Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this ok? Synchronized( thread ), then thread=null in the synch block

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.

like image 601
bobobobo Avatar asked Nov 19 '10 16:11

bobobobo


People also ask

Does synchronized block thread?

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.

Which is more efficient synchronized method or synchronized 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.

Why must wait () always be in synchronized block?

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.

What happens when synchronized is invoked?

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.


2 Answers

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.

like image 152
Jon Skeet Avatar answered Oct 27 '22 00:10

Jon Skeet


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.

like image 25
Sean Patrick Floyd Avatar answered Oct 26 '22 23:10

Sean Patrick Floyd