I have a singleton class MyService
, it has two functions to read & write data from/to file:
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();
}
}
MyFileAccessor
class has synchronized functions to read & write file:
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
…
}
}
My question : Is the singleton MyService
class thread-safe when my project reading & writing data from/to file through it? Are there potential concurrency issues?
===== UPDATE ===
Two more questions based on the answers:
Q1. I see the answers below about using Initialized-On-Demand idom. But isn't it enough if I just use the synchronized
keyword on getInstance()
static method?
public static synchronized MyService getInstance() {
...
}
Doesn't it also make the singleton instance creation atomic?
Q2. If I only use MyFileAccessor
through MyService
instance, is it still necessary to make MyFileAccessor
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 MyFileAccessor
?