Reputation: 994
I have a class that creates multiple threads, each thread gets an socket as parameter in constructor.
I need to synchronize the threads, so that only one thread accesses the sockets streams at given time.
Here is quick draft of what I need:
class MyClass{
Socket socket;
public MyClass() {
socket = new Socket(address, port);
}
void createThread(){
Worker worker = new Worker(socket);
Thread t = new Thread(worker);
t.start();
}
void doStuff(){
InputStream is = socket.getInputStream();
/* ... */
}
}
class Worker implements Runnable{
Socket socket;
public Worker(Socket socket){
this.socket = socket;
}
@Override
public void run() {
InputStream is = socket.getInputStream();
/* ... */
}
}
Now here, potentially multiple threads can access sockets input stream at the same time, which would be very bad.
Now my question is: will synchronized
keyword work for this case?
Upvotes: 2
Views: 454
Reputation: 36562
To use basic synchronization you could use the socket as the lock since it's shared by each worker.
public void run() {
synchronized (socket) {
InputStream is = socket.getInputStream();
/* ... */
}
}
If MyClass
really needs to access the socket as well, perform the same synchronization in doStuff
.
However, you're effectively serializing access to the socket and bypassing the multi-threaded aspect of your application since the lock is held during the entire duration of the run
method.
Upvotes: 6