Multiple Threads calling static helper method

前端 未结 7 817
孤街浪徒
孤街浪徒 2021-02-08 03:05

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

7条回答
  •  时光取名叫无心
    2021-02-08 03:42

    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.

提交回复
热议问题