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?
You can check it yourself:
all method invocations from separate threads in java are concurrent by default.
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.
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 (sincethis
doesn't exist for static methods).Answering exactly your question:
You need to add the
synchronized
modifier if you are working with objects that require concurrent access.