title: How To Delay Method Return Until File Is Completely Read
body: <p>Consider the following code example, in which I removed all error handling code in order to keep it readable:</p>
  
  <pre><code>public class MyClass {
  
    protected Something myAttribute;
    protected boolean busy = true;
  
    public ReactiveLogger() {
      new Thread(new FileListener()).start();
    }
  
    private class FileListener implements Runnable {
  
      @Override
      public void run() {
        RandomAccessFile raf = new RandomAccessFile(LOG_FILE, "rw");
        while (true) {
          final String line = cutFirstLine(raf);
          if (line == null) {
            busy = false;
            Thread.sleep(1000);
          } else {
            busy = true;
            // handeLogMessage changes myAttribute
            handleLogMessage(line);
          }
        }
      }
  
      // definition of cutFirstLine etc.
  
    }
  
    // definition of handleLogMessage etc.
  
    public Something getSomething() {
      while (busy) {
        Thread.sleep(100);
      }
      return myAttribute;
    }
  
  }
  </code></pre>
  
  <p>So my class <code>MyClass</code> reads a log file in the background (in another thread) and updates an attribute <code>myAttribute</code> with every line it reads from the log file. As long as there are any entries in the log file and my attribute is updated, the return of the getter function <code>getMyAttribute()</code> should be delayed. As soon as there are no more entries in the log file, <code>getMyAttribute()</code> should return <code>myAttribute</code>.</p>
  
  <p>Although this code example works as required, it does not seem to be the most elegant solution. It is not clear at all how long the thread should sleep in order to have an optimal result. If one simply removes the call to <code>Thread.sleep</code> in the getter function, the program freezes. But if I set the value of the sleep method too high, the execution also takes too long.</p>
  
  <p>How can I achieve the same in a better way? I already had a look at Java multithreading / concurrent programming resources, but nothing (like Java's <code>synchronized</code>) seems to fit this situation.</p>