aspose file tools*
The moose likes Threads and Synchronization and the fly likes Singleton/Static in Multi threading scenario Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Singleton/Static in Multi threading scenario" Watch "Singleton/Static in Multi threading scenario" New topic
Author

Singleton/Static in Multi threading scenario

Arpit Purohit
Greenhorn

Joined: Jan 09, 2007
Posts: 21
Hi all,
I have created a class to use singleton Socket to connect to an IP. I want that at a time, only a single thread should be able to use this connection (use its InputStream and OutputStream).
Following is the code:

Further I will be using above class as follows:


Now my doubts are:
1. Is above code fine for multi threaded scenario
2. As Socket object is Static(and singleton), will it always return reference to same InputStream and OutputStream (implies they are also singleton).
If Yes than how to make InputStream and OutputStream thread safe.(one way is to use synchronized block in second code snippet)

Regards,
Arpit Purohit
Yaroslav Chinskiy
Ranch Hand

Joined: Jan 09, 2001
Posts: 147
Hi,

This is not a singleton. Specially if you use Java 1.4
Depending you your need you can do one of the following:

1. For 1.5 you can create an enum that will encapsulate the socket.
2. For 1.4 you can create a handler object that will create singleton (lazy) or define it as a static final variable.
3. Regardless of the pattern you choose to create singleton, abstract in and out streams to synchronized methods that will delegate to IO.
This approach is more flexible in the long run.
Ashraf Abu-Aisheh
Ranch Hand

Joined: Apr 17, 2009
Posts: 88
Yaroslav Chinskiy wrote:Hi,

This is not a singleton. Specially if you use Java 1.4
Depending you your need you can do one of the following:

1. For 1.5 you can create an enum that will encapsulate the socket.
2. For 1.4 you can create a handler object that will create singleton (lazy) or define it as a static final variable.
3. Regardless of the pattern you choose to create singleton, abstract in and out streams to synchronized methods that will delegate to IO.
This approach is more flexible in the long run.


You are appreciated if you modify the above 'Arpit Purohit' code with 1.5 as point #1 and post it again here.

Thanks.


SCJP 5 - 79%
SCWCD 5 - 100%
Yaroslav Chinskiy
Ranch Hand

Joined: Jan 09, 2001
Posts: 147
Here is a simple example of singleton socket. The concept is there, implementation may be improved.
I am also putting some simple echo server to test this code.

I hope it makes sense.

Ashraf Abu-Aisheh
Ranch Hand

Joined: Apr 17, 2009
Posts: 88
many thanks to you
Yaroslav Chinskiy

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton/Static in Multi threading scenario