Home » Concurrency
Archiv der Kategorie: Concurrency
Static Method and Concurrency (MultyThrading) / Java Memory Model
Clarification by user Selig on stackoverflow:
„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.“
Trap: Multithreading: Create Thread but it has no context
Often a newly created Thread has no access to some context because this is defined in the environment (e.g. Server Container) as being thread local.