Can I declare something like this??
static volatile boolean first=false;
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.