在 POST 方法之外创建方法是 servlet

Create method outside POST method is servlet

您好,我在 servlet 中创建了一个私有方法。 该方法将从 post 方法调用。我的问题是,它会是线程安全的吗 因为它会被许多用户通过 ajax 调用?

protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    callPrivateMethod();
}

private static void callPrivateMethod(){
}

只要 callPrivateMethod() 是线程安全的,即它不使用 class 成员变量,就可以了。

不,您的私有方法不是线程安全的,因为 doPost 在 servlet 中不是线程安全的。

它是静态方法,在你的情况下(无参数)以不可变对象作为参数是线程安全的

Servlet 应该是无状态的。但是,如果您需要使用 class 成员或任何其他线程不安全的元素,您总是可以使用 "synchronized" 句子。

servlet 在加载时仅实例化一次。如果你想让 call to call Private Method() 线程安全,你可以把它放在一个同步块中。

private Object mutex = new Object();

protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
   synchronized (mutex){
    callPrivateMethod();
   }
}

private static void callPrivateMethod(){
}