Concurrent access to static methods

2019-01-23 04:48发布

I have a static method with the following signature:

public static List<ResultObjects> processRequest(RequestObject req){
  // process the request object and return the results.
}

What happens when there are multiple calls made to the above method concurrently? Will the requests be handled concurrently or one after the other?

5条回答
冷血范
2楼-- · 2019-01-23 05:14

You can check it yourself:

public class ConcurrentStatic {

    public static void main(String[] args) {
        for (String name: new String[] {"Foo", "Bar", "Baz"}) {
            new Thread(getRunnable(name)).start();
        }
    }

    public static Runnable getRunnable(final String name) {
        return new Runnable() {
            public void run() {
                longTask(name);
            }
        };
    }

    public static void longTask(String label) {
        System.out.println(label + ": start");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(label + ": end");
    }

}
查看更多
三岁会撩人
3楼-- · 2019-01-23 05:14

all method invocations from separate threads in java are concurrent by default.

查看更多
贪生不怕死
4楼-- · 2019-01-23 05:26

All your calls to the method will be executed concurrently... but:

You may have concurrency issue (and being in non thread-safe situation) as soon as the code of your static method modify static variables. And in this case, you can declare your method as synchronized

If your method only use local variables you won't have concurrency issues.

查看更多
SAY GOODBYE
5楼-- · 2019-01-23 05:27

If you need to avoid concurrent execution, you need to explicitly synchronize. The fact that the method is static has nothing to do with it. If you declare the method itself to be synchronized, then the synchronization will be on the class object. Otherwise you will need to synchronize on some static object (since this doesn't exist for static methods).

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-23 05:38

Answering exactly your question:

  1. Method will be executed concurrently (multiple times in the same time if you have several threads).
  2. Requests will be handled concurrently.

You need to add the synchronized modifier if you are working with objects that require concurrent access.

查看更多
登录 后发表回答