title: IO operation in other thread blocking my UI thread?
body: <p>So that IO doesn't block the UI thread in my Android app, I'm trying to move a file write operation into a separate thread. This is the code I'm using to start a low priority thread to write about 1Mb from a byte buffer:</p>
  
  <pre><code>Thread t = new Thread(new Runnable()
  {
    @Override
    public void run()
    {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        try
        {
          FileOutputStream fos = new FileOutputStream(filename));
          try
          {
            final java.nio.channels.FileChannel outChannel = fos.getChannel();
            outChannel.write(byteBuffer);
            fos.getFD().sync();
          }
          finally
          {
            if (fos != null)
              fos.close();
          }
        }
      catch (Exception e)
      {
        e.printStackTrace();
      }
  }
  });
  
  t.setPriority(Thread.MIN_PRIORITY);
  t.start();
  </code></pre>
  
  <p>These threads are started in my app when certain UI events happen. Unfortunately, I still notice a huge amount of lag sometimes. My UI will freeze for ~2 seconds every 10 or so times I start/finish one of the above threads. If I comment out the thread code, these delays disappear.</p>
  
  <p><b>What can I do to stop this IO operation from blocking my UI thread?</b></p>
  
  <p>I'm not sure what to do now to diagnose the problem. My understand was that the IO thread would become blocked when "outChannel.write" happened as it was waiting for an IO operation to finish, which would mean my UI thread would immediately take over. Is it the case the write operation actually requires a big chunk of CPU power?</p>
  
  <p>Edit:</p>
  
  <p>With StrictView on (which I'm sure of because it caught some unrelated IO problems in the UI thread that I fixed first), I can confirm no IO occurs in my IO thread.</p>
  
  <p>The results of running traceview are quite puzzling. The UI problem is that, when I'm performing drag and drop actions, every 10 or so times I do this the device seems to freeze for about 0.5 to 1s. The thing you're dragging will freeze and after a delay will eventually jump to where your finger is. In traceview, I kept dragging and dropping until this happened. For the case where this happens in traceview, my background threads aren't running  but there's a sudden block of about 1 second where operations on my UI thread that are usually fast to call are taking about x10 longer to perform. For example, a call to .drawBitmap (with a fixed size bitmap) is shown as taking ~0.2s to execute when every time before this the same .drawBitamp call is taking a tenth of this time. I could just be reading it wrong, but I don't know where to go from here or what to look for.</p>