This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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


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: 20029
    
  44

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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: synchronization problem
 
It's not a secret anymore!