Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton/Static in Multi threading scenario

 
Arpit Purohit
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Yaroslav Chinskiy
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Yaroslav Chinskiy
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
many thanks to you
Yaroslav Chinskiy

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic