Rahul Kurup
Rahul Kurup

Reputation: 741

Class level lock for static variables in java

If i don't use any setters/getters in my java class X. When a thread A has class level lock of my class X. Can another thread B change my static variable directly ??

public class X {

    Integer static_variable = 10;

    public static void doNothing {
        /* Do Nothing */
    }

}

Lets say thread A has class level lock now. Can i do X.static_variable = 11 from another thread B?

I was writing a code to get deadlock in java.

public class A implements Runnable {

    public static Integer as = 5;
    static A a = new A();
    static B b = new B();

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here

    Thread thread1 = new Thread(a);
    Thread thread2 = new Thread(b);
    thread1.setName("First");
    thread2.setName("Second");
    thread1.start();
    thread2.start();
}


public void run() {    
    runme();

}

public static synchronized void runme() {
    try {
    System.out.println(Thread.currentThread().getName() + " has object a's key and waiting");
    Thread.sleep(1000);
    System.out.println(Thread.currentThread().getName() + " Woke up from sleep"); 
    System.out.println(Thread.currentThread().getName() + " wants b's Key"); 

    B.bs = 10;
    System.out.println(Thread.currentThread().getName() + " over"); 

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

public class B implements Runnable {

public static Integer bs = 6;

public void run() {
    runme();
}

public static synchronized void runme() {
    try {
        System.out.println(Thread.currentThread().getName() + " has object b's key and waiting");
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " Woke up from sleep");
        System.out.println(Thread.currentThread().getName() + " wants a's Key");

        A.as = 10;
        System.out.println(Thread.currentThread().getName() + " over");

    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

}

But getting below result:

Second has object b's key and waiting First has object a's key and waiting First Woke up from sleep Second Woke up from sleep Second wants a's Key Second over First wants b's Key First over

Second thread is clearly editing the static variable of class A even when another thread holds the class level lock of class A

Upvotes: 0

Views: 597

Answers (1)

TheLostMind
TheLostMind

Reputation: 36304

Yes you can. Unless you have a synchronized block around the variable changing code. If you don't use synchronization, other threads don't have to acquire the X.class's monitor before changing its static_variable.

Make the field private, and add a setter, make it synchronized, then you will not be able to change the field when another thread holds the lock for X.class

Upvotes: 1

Related Questions