title: Access thread variable that changes from main thread
body: <p>So, I am new to threads, and I'm still learning how everything works. So, I couldn't find an answer that would provide an explanation for my problem (to my level of understanding).</p>
  
  <p>I have a <code>Runnable</code> class that looks like so:</p>
  
  <pre><code>public class Request implements Runnable {
      private Boolean ok = true;
  
      public synchronized void setOk(Boolean ok) {
          this.ok = ok;
      }
  
      public synchronized Boolean getOk() {
          return ok;
      }
  
      private synchronized void foo() {
          //if something happens
          setOk(false);
      }
  
      @Override
      public void run() {
          while (true)
              foo();
      }
  }
  </code></pre>
  
  <p>And then I have another class that does the following:</p>
  
  <pre><code>private static Request request;
  
  private static void spawnThreads() {
      ExecutorService e = new Executors.newFixedThreadPool(4);
      request = new Request();
  
      e.execute(request); 
  }
  
  public static void main(String[] args) {
      spawnThreads();
  
      while (true) {
          System.out.println(request.getOk());
          if (!request.getOk())
              request.setOk(true);
  
          TimeUnit.SECONDS.sleep(10);
      }
  }
  </code></pre>
  
  <p>I need that if in the main thread, that <code>getOk()</code> returns <code>false</code>, do something and set it to <code>true</code>. Viceversa, set it to <code>false</code> in the thread (which I need to keep on going, no matter what the value of <code>ok</code> is at any given time).</p>
  
  <p>As this code is, I can't get the value of <code>request.getOk()</code> in the main thread. If I remove the <code>synchronized</code> words from the getter and setter, I can access the value in the main thread until a point in time when it is changed by the thread, and never again. </p>
  
  <p>Also, the executor is used because I would create multiple <code>Request</code> objects, and waiting for it to shutdown before accessing the variable would contradict my reason for doing this, as I would need all the threads to keep running.</p>
  
  <p>That thread is making http requests to a server (that randomly times out, denies response, etc) and is used to retrieve some information. The <code>ok</code> variable is there to take a note when the thread acquires an ok response and some information from the server.</p>
  
  <p>How do I solve it so that the thread can update that variable, but the main thread to be able to retrieve it whenever needed, no matter if it was changed by the thread in the meanwhile or not.</p>
  
  <p>Would changing my <code>Runnable</code> to a <code>Callable</code> help? If yes, how?</p>