This week's book giveaways are in the iOS and Features new in Java 8 forums.
We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronized block of code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Barcodes with iOS this week in the iOS forum
or Core Java for the Impatient in the Java 8 forum!

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronized block of code" Watch "Synchronized block of code" New topic

Synchronized block of code

Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200
I got this code from K & B:

What is the logic behind the synchronization on the letter object? Can you put just any object inside the synchronization parentheses just to satisfy the requirement of synchronizing a block of code? I'm trying to learn the synchronization concepts of threads and I'm looking for a clear cut explanation on this concept.

Be Afraid...Be very Afraid...
Henry Wong

Joined: Sep 28, 2004
Posts: 19302

Yes, you can practically use any object as the synchronization lock... but there is a reason why the stringbuffer was chosen. It is the same instance with all three threads, and synchronization was done to prevent the threads from stepping on each other.

So if you use any other object, you have to make sure that the three threads are using the same instance / object.

[ April 24, 2005: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: Synchronized block of code