Note that there are some explanatory texts on larger screens.

plurals
  1. POShould variable be made volatile?
    primarykey
    data
    text
    <p>I have a class in which there is a <code>boolean</code> variable called <code>isbeingwritten</code>. It keeps track of whether a file is being written to. A function of this class invokes a few threads which write to files. these will first check the value of the <code>isbeingwritten</code> variable and if it is <code>false</code>, set it to <code>true</code> and start writing, otherwise they will wait. At the end of writing they will change the value back to <code>false</code>. Should this variable be made <code>volatile</code>?</p> <pre><code>class A { public boolean isbeingwrittenfalse; public void func() { new thread1(); new thread2(); } class thread1 implements Runnable { Thread t; thread1() { t=new Thread (this); t.start(); } public void run() { while(isbeingwritten); isbeingwritten=true; //wrrite very long string isbeingwritten=false; } } class thread2 implements Runnable { Thread t; thread2() { t=new Thread (this); t.start(); } public void run() { while(isbeingwritten); isbeingwritten=true; //wrrite very long string isbeingwritten=false; } } </code></pre> <p>The following is the correct solution </p> <pre><code>public class XSSThread implements Runnable { Thread xt; public void init() { xt = new Thread(this); xt.start(); } public void run() { new Thread1().init(); new Thread2().init(); } public synchronized void saveToFile(String a) { File aFile = new File("filename.txt"); try { BufferedWriter out = new BufferedWriter(new FileWriter(aFile, aFile.exists())); out.write(a + "\r\n"); out.close(); } catch (IOException e) { e.printStackTrace(); } } } public class Thread1 extends XSSThread implements Runnable{ Thread xt1; public void init() { xt1 = new Thread(this); xt1.start(); } public void run() { String a;//very long string saveToFile(a); } } public class Thread2 extends XSSThread implements Runnable { Thread xt2; public void init() { xt2 = new Thread(this); xt2.start(); } public void run() { String a;//very long string saveToFile(a); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload