Lets take an example:
public class DBServer {
static boolean listening = false;
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
static List<ClientThread> users = null;
public static void main(String[] args) {
users= new LinkedList();
int portNumber = 0;//some valid port number
System.out.println("Now using port number=" + portNumber);
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
while (listening) {
try {
System.out.println("Number of users connected: " + users.size());
clientSocket = serverSocket.accept();
System.out.println("Someone just joined.");
ClientThread ct= new ClientThread(clientSocket);
users.add(ct);
ct.start();
}catch (IOException e) {
System.out.println(e);
}
}
}
}//End of class
public class ClientThread extends Thread {
int c = 0;
//some other variables
ClientThread(Socket s){
this.clientSocket= s;
}
void doSomething(){
ClientThread ct = DBServer.users.get(0);
synchronized(ct){
ct.c++;//or some other operation on c
}
}
void method2(){
c++;//or some other operation on c
}
//some other methods
public void run(){
//some never ending logic that decides which method is being called
}
}//End of class
Let's assume that there are 3 users(User 0, User 1, User 2) connected to the server at a given time.
User 1 obtains the intrinsic lock for the object of User 0. It is certain that User 2 can't obtain the lock for User 0 while User 1 still posses it. Can User 0 himself change the value of c
using method2()
while the lock is held by User 1? If so, is there a way to make variable c
synchronized between the thread owning it and other threads?