多个线程调用静态帮助器方法 [英] Multiple Threads calling static helper method

查看:113
本文介绍了多个线程调用静态帮助器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Tomcat上运行了一个Web应用程序。

I have a web application running on Tomcat.

需要在Web应用程序的多个位置进行多项计算。我可以将这些计算用于静态辅助函数吗?如果服务器有足够的处理器内核,那么对该静态函数的多次调用(由多个不同servlet的请求产生)是否可以并行运行?或者一个请求是否必须等到另一个请求完成调用?

There are several calculations that need to be done on multiple places in the web application. Can I make those calculations static helper functions? If the server has enough processor cores, can multiple calls to that static function (resulting from multiple requests to different servlets) run parallel? Or does one request have to wait until the other request finished the call?

public class Helper {
    public static void doSomething(int arg1, int arg2) {
        // do something with the args
        return val;
    }
}

如果并行呼叫:
I有另一个带有静态函数的辅助类,但是这个类包含一个静态函数中使用的私有静态成员。如何确保函数是线程安全的?

if the calls run parallel: I have another helper class with static functions, but this class contains a private static member which is used in the static functions. How can I make sure that the functions are thread-safe?

public class Helper {

    private static SomeObject obj;

    public static void changeMember() {
        Helper.obj.changeValue();
    }

    public static String readMember() {
        Helper.obj.readValue();
    }

}

changeValue () readValue()读取/更改 Helper.obj 的相同成员变量。我是否必须使整个静态函数同步,或者仅使用 Helper.obj 的块?如果我应该使用一个块,我应该使用什么对象来锁定它?

changeValue() and readValue() read/change the same member variable of Helper.obj. Do I have to make the whole static functions synchronized, or just the block where Helper.obj is used? If I should use a block, what object should I use to lock it?

推荐答案


我可以使那些计算静态辅助函数?如果服务器有足够的处理器内核,那么对该静态函数的多次调用(由对多个不同servlet的多个请求产生)是否并行运行?

can i make those calculations static helper functions? if the server has enough processor cores, can multiple calls to that static function (resulting from multiple requests to different servlets) run parallel?

是的,是的。


我是否必须使整个静态函数同步

do i have to make the whole static functions synchronized

这将有效。


或只是 Helper.obj的块使用

这也可以。

如果我应该使用一个块,我应该使用什么对象来锁定它?

if i should use a block, what object should i use to lock it?

使用 static Object

public class Helper {

    private static SomeObject obj;
    private static final Object mutex = new Object();

    public static void changeMember() {
        synchronized (mutex) {
            obj.changeValue();
        }
    }

    public static String readMember() {
        synchronized (mutex) {
            obj.readValue();
        }
    }
}






但理想情况下,您可以将辅助类编写为不可变(无状态或其他),这样您就不必担心线程安全。


Ideally, though, you'd write the helper class to be immutable (stateless or otherwise) so that you just don't have to worry about thread safety.

这篇关于多个线程调用静态帮助器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