Concurrent access to static methods

2019-01-23 05:03发布

问题:

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?

回答1:

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.



回答2:

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).



回答3:

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.



回答4:

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

}


回答5:

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