The Internal Java Memory Model for Thread Stacks - java

I was reading article about Internal Java Memory Model.
There is one point I want to ask about :
Each thread running in the Java virtual machine has its own thread stack. The thread stack contains information about what methods the thread has called to reach the current point of execution.
Why each thread needs to save information about what methods has been executed(!) ? If it's related to context-switching then (if I'm not wrong) thread must save the information about method which is currently being executed.
What is actual need for save already executed method's information?

This is referring to the currently active methods. Note that there can be several methods in a thread active at the same time (A calls B calls C, ...). The stack does not contain information about methods that have already completed.

I think rephrasing this paragraph makes it clearer and easier to understand:
Each thread running in the Java virtual machine allocates some memory for its call stack. The call stack contains information about what methods the thread has called to reach the current point of execution.

Related

Resuming a thread on another machine from the current JVM stack

On the JVM, I run a thread and at some point I block it. If I persist the JVM thread stack at this point, and all the objects I explicitly created in my code that it refers to (I assume they are all serializable), will it be feasible to use this data to resume the thread on another JVM?
Are there any frameworks/libraries out there that can help me or get me closer to doing such a thing?

Difference between "call stack" and "thread stack"

Is there a semantic difference between the terms call stack and thread stack, in Java multithreading?
Each thread has its own call stack, "call stack" and "thread stack" are the same thing. Calling it a "thread stack" just emphasizes that the call stack is specific to the thread.
Bill Venners calls this the Java stack:
When a new thread is launched, the Java virtual machine creates a new Java stack for the thread. As mentioned earlier, a Java stack stores a thread's state in discrete frames. The Java virtual machine only performs two operations directly on Java Stacks: it pushes and pops frames.
The method that is currently being executed by a thread is the thread's current method. The stack frame for the current method is the current frame. The class in which the current method is defined is called the current class, and the current class's constant pool is the current constant pool. As it executes a method, the Java virtual machine keeps track of the current class and current constant pool. When the virtual machine encounters instructions that operate on data stored in the stack frame, it performs those operations on the current frame.
When a thread invokes a Java method, the virtual machine creates and pushes a new frame onto the thread's Java stack. This new frame then becomes the current frame. As the method executes, it uses the frame to store parameters, local variables, intermediate computations, and other data.
A call stack is a stack data structure that stores information about the active subroutines of a computer program.
What you're calling a thread stackis what i assume is the private stack of a thread.
These two things are essentially the same. They are both stack data structures.
A thread's stack is used to store the location of function calls in order to allow return statements to return to the correct location
Since there usually is only one important call stack, it is what people refer to as the stack.
Here is information about the stack.
Here is information about Stack-based memory allocation.
Each thread has its own stack, each method call uses a new area of that stack. This means when a method calls itself (recursion), it will have a new set of local variables.
When FileWriter throws an IOException, the runtime system immediately stops executing the try block; method calls being executed are not completed. The runtime system then starts searching at the top of the method call stack for an appropriate exception handler.
In this example, when the IOException occurs, the FileWriter constructor is at the top of the call stack. However, the FileWriter constructor doesn't have an appropriate exception handler, so the runtime system checks the next method — the writeList method — in the method call stack. The writeList method has two exception handlers: one for IOException and one for IndexOutOfBoundsException.

Where is Thread Object created? Stack or Heap?

