Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How the Synchronization works

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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

 
Vepa Sritej
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic