title: Is my service thread safe?
body: <p>I have a <strong>singleton</strong> class <code>MyService</code>, it has two functions to read &amp; write data from/to file:</p>
  
  <pre><code>public class MyService {
   private static MyService instance;
   private MyFileAccessor fileAccessor;
  
   private MyService() {
     fileAccessor = new MyFileAccessor();
   }
  
   public static MyService getInstance() {
    if (instance == null) {
       instance = new MyService();
    }
    return instance;
   }
   // write data to file through fileAccessor object
   public void writeDataToFile(Object data){
     fileAccessor.writeToFile(data);
   }
   // read data from file through fileAccessor object
   public Object readFile() {
     return fileAccessor.readFromFile();
   }
  
  }
  </code></pre>
  
  <p><code>MyFileAccessor</code> class has <strong>synchronized</strong> functions to read &amp; write file:</p>
  
  <pre><code>public class MyFileAccessor {
    private File mFile;
  
    public MyFileAccessor() {
      mFile = new File(PATH);
    }
    public synchronized Object readFromFile() {
      // code to read mFile
      …
    } 
  
    public synchronized void writeToFile(Object data) {
      // code to write data to mFile
      …
    } 
  }
  </code></pre>
  
  <p>My question : Is the singleton <code>MyService</code> class <strong>thread-safe</strong> when my project reading &amp; writing data from/to file through it? Are there potential concurrency issues?</p>
  
  <p><strong>===== UPDATE ===</strong></p>
  
  <p>Two more questions based on the answers:</p>
  
  <p><strong>Q1.</strong> I see the answers below about using Initialized-On-Demand idom. But isn't it enough if I just use the <code>synchronized</code> keyword on <code>getInstance()</code> <strong>static</strong> method?</p>
  
  <pre><code>public static synchronized MyService getInstance() {
   ...
  }
  </code></pre>
  
  <p>Doesn't it also make the singleton instance creation atomic?</p>
  
  <p><strong>Q2.</strong> If I only use <code>MyFileAccessor</code> through <code>MyService</code> instance, is it still necessary to make <code>MyFileAccessor</code> a singleton or synchronized on MyFileAccessor.class ? I mean MyService is a singleton, isn't it already guaranteed only one instance is able to invoke methods in <code>MyFileAccessor</code>?</p>