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 How the Synchronization works 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 "How the Synchronization works" Watch "How the Synchronization works" New topic

How the Synchronization works

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 481
I am trying to understand how the locks will work in synchronization. It seems like theoretically I got how locks would work. But I couldn�t get how the synchronization code works in a coding way.

We have started three threads on one object (sb).Can anyone please explain the synchronization block for me?
prarthana reddy
Ranch Hand

Joined: Jul 24, 2006
Posts: 48
What happens when you compile the code ? Synchronization has to be done on an object not on an instance variable ( letter ---line 9 ) .
Surendra Kumar
Ranch Hand

Joined: Jul 04, 2006
Posts: 236
Hi Prarthana,

synchronization can be done on any object, and in this code the variable 'letter' is an object of StringBuffer.
Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 481
When run the code (without line -9 and line-18) also the output is same like with synchronization on. Can anyone please explain execution steps of synchronized block and without that?
Nilesh Patel
Ranch Hand

Joined: Feb 02, 2006
Posts: 91
when you run code without synchronization block ( w/o line 9 & 18) it will give the series of "A" in output or my be depend on platform...

if you use synchronozation block output will be series of "A" "B" "C"

Means w/o sync all three thread use letter object same time and using sync block on letter object it is use one by one...

you can verift it using below line on line No. 11

Nilesh Patel
SCJP 1.5 - 87%
Vepa Sritej
Ranch Hand

Joined: Jul 31, 2006
Posts: 42
In this case, all the three threads have the same StringBuffer Instance. That is their respective letter references point to the same StringBuffer object so synchronisation works.Because lock is obtained on the same object.

Try changing the constructor code to
public JavaThread(StringBuffer b)
sb= new StringBuffer(b.toString());
In this case synchronisation will not occur as each thread has its own sb object.

tej<br /> <br />SCJP 1.5 --75%<br />SCWCD --89%<br />SCBCD/Web Services!! Yet to Decide
I agree. Here's the link:
subject: How the Synchronization works
It's not a secret anymore!