aspose file tools
The moose likes Java in General and the fly likes Singleton Question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Singleton Question" Watch "Singleton Question" New topic
Author

Singleton Question

Rob Bass
Ranch Hand

Joined: Aug 28, 2001
Posts: 67
Maybe I am just not understanding how singletons work... there is only one instance of my singleton class, it has onemethod called write, which writes a file out to disk. Senario: Client A calls write, Client B calls write
What happens? Does B wait on A? does B overwrite A? How are multiple calls to the same method in a singleton class handled?
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
Basically, there is no more problem with a Singleton class than with any other type of classes regarding your example.
In your case, it may judicious to choose a Singleton to handle file access and ensure that only one client access at the file at a given time.
In the nominal case, Client A calls write on the Singleton, then Client B calls write on the Singleton. This action for B is performed when the Singleton is over with writing with class A.
Now if the calls to write are done in two different threads, then you have to be careful. You must bracket the critical section in a synchronized block. The writing for class A can then not be interrupted by class B.
W.
Rob Bass
Ranch Hand

Joined: Aug 28, 2001
Posts: 67
The write method is part of the Singleton class, so it should be ok, as the Singelton just has one instance.
Kaspar Dahlqvist
Ranch Hand

Joined: Jun 18, 2001
Posts: 128
Hi Rob!
Yes, the Singleton class has only one instance, but it is possible to start many threads on one single instance, right? If two threads, both started on this lone instance, happen to call the write method simultaneously, there will be trouble. The only way to bypass this problem is to synchronize either the method or part of it (the critical parts; where you write to the disk).
In other words, just like Wilfried said.
Hope this helps!
//Kaspar
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton Question
 
Similar Threads
singleton class
singleton class
Identifying a Client from the RemoteObject
Clarifications/Suggestions in Java
Doubt regarding singleton