File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronizing Code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronizing Code" Watch "Synchronizing Code" New topic

Synchronizing Code

Anuj Troy
Ranch Hand

Joined: Apr 07, 2005
Posts: 30
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?

SCJP 1.4, SCWCD 1.4
your eyes cannot see what your mind does not know
Sanju Thomas
Ranch Hand

Joined: Dec 29, 2004
Posts: 243
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.

Joe Sondow
Ranch Hand

Joined: Apr 10, 2005
Posts: 195
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:

SCJA 1.0 (98%), SCJP 1.4 (98%)
I agree. Here's the link:
subject: Synchronizing Code
It's not a secret anymore!