Does the keyword synchronize the thread from using its variable when locking?

Let's 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 

Suppose that 3 users are currently connected to the server (User 0, User 1, User 2).
User 1 gets an internal lock for user 0. I’m sure User 2 cannot get a lock for user 0 while User 1 still has this. Can user 0 independently change the value of c with method2() , while the lock is held by user 1? If so, is there a way to make variable c synchronized between a thread that owns it and other threads?

+1
java multithreading
Feb 05 '16 at 6:46
source share
2 answers

So, for your next question // If yes, is there a way to make the variable c synchronized?

Go for AtomicInteger, which will prevent race condition,

AtomicInteger c;

0
Feb 05 '16 at 6:53
source share
β€” -

you can make C static variable of the DBServer class so that all threads have access to it.

Now you need to change method2() to synchronize.

and if you do this to answer your question in accordance with these new conditions, user 0 will not be able to change the variable C while it is under the control of user 1.

0
Feb 05 '16 at 7:40
source share



All Articles