Question

What happens when two threads call the same static method at the same time? For example:

public static String someMethod(){

    //some logic, can take about 1 second to process

    return new String(result);
}

First thread calls someMethod() now. Second thread calls someMethod() 0.5 seconds from now (first thread still processing the data).

I know that someMethod() can be synchronized. But what will happen if it's not synchronized?

Was it helpful?

Solution 2

It depends on whether your method changes outside state.

static long i = 0l;
public static String someMethod(){
    String accm = "";
    for(;i < Integer.MAX_VALUE*20/*Just to make sure word tearing occurs*/; i++)
        accm += i
    return accm;
}

Will cause problems:

  • Longs are not guaranteed to be set atomically, so they might be 'torn' (Spec)
  • ++ is not an atomic operation. It is exactly the same as {int n = i; i = i + 1; return n}
    • i = i + 1 is also not atomic, if it changes in the middle, some values will be repeated
    • The return of n might be stale

But if i is a local variable, there will be no problems. As long as any outside state is guaranteed to be immutable while it is being read, there can never be any problems.

OTHER TIPS

When a method is called, the JVM creates a stack frame for the call in the executing thread. This frame contains all of the local variables declared in the method. In the case of any method, static or otherwise, that doesn't access fields, each execution proceeds completely independently on each thread. If the method uses parameters in its calculation, these parameters are also located in the stack frame, and multiple calls don't interfere with each other.

The fact the method is static is irrelevant. They question should be what state variables are being manipulated by the code in question.

  • If no members of any instance/class are read/written, then there should be no problem.
  • In the case of write operations, synchronization of some kind is needed
  • If there are only reads, it doesn't necessarily mean the method is well synchronized. It depends on how the data is being written and by which thread. If for example the code reads V which is protected by a monitor M during the write operation, then the reads of V must synchronize on the same monitor as well.

If the two statements are executed in separate threads, there's no guarantee that the first thread changes will be visible to the second thread unless you establish a happens-before relationship between these two statements by synchronizing someMethod() using a given synchronization strategy. In other words, your logic can give unexpected and unpredictable results if you are writing to the same variable(s) and then reading from two threads simultaneously.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top