Are the injected classes in Java EE and Spring synchronized?

I want to have just one TCP socket that connects to another program. Every new call to my rest endpoint writes to my TCP socket. If I write a class with my TCP socket and inject it into my Controller class, will it be thread safe? or do I have to synchronize them using the synchronize keyword?

@Component
public  class ViconetBuffer {

private Socket socket;

private boolean connectToViconSocket(){
    try {
        socket = new Socket(DeviceAddressUtil.socketIp,DeviceAddressUtil.port);
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        return false;
    }
}

public void sendDataToViconSocket(String message){
    try {
        if (!socket.isConnected()){
            connectToViconSocket();
        }else socket.getOutputStream().write(message.getBytes());
    }catch (Exception ex){
        ex.printStackTrace();
    }
}

}

Answer

No, that’s your job. Spring/CDI/EJB can not know how you want the several threads to coordinate their use of the Socket.

Leave a Reply

Your email address will not be published. Required fields are marked *