Multiple Threads calling static helper method Multiple Threads calling static helper method multithreading multithreading

Multiple Threads calling static helper method


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?

Yes, and yes.

do i have to make the whole static functions synchronized

That will work.

or just the block where Helper.obj is used

That will also work.

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

Use a 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.


You should capture the calculations in a class, and create an instance of the class for each thread. What you have now is not threadsafe, as you are aware, and to make it threadsafe you will have to synchronize on the static resource/the methods that access that static resource, which will cause blocking.

Note that there are patterns to help you with this. You can use the strategy pattern (in its canonical form, the strategy must be chosen at runtime, which might or might not apply here) or a variant. Just create a class for each calculation with an execute method (and an interface that has the method), and pass a context object to execute. The context holds all the state of the calculation. One strategy instance per thread, with its context, and you shouldn't have any issues.


If you don't have to share it you can make it thread local, then it doesn't have to be thread safe.

public class Helper {private static final ThreadLocal<SomeObject> obj = new ThreadLocal<SomeObject>() {    public SomeObject initialValue() {        return enw SomeObject();    }}public static void changeMember() {    Helper.obj.get().changeValue();}public static String readMember() {    Helper.obj.get().readValue();}}