• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

synchronizing on public member of type ArrayList<String>

 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Siva for the nice explanation.
 
reply
    Bookmark Topic Watch Topic
  • New Topic