title: Synchronize object serialization(Android)
body: <p><strong>tl;dr:</strong> 
  I have two threads, one of them serealizes object, and another tries to read object. How do I avoid collisions, i.e. synchronize access to file?</p>
  
  <p><strong>More info:</strong>
  I have Service which uses AsyncTask to fetch data and then serializes object:</p>
  
  <pre><code>  @Override
    protected Boolean doInBackground(Void... params) {
        FeedItem currentItem = mParser.parseFeed();
        Util.saveItem(UpdateService.this, currentItem);       
    }
  </code></pre>
  
  <p>Object serialization:</p>
  
  <pre><code>public class Util {
  
      private static final String sFileName = "feedobject";
  
      public static FeedItem loadItem(Context context) {
          FeedItem result = null;
          try {
              FileInputStream fis = context.openFileInput(sFileName);
              ObjectInputStream is = new ObjectInputStream(fis);
              result = (FeedItem) is.readObject();
              is.close();
          } catch (IOException e) {
              e.printStackTrace();
          } catch (ClassNotFoundException e) {
              e.printStackTrace();
          }
          return result;
      }
  
      public static void saveItem(Context context, FeedItem item) {
          FileOutputStream fos;
          try {
              fos = context.openFileOutput(sFileName, Context.MODE_PRIVATE);
              ObjectOutputStream os = new ObjectOutputStream(fos);
              os.writeObject(item);
              os.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>I also try to read object from Activity, i.e. from UI thread.</p>
  
  <pre><code>mTextView.setText(Html.fromHtml(Util.loadItem(this).message));
  </code></pre>