27

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?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
user1226058
  • 403
  • 1
  • 6
  • 12

6 Answers6

30

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.

user1156544
  • 1,725
  • 2
  • 25
  • 51
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
  • 2
    You need to add `synchronized` whenever you want to prevent concurrent execution. Whether fields or methods are `static` is irrelevant to this consideration. – Ted Hopp Jan 02 '13 at 17:51
  • @TedHopp, thanks, I know. Speaking about `synchronized' I meant that problems with concurrency could appear only in case, if method will have a deal with some static (in this particular case) fields. – Andremoniy Jan 02 '13 at 17:53
  • 1
    @andremoniy. can you please explain how static methods executes concurrently on mulithread. we have only one copy of static method in class area of jvm. how it works parallely. – vijaya kumar Mar 23 '15 at 13:42
  • 7
    @vijayakumar Methods are just sets of instructions. When you call a static method from 2 different threads, both of those threads are simply given identical instructions. This is why they work concurrently, and don't have to "wait in line." Thread-1 doesn't necessarily know, or care, if Thread-2 is following the same instructions (unless they access shared data, which is where concurrency problems can occur.) – arkon Jul 18 '15 at 11:54
21

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.

ben75
  • 29,217
  • 10
  • 88
  • 134
  • 4
    I think this line is what trips up more people "If your method only use local variables you won't have concurrency issues.". I think this should get more upvotes! – D-Klotz May 31 '17 at 13:38
  • @ben75 how about method parameter? one thread can override the parameter value of another at concurrency level. – Zaw Than oo Jul 25 '22 at 11:29
15

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

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • +1 It's not clear that you need to "avoid concurrent execution" but if you do, you need some sort of locking. – Peter Lawrey Jan 02 '13 at 17:53
  • I'm not the downvoter, but I'd like to notice, that the question of this topic isn't about how he can prevent concurrency execution. He just asks about: what will be... if... – Andremoniy Jan 02 '13 at 17:57
  • @PeterLawrey- Ah. I see now how my first sentence could have been interpreted as stating that concurrent execution needed to be avoided. I meant it as conditional. I'll rephrase. – Ted Hopp Jan 02 '13 at 17:57
  • @Andremoniy - I rephrased my first sentence to more clearly express what I was trying to say. – Ted Hopp Jan 02 '13 at 17:59
8

I see a lot of answers but none really pointing out the reason.

So this can be thought like this,
Whenever a thread is created, it is created with its own stack (I guess the size of the stack at the time of creation is ~2MB). So any execution that happens actually happens within the context of this thread stack.
Any variable that is created lives in the heap but it's reference lives in the stack with the exceptions being static variables which do not live in the thread stack.

Any function call you make is actually pushed onto the thread stack, be it static or non-static. Since the complete method was pushed onto the stack, any variable creation that takes place lives within the stack (again exceptions being static variables) and only accessible to one thread.

So all the methods are thread safe until they change the state of some static variable.

swayamraina
  • 2,958
  • 26
  • 28
3

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

}
Raffaele
  • 20,627
  • 6
  • 47
  • 86
1

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

jtahlborn
  • 52,909
  • 5
  • 76
  • 118