When I say something like:
Thread t1 = new Thread();
does it create it on a heap or a stack?
There is no way to allocate objects on the stack in Java.
The stack can only hold references and primitives, and only for local variables.
Note that starting a thread will create a new stack for that thread.
Thread t1 = new Thread();
tl;dr This allocates object i.e. t1 in heap.
As each new thread comes into existence, it gets its own pc register (program counter) and Java stack. If the thread is executing a Java method (not a native method), the value of the pc register indicates the next instruction to execute. A thread's Java stack stores the state of Java (not native) method invocations for the thread. The state of a Java method invocation includes its local variables, the parameters with which it was invoked, its return value (if any), and intermediate calculations. The state of native method invocations is stored in an implementation-dependent way in native method stacks, as well as possibly in registers or other implementation-dependent memory areas.
The Java stack is composed of stack frames (or frames). A stack frame contains the state of one Java method invocation. When a thread invokes a method, the Java virtual machine pushes a new frame onto that thread's Java stack. When the method completes, the virtual machine pops and discards the frame for that method.
The Java virtual machine has no registers to hold intermediate data values. The instruction set uses the Java stack for storage of intermediate data values.
Figure shows a snapshot of a virtual machine instance in which three threads are executing. At the instant of the snapshot, threads one and two are executing Java methods. Thread three is executing a native method. It also shows of the memory areas the Java virtual machine creates for each thread, these areas are private to the owning thread. No thread can access the pc register or Java stack of another thread.
In Java 8, using Escape Analysis objects can be created on the stack. This occurs when an object is detected as not escaping the current method (after inlining has been performed) Note: this optimisation is available in Java 7, but I don't think it worked as well.
However, as soon as you call start() it will escape the current method so it must be placed on the heap.
When I say something like:
Thread t1 = new Thread();
does it create it on a heap or a stack?
It could place it on the stack, provided you don't use it to create a real thread. i.e. if you so
Thread t1 = new Thread(runnable);
t1.start();
It has to place it on the heap.

Static method behavior in multi-threaded environment in java

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?
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.
Will it go to sleep state?
No, running a thread does not affect other threads as long as they don't intentionally synchronize with each other. If you have more than one processor core, all recent machines do, those threads are likely to execute at the exact same time. That gets to be bit less likely when you start 5 threads since your machine might not have enough cores. The operating system is forced to choose between them, giving them each some time to run. The job of the thread scheduler. A thread will then not be in a "sleep" state, it is simply paused and waiting for the thread scheduler to give it a chance to run. It will resume where it was interrupted by the scheduler.
Is there any possibility to interchange the inFileStr sent by multiple threads?
There is no such possibility, threads have their own stack so any method argument and local variable will be unique for each thread. Using a string furthermore guarantees that these threads cannot interfere with each other since strings are immutable.
There's no such guarantee if the argument is a reference to another kind of mutable object. Or if the method itself uses variables that are static or references to objects on the heap. Synchronization is required when a thread modifies the object and another thread reads it. The lock keyword in the C# language is the boilerplate way to implement such required synchronization. The fact that the method is static does not mean such synchronization is never required. Just less likely since you don't have to worry about threads accessing the same object (sharing this).

multi thread safe class

Question:
A) Write a thread safe class with methods doA(), doB(), doC(). Each of these methods must report the method name, time of invocation, and calling thread name.
B) Write a multi threaded driver that spawns 4 threads, and each thread must call every method – doA(), doB(), doC() – 10 times
I am assuming that it means doA(), doB(), doC() must be safe. But none of them mutate the shared state within the object, they just read object state such as method name, thread name and running time. So, do I need synchronize each method? For the counter within each thread, it is not shared.
I am a little confused here, which of state of the object needs protection?
Edit:
Do we need a mechanism to assure the running sequence of doA(), doB(), doC()? I dont think so.
From the sounds of it, your object will have no mutable state at all. Objects without mutable state are usually (not always, but usually) thread-safe without any additional locking. Of course, if there's additional requirements that do imply mutable state, the answer would be different.
How are you reporting the information? If it's to a console or any other resource that's independent of thread, there's your shared "state". Sort of. Some mechanisms for writing to a console will buffer lines, so you may not have problems, but over multiple lines you'll have to make sure that two don't write to it at the same time. For example, if I were to print:
Thread: A
Method: doA
Running Time: 4.6s
Then I'd want to make sure another thread doesn't start half-way through. Otherwise you may end up with something like this:
Thread: A
Thread: B
Method: doB
Running Time: 4.6s
Method: doA
Running Time: 3.2s
Not so helpful.

Categories

Resources