I see this:
// thread is a member of this class
synchronized( this.thread )
{
this.thread.running = false;
this.thread.notifyAll(); // Wake up anything that was .waiting() on
// the thread
this.thread = null; // kill this thread reference.
// can you do that in a synchronized block?
}
Is it ok to set the thread=null
while still keeping a lock on it?
I found this nugget in a bit of BB code.
All synchronized blocks synchronize on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared resource. The system performance may degrade because of the slower working of synchronized keyword. Java synchronized block is more efficient than Java synchronized method.
As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
Yes, that's fine. The synchronized statement will take a copy of the reference that it's locking on, and use the copy to work out what to unlock at the end.
Section 14.19 of the Java Language Specification isn't actually clear about this, but it does state that the expression is evaluated at the start - and doesn't mention evaluating it again later on.
There's a difference:
synchronized( this.thread )
You are synchronizing on the Object the field this.thread
points to
this.thread = null;
You are reassigning the field. You are not doing anything with the object you referenced above, so the lock is still valid.
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