title: How to avoid writing too much data to output and which blocks the thread?
body: <p>In a task which is run by a thread pool, I want to write a bunch of strings to remote, and there is a flag to indicate if the task has been cancelled or not.</p>
  
  <p>I'm using the following code to make sure I can stop as soon as possible:</p>
  
  <pre><code>public void sendToRemote(Iterator&lt;String&gt; data, OutputStream remote) {
      try {
          System.out.println("##### staring sending")
          while(!this.cancelled &amp;&amp; data.hasNext()) {
              remote.write(data.next())
          }
          System.out.println("##### finished sending")
          System.out.println("")
      } catch(Throwable e) {
          e.printStackTrace();
      } finally {
          remote.close();
      }
  }
  </code></pre>
  
  <p>I found sometimes, if I give a very large data(or infinite iterator) to this method, even if I have set the <code>this.cancelled</code> to <code>true</code> later, it can't finish in time. The code seems blocked, and after a long time(1 minute or so), there will be an error like:</p>
  
  <pre><code>java.net.SocketTimeoutException: write blocked too long
  </code></pre>
  
  <p>So I guess it might be the <code>remote.write</code> method can block itself if there is too much data to send, but the remote doesn't consume it in time. Although I set <code>this.cancelled</code> to <code>true</code>, but the method has been blocked in the <code>remote.write(data.next())</code> line for a long time, so it doesn't have chance to check the value of <code>this.cancelled</code> and skip the loop. Instead, at last, it throws an <code>SocketTimeoutException</code> after a long time.</p>
  
  <p>Is my understanding correct? If it is, how can I avoid the blocking if there is too much data to send?</p>