Consider the snippet:
If in a main thread, I have this inside a method-
volatile CountDownLatch latch = new CountDownLatch(3);
new Thread(new ProcessThread("Worker1",latch, 20000)).start();//20 secs
new Thread(new ProcessThread("Worker2",latch, 60000)).start();//60 secs
new Thread(new ProcessThread("Worker3",latch, 40000)).start();//40 secs
I see that volatile
is shown as an illegal modifier. And only final
is permitted. And final guarantees initialization safety.
public static class ProcessThread implements Runnable {
final CountDownLatch latch;
final long workDuration;
final String name;
public ProcessThread(String name, CountDownLatch latch, long duration){
this.name= name;
this.latch = latch;
this.workDuration = duration;
}
}
The object below i.e new CountDownLatch(3)
is properly constructed but I also want to make sure that the reference latch
to which the above object is assigned is guaranteed to be visible to the code below it.
final CountDownLatch latch = new CountDownLatch(3);
Does the above code guarantee initialization so that latch
is perfectly visible to the code below i.e
new Thread(new ProcessThread("Worker1",latch, 20000)).start();
Operations you perform locally will not have visibility or interference issues by other threads so it does not make sense to declare local variable volatile.
A local variable cannot be declared as volatile because a local variable is always private to the thread which is never shared with other threads.
Volatile can only be applied to instance variables, which are of type object or private.
Access modifiers cannot be used for local variables.
Local variables live on the stack; and of course, when you invoke the same method twice, they have all their local variables on their individual stacks.
volatile only makes sense when multiple threads would be writing to the same memory location (on the heap).
Which makes absolutely no sense for local variables from within the body of a method!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With