• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronizing on public member of type ArrayList<String>

 
Shashank Rudra
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

Here is the code where I am trying to synchronize access to the public instance . But from the output I am not able to figure out the difference than when I am commenting out the
synchronized(lst){
-line from the source.

Please help me understand the use of synchronizing on lst and the difference it is making. Thanks in advance for help.

 
Siva Masilamani
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronizing lst on your code does not stop you add or delete the element in the list in order,

because both the operations (add and delete method are not atomic in your case.)

Think like this

Lets say there are two thread A and B.

Thread A tries to add the element to List in your case it will add Ram first then it releases the lock when the method completes and go to next line in the run method try to call the add method again ...during which time thread B can get the lock lst object and never give a chance to thread A and add all the elements to the lst and when thread B calls display method it will also display the Ram added by Thread A so in this case Ram will be displayed twice.

This kind of situation can happen in your program between each thread.

So in order to avoid this problem all the operation on the lst should be atomic.

This could work

inside run metod



now this will work the way we want as both the add and delete operation are atomic.
hope this helps you.
 
Shashank Rudra
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Siva for the nice explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic