In below code I am trying to use multiple threads to access queue until isFound = false
. I have declared isFound
variable as volatile
and I am changing its value to true after some condition. If I change its value in one thread and by definition its updated value should be visible to all other threads. When I run this code, the value of isFound
is still false
.
If I change isFound from volatile to static it works fine why is that?
class FileAccessThread implements Runnable {
volatile boolean isFound = false;
BlockingQueue<String> bq;
public FileAccessThread(BlockingQueue<String> bq) {
this.bq = bq;
}
public void run() {
System.out.println("ifFound "+isFound);
if(bq !=null && !isFound){
try {
System.out.println("Current Thread "+Thread.currentThread().getName());
String filePath = bq.take();
System.out.println("File Path "+filePath);
Thread.sleep(2000);
if(filePath.equals("c:/test/t5.txt")) {
isFound = true;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MultiFileAccess {
public static void main(String[] args) {
ExecutorService e = Executors.newFixedThreadPool(3);
BlockingQueue<String> bq = new LinkedBlockingQueue<>();
bq.add("c:/test/t1.txt");
bq.add("c:/test/t2.txt");
bq.add("c:/test/t3.txt");
bq.add("c:/test/t4.txt");
bq.add("c:/test/t5.txt");
bq.add("c:/test/t6.txt");
bq.add("c:/test/t7.txt");
bq.add("c:/test/t8.txt");
bq.add("c:/test/t9.txt");
bq.add("c:/test/t10.txt");
int lengthOfQueue = bq.size();
for(int i=0;i < lengthOfQueue-1;i++){
e.execute(new FileAccessThread(bq));
}
e.shutdown();
}
}