Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization problem

 
Ryan Raina
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21202
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ryan Raina
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for you help !!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic