aspose file tools*
The moose likes Threads and Synchronization and the fly likes synchronization problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronization problem" Watch "synchronization problem" New topic
Author

synchronization problem

Ryan Raina
Greenhorn

Joined: Jun 16, 2010
Posts: 28
hello friends please see the code below..Here I am using executors for multi-threading....

My problem is that I am acquiring lock on the list so that in consumer thread only one thread should be allowed to remove the element from list...but it has a drawback I cannot add an item in same list in producer as it might happen that list lock in taken by one of the consumer thread...
so I want that producer should be able to add in the list but only one consumer should be able to remove from it.. any suggestions...please note that there are 3 consumer threads and 1 producer thread



[Added code tags - see UseCodeTags for details]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Ryan Raina wrote:hello friends please see the code below..Here I am using executors for multi-threading....

My problem is that I am acquiring lock on the list so that in consumer thread only one thread should be allowed to remove the element from list...but it has a drawback I cannot add an item in same list in producer as it might happen that list lock in taken by one of the consumer thread...
so I want that producer should be able to add in the list but only one consumer should be able to remove from it.. any suggestions...please note that there are 3 consumer threads and 1 producer thread


Well.... One option is to *not* grab the lock on the list (for the whole operation). Just use the Collections.synchronizedList() method to return a thread safe list, which will allow the producer and consumers to both work on the list concurrently. Of course, this option will not stop the consumers from working concurrently. To solve that you can use the same technique, but with a different object. Have the consumers grab the lock of a different object -- that the producer will not grab. Only one consumer will own the lock, and it will work concurrently with the producer(s).

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ryan Raina
Greenhorn

Joined: Jun 16, 2010
Posts: 28
Thanks for you help !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronization problem