Concurrent access to a utility static method

Viewed 4030

We have a scenario in which several threads call a static method like the following one:

public static boolean isEmpty(final String s) {
    return s == null || s.length() < 1;
}

Could it cause a problem of inconsistence if 100 threads call it?

5 Answers

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.

Related