Reputation: 18557
I'm developing a simple network client/server. The client has a MainConnection class which maintains the connection to the server and starts worker threads based on information coming in. I want the worker threads to send feedback on their progress to the server via the main connection. I’m not sure if I should have a public static synchronized method in MainConnection for sending data, or pass a Session object to the threads which would contain the Socket and a synchronized method for sending data.
Upvotes: 1
Views: 404
Reputation: 115328
It does not matter which design will you choose. It is really up to you. The only thing you should care about is to avoid 2 threads writing to the same stream concurrently. So, you can create your own layer that is synchoronized and used by several threads. Alternatively you can create synchronized output stream and pass it to all threads. This is probably the best approach: in this case each thread just knows to write stuff to the stream. The only layer that knows that stream is synchronized is a factory that creates it.
Upvotes: 2