简体   繁体   中英

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();
    }
}

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM