简体   繁体   中英

Toggle a volatile boolean in Java

I notice that the following code doesn't toggle the flag as it is intended to be (the flag value remains the same after toggleFlag is called). Why is this the case?

private static volatile boolean flag;

static synchronized void toggleFlag() {
   flag = !flag;
}

It is impossible for the code you put to compile, leave running.

Your code has multiple errors, for example,

  1. You can't access a non-static variable( flag in this case) from a static method( toggle() in this case).
  2. Proper declaration of toggle() method is, static synchronized void toggle()

Correct code:

private static volatile boolean flag;

static synchronized void toggle()
{
 flag = !flag;
}

Thank you.

You cannot use this with static variable.

In static block or a static method, there is no instance to refer to, and therefore the this keyword is not permitted.

Check this out:

private static volatile boolean flag;

    static synchronized void toggleFlag() {
        flag = !flag;
    }

From docs.oracle.com:

Not all combinations of instance and class variables and methods are allowed:

  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

Link: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

UPD. When you create boolean variable such as private static volatile boolean flag; it becomes false by default. So using this code toggleFlag(); means !false .

You can check the Default Values section in Primitive Data Types for more information about the class members default values.

Link: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM