Static elements when used in a synchronized method or block in java

when I use the synchronized method method in an instance, the monitor is connected to 'this', and on the other hand, when I synchronize on my class (static) method, the monitor is connected to the class object, which in case I have a static variable used in the non-stationary method? will it be synchronized?

they say

public class A{

   public static int reg_no = 100;

   public synchronized void registration(){

      A.reg_no = some operation...

   }

}

in the case above, what happens to the reg_no static variable if two or more threads compete to register the method ()

+3
source share
5 answers

- synchronized . , :

public synchronized void registration() {
    synchronized (A.class) {
        A.reg_no = some operation ...
    }
}

, , , - . synchronized , synchronized (A.class).

+2

( ) . , ( )

, , .

+1

( )

int , punkers.

- , ...

, , -, A, , , "" .

, :

  • A ( public!)
  • A ( ), ,
  • A

, , - , , / :

synchronized (objectOfTypeA) { ... } // takes the instance lock

synchronized (A.getClass()) { ... } // takes the class lock

, , ( ) :

public class A {

    private static int reg_no = 100;
    private static Object lock = new Object();

    public void registration(){
        synchronized(lock) {
            reg_no = some operation...
        }
    }

    public static int getRegNo() {
        synchronized(lock) {
            return reg_no;
        }
    }
}
+1

No, you need to synchronize the method with the class, for example. synchronized(A.class).

0
source

instead of adding another synchronized block inside the synchronous method, I would declare the static variable as volatile if your problem is to share this variable with other threads.

0
source

Source: https://habr.com/ru/post/1769096/


All Articles