There is a piece of code:

public class Test { private final Socket socket; private final ObjectOutputStream out; private final ObjectInputStream in; public Connection(Socket socket) throws IOException { this.socket = socket; out = new ObjectOutputStream(socket.getOutputStream()); in = new ObjectInputStream(socket.getInputStream()); } public void sendSomeThing1(Message message) { synchronized (out) { out.writeObject(message); } } public synchronized void sendSomeThing2 (Message message) { out.writeObject(message); } } 

Do I understand correctly that in sendSomeThing1 I only block the out object? This means that other threads can use the object and methods of the Test class.

But when using void sendSomeThing2, threads will not be able to use methods of the TESE class at the same time, will they wait for their turn?

Also what are the differences between

 synchronized (**out**) { out.writeObject(message); } 

and

 synchronized (**this**) { out.writeObject(message); } 
  • If you are given an exhaustive answer, mark it as accepted ^^ - Suvitruf

1 answer 1

Do I understand correctly that in sendSomeThing1 I only block the out object? This means that other threads can use the object and methods of the Test class.

Yes.

But when using void sendSomeThing2, threads will not be able to use methods of the TESE class at the same time, will they wait for their turn?

Not certainly in that way.

synchronized method is the same as making a synchronized (this) inside a method.

Other threads will wait in the queue if they access this method, other synchronized methods or locks on this .

If a method is not marked as synchronized , other threads will be able to access it at any time, even if some synchronized method is locked by some stream.

Also what are the differences between

 synchronized (**out**) { out.writeObject(message); } synchronized (**this**) { out.writeObject(message); } 

This is the same thing in general. But there are nuances. Say, if this is a class that implements the logic of a container / collection, it has methods for reading and writing. By logic, it is permissible to read and write there simultaneously. If you get both set get / set methods on this , then the record will wait for the end of the reading and vice versa. In such cases, you can create two different objects. Write on one of them, reading on another.