Reputation: 43
I would like to know an example for singleton pattern like 5 threads trying to access a single text file.At a time only one should be able to read that and that in turn creates a file displaying date, thread name, contents.
Textfile- source
A B C D
Text file - details of the threads and contents
Date & Time Thread name Contents
mar 25 10.02 a A B C D
mar 25 10.05 b A B C D
Thanks
Upvotes: 0
Views: 541
Reputation: 22171
I disagree with @Peter Mensik.
Indeed, in a multithreaded environnement, the double-check locking solution is broken. http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
The solution (and best practice) is to use the initialization-on-demand pattern :
example at the bottom of this page.
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/singleton.html
This solution is useful when using JDK 1.4 and older.
In JDK 1.5, you can use enum also.
For better understanding, you can read this excellent article :
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
Upvotes: 1