File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronizing on public member of type ArrayList<String> 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 "synchronizing on public member of type ArrayList<String>" Watch "synchronizing on public member of type ArrayList<String>" New topic
Author

synchronizing on public member of type ArrayList<String>

Shashank Rudra
Ranch Hand

Joined: Mar 26, 2009
Posts: 131
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.


Programmer Analyst || J2EE web development/design
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
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.


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
Shashank Rudra
Ranch Hand

Joined: Mar 26, 2009
Posts: 131
thanks Siva for the nice explanation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronizing on public member of type ArrayList<String>