[Singleton] Toutes les méthodes doivent-elles être 'synchronized'
Bonjour à tous,
J'utilise une socket pour envoyer des données.
Il y a plusieurs thread qui y ont accès. Notamment un thread qui envoie des trames de "présence" et un autre des trames de "commande". La ressource socket est donc partagée mais il ne peut en avoir qu'une instance.
Du coup la classe SocketCom est en singleton.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class SocketCom
{
private java.net.DatagramSocket socket = null;
private InetAddress addr;
private int port = 6680;
private int receiveDelay = 100;
private static SocketCom instance = null;
public static synchronized SocketCom getInstance() throws IOException
{
if(instance==null)
{
instance = new SocketCom();
instance.open();
}
return instance;
}
private void socketCom() { ........}
private void open() throws IOException {.....}
public synchronized void sendKeepAlive() throws IOException {
DatagramPacket dp = new DatagramPacket(KeepAlive, 2, addr, port);
socket.send(dp);
}
public synchronized void commande1() throws IOException {
DatagramPacket dp = new DatagramPacket(commande1, 2, addr, port);
socket.send(dp);
}
public synchronized void commande2() throws IOException {
DatagramPacket dp = new DatagramPacket(commande2, 2, addr, port);
socket.send(dp);
}
} |
Quelqu'un saurait-il me dire si toutes les méthodes doivent déclarées synchronized ?
Merci d'avance pour votre aide.