This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
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
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.