Can a thread lose control after calling a method but before the first instruction of the method?

Tags: , ,



I need to record the exact order in which a method is called by various threads in Java. I’m supposed to use an object timeProvider which returns non-decreasing long integers. The solution I have come up with is:

public synchronized void method() {
    long order = timeProvider.getTime();
    // some stuff that can be run concurrently
}

Of course it is a bottleneck because the only place I need to use synchronization is the first line. So I’m wondering whether it would be safe to change the code to:

 public void method() {
    //(1)
    synchronized (timeProvider) {
        long order = timeProvider.getTime();
    }
    // some stuff that can be run concurrently
}

But in this version I’m worried that the running thread A could lose control in the place marked as (1) – inside the method but before the first instruction. Then another thread B could call the method after A has called it and execute the first intruction and as a result the order from the timeProvider would be recorded wrong. Is this possible?

Answer

Yes: The thread executing code inside a method can be halted before the first line.

It might appear as if nothing happens by just calling the method, but actually much happens, especially the creation of the stack frame.



Source: stackoverflow