Quando usar voláteis e sincronizados
Eu sei que há muitas perguntas sobre isso, mas ainda não entendi direito. Sei o que essas duas palavras-chave fazem, mas não consigo determinar qual usar em determinados cenários. Aqui estão alguns exemplos que estou tentando determinar qual é o melhor para usa
Exemplo 1
import java.net.ServerSocket;
public class Something extends Thread {
private ServerSocket serverSocket;
public void run() {
while (true) {
if (serverSocket.isClosed()) {
...
} else { //Should this block use synchronized (serverSocket)?
//Do stuff with serverSocket
}
}
}
public ServerSocket getServerSocket() {
return serverSocket;
}
}
public class SomethingElse {
Something something = new Something();
public void doSomething() {
something.getServerSocket().close();
}
}
Exemplo 2:
public class Server {
private int port;//Should it be volatile or the threads accessing it use synchronized (server)?
//getPort() and setPort(int) are accessed from multiple threads
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
Qualquer ajuda é muito apreciada