Can volatile variable be defined as static in java?

后端 未结 5 1507
無奈伤痛
無奈伤痛 2021-02-01 04:36

Can I declare something like this??

static volatile boolean first=false;
5条回答
  •  半阙折子戏
    2021-02-01 05:28

    As per the question, yes we can but in that case we need to handle all the scenario.

    Access a static value through multiple threads, each thread can have it’s local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value. However, volatile is not a substitute for proper synchronisation

    private static volatile int cnt= 0;

    private void checkCnt() {
         cnt+= 1;
         // some conditions
         // some code
         cnt -= 1;
    }
    

    Executing checkCnt concurrently many times the final value of cnt different from what we expect! To solve the problem, we’ve to implement a lock to keep track of increment/decrement

    private static final Object lock = new Object();
    private static volatile int cnt= 0;
    
    private void checkCnt() {
         synchronized (lock) {
             cnt += 1;
         }
         //some conditions
         //some code
         synchronized (lock) {
             cnt -= 1;
         }
    }
    

    Not sure is this the right way but by this we can manage the things and use static with volatile. Please provide inputs, if there is better way.

提交回复
热议问题