Are the injected classes in Java EE and Spring synchronized? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Are the injected classes in Java EE and Spring synchronized? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about Are the injected classes in Java EE and Spring synchronized? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji