As I understand it, internally obj.join()
calls wait()
. This means that join()
always releases the lock (because wait()
always releases the lock after being called).
The API doc explains:
This implementation uses a loop of
this.wait
calls conditioned onthis.isAlive
. As a thread terminates thethis.notifyAll
method is invoked. It is recommended that applications not usewait
,notify
, ornotifyAll
onThread
instances.
People here on SO say that join()
does not release any lock because the API does not mention it explicitly. But this logic seems strange to me.
Here is the main logic from join()
's code:
while (isAlive()) {
wait(0);
}
This site further adds to the confusion (I think they are mistaken):
3) The third difference between the
wait()
andjoin()
methods is that when a thread calls thewait()
method it releases any lock held for the object on whichwait()
is called, but calling thejoin()
method doesn't release any monitor or lock.
wait
releases the monitor held on the object which wait
is invoked on, but not any other monitors.
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits [...].
In other words, given the following:
synchronized (a) {
synchronized (b) {
b.wait();
}
}
At b.wait()
, the current thread releases b
's monitor, but not a
's monitor.
If t.join()
is implemented using t.wait()
internally, then t
's monitor is released while waiting, but not any other monitor.
This join
implementation is a case of leaky abstraction, by the way. If Thread
used a private final Object monitor;
to wait on instead, we could say that join
released no monitors, even if it used wait
internally without us knowing. There would be no reason to document the implementation detail of using wait
, because the monitor would be inaccessible to us, so we would not need to know about it.
The reason that we know join
uses wait
internally is that the people who originally wrote the method chose a monitor which is accessible to us. This created the need to reveal the implementation details. join
is not really supposed to release monitors from our perspective, just wait for a thread to complete, but an implementation was chosen which required us to know more about it than we should.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With