Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is volatile keyword not allowed for local variables?

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();
like image 849
Farhan Shirgill Ansari Avatar asked Oct 10 '16 07:10

Farhan Shirgill Ansari


People also ask

Can local variables be volatile?

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.

Can a local variable be volatile in Java?

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.

Can volatile keyword used with instance variable?

Volatile can only be applied to instance variables, which are of type object or private.

What Cannot be used for local variables?

Access modifiers cannot be used for local variables.


1 Answers

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!

like image 112
GhostCat Avatar answered Oct 22 '22 11:10

GhostCat