Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

implementing producer consumer with singleton

 
sahana mithra
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I am new to the concept of singleton. I have a text file and whenever i update this file, producer should be notified and many consumers say 5 threads try to access this. Only one thread should be able to read this file and that should write to the another text file. When second thread tries to access the same file at the same time, it should be said that thread 1 is accessing.


Please help me on how to approach this kind of scenario.
It would be easy for me to understand if some one can code it.
Thanks in advance
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't understand your needs completely from your description and as such I'm not exactly sure the producer-consumer pattern ideally fits your needs. If this does not sound right, please come back to clarify.

Anyway, this pattern can be rather easily implemented in Java by using one of the synchronized queues in the java.util.concurrent package, such as ArrayBlockingQueue. All the hard synchronizing work is already implemented in these queue classes. You'll create one of these (read their javadoc and choose the one that fits your needs best). Then let producer threads put work items into that queue and consumer threads retrieve and process these items. This design ensures that only one consumer will start processing the work item (probably a file in your case) and therefore you don't need to further coordinate worker threads not to compete for work on a single file.

The queue could be part of a singleton, so that all threads share the same instance (this is naturally very important). Googling up singleton design pattern brings up many materials on this; try some of them, as conceptually singleton pattern belongs to the easier ones.
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sahana mithra wrote:I have a text file and whenever i update this file, producer should be notified

In producer-consumer model, producer notifies the consumers (i.e. consumers are notified, not the other way round).

Secondly, the behavior you want can be simply done by synchronization. I don't understand why and how you reached the conclusion that you need singleton to fix this thing.

I hope this helps.
 
claudiu cosar
Greenhorn
Posts: 1
Java Oracle Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try using BlockingQueue from util.concurrent pkg for your producer consumer pattern.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic