Forums Register Login

Singleton/Static in Multi threading scenario

+Pie Number of slices to send: Send
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)
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
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.

+Pie Number of slices to send: Send
many thanks to you

Yaroslav Chinskiy


Willie Smits increased rainfall 25% in three years by planting trees. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 6781 times.
Similar Threads
Client Failed to connect, how do I attempt a reconnect?
Producer/Consumer Design impacts exception handling
Multithread-call center support
Creating a Pipe that connects 2 sockets
connection refused
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:46:33.