MarioP MarioP - 1 month ago 7
Java Question

Multiple Threads calling static helper method

I have a web application running on Tomcat.

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;
}
}


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()
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?

Answer

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.