Static method behavior in multi-threaded environment in java

namalfernandolk picture namalfernandolk · Jun 27, 2013 · Viewed 56.7k times · Source

There's a simple stupid question that bother me and make several arguments in my mind. I want to throw out all the doubts about below questions.

class Clstest{

    public static String testStaticMethod(String inFileStr) {

        // section 0

        // section 1

        // do something with inFileStr

        // section 2

        // section 3

        return inFileStr;

    }

}

Let's assume there are five threads are each executing a call to Clstest.testStaticMethod("arg-n") at the same time.

Thread 1 calls Clstest.testStaticMethod("arg-1").

When thread 1 is in the section 1, thread 2 calls Clstest.testStaticMethod("arg-2").

Then what will happen to Thread 1? Will it go to sleep state?

When Thread 1 got the chance will it resume the execution from section 1 where it was paused?

How it happens when there's one Clstest.testStaticMethod and same Clstest.testStaticMethod is shared between all five threads?

Is there any possibility to interchange the inFileStr sent by multiple threads?

Answer

selig picture selig · Jun 27, 2013

Hans Passant's answer is good. But I thought I would try and explain at a slightly more simple level for anybody who comes across this and is newish to Java. Here goes..

Memory in java is split up into two kinds - the heap and the stacks. The heap is where all the objects live and the stacks are where the threads do their work. Each thread has its own stack and can't access each others stacks. Each thread also has a pointer into the code which points to the bit of code they're currently running.

When a thread starts running a new method it saves the arguments and local variables in that method on its own stack. Some of these values might be pointers to objects on the heap. If two threads are running the same method at the same time they will both have their code pointers pointing at that method and have their own copies of arguments and local variables on their stacks. They will only interfere with each other if the things on their stacks point to the same objects on the heap. In which case all sorts of things might happen. But as Hans points out, Strings are immutable (cannot be changed) so we're safe if this is the only object being "shared".

So many threads can be running the same method. They might not be running at the same time - it depends how many cores you have on your machine as the JVM maps Java threads to OS threads, which are scheduled onto hardware threads. You therefore have little control over the way these threads interleave without using complex synchronisation mechanisms.

Note that sleeping is something a thread does to itself.