[Logo]
Forums Register Login
Synchronizing Code
hii i have a doubt in K&b book page 523

last paragraph..

"When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired"

what does this mean?

can someone explain me the working of synchronized blocks too?
thanks
regards
anuj
To execute a synchronized method, the invoking object should have the lock on that object.

see what is sun telling about the lock ..

"Within a program, the code segments that access the same object from separate, concurrent threads are called critical sections. A critical section can be a block or a method and is identified with the synchronized keyword. The Java platform associates a lock with every object and the lock is acquired upon entering a critical section."

That means when you invoke synchronized method, you should have mutex or mutually exclusive lock on that object, other object can invoke that method only after you relase the lock on that object. But other objects can invoke non-synchronized method on the same object concurrently.

Synchronized block will reduce the domain synchronization, The advantage in instead synchronizing the whole method you can synchronize a small part of the method.


 
Originally posted by Anuj Soumya:
"When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired"

what does this mean?


What they mean is that in order to execute code within a synchronized method, you need the lock on the this object, which is the object you called the method on.

Here's an example:



The go() method is synchronized, which means it needs the lock on the this object in order to execute. The this object in the go() method is the mySynch object in the main() method, on which I called go().

This next example looks different but it will behave exactly the same way as my first example because all the statements in the go() method are inside a synchronized(this) block:

Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Dec 15, 2017 05:12:32.