Greetings everyone
Once again I am having some trouble understanding some concepts. From Kathy's and Bert's book (SJCP 6) , Chapter 9 - Threads- , pages 735, 736 and 737 . These are the things I do not get and would appreciate a practical example . (What a tough chapter)
First one: (Page 736)
A thread can acquire more than one lock. For example, a thread can enter a
synchronized method, thus acquiring a lock, and then immediately invoke
a synchronized method on a different object, thus acquiring that lock as
well. As the stack unwinds, locks are released again. Also, if a thread acquires
a lock and then attempts to call a synchronized method on that same
object, no problem. The JVM knows that this thread already has the lock for
this object, so the thread is free to call other synchronized methods on the
same object, using the lock the thread already has.
:/ does anyone feel like writing a code example , please?.
Second one:
The way you can change a synchronized method to a synchronized code block: (Page 736 to 737 )
When you synchronize a method, the object used to invoke the method is the
object whose lock must be acquired. But when you synchronize a block of code, you
specify which object's lock you want to use as the lock, so you could, for example,
use some third-party object as the lock for this piece of code. That gives you the
ability to have more than one lock for code synchronization within a single object.
Or you can synchronize on the current instance (this) as in the code above.
Since that's the same instance that synchronized methods lock on, it means that
you could always replace a synchronized method with a non-synchronized
method containing a synchronized block. In other words, this:
is equivalent to this:
I have a feeling exam will be playing with this somehow way often than I think.
Basically , does it mean I can change synchronized method to just a synchronized block of code , in order to avoid (if necessary) get whole method synchronized.
Can we do this for any synchronized method?
Also, in that example, synchronized(this) ...looks like you are synchronizing "this" object rather than code block (and no idea how to determine which
thread object would be the one holding the lock in this example) . Anyone can provide a better practical example?
I do understand lock as hmm kind of "state" perhaps?
Thank you in advance