I use singleton to record all events occuring simoultanously in the system.
public class Singleton {
private static Lock dbLock;
protected Singleton() {}
private static class SingletonHolder {
private final static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
public void recordEvent(Event ev) {
dbLock.lock();
try {
database.insert(ev);
} finally {
dbLock.unlock();
}
}
public File lockAndGetDB() {
dbLock.lock();
return database.getFile();
}
public void unlockDB() {
dbLock.unlock();
}
}
Every few hours I want to lock recording event to send database over internet.
file = Singleton.getInstance().lockAndGetDB();
try {
sendViaHTTP(file);
}
finally {
Singleton.getInstance().unlock();
}
Is there any possible deadlocks? Is it thread safe?
EDITED. (try/finally added for sending viaHTTP) But this is not the main problem. The question is, if there are threads waiting on dbLock.lock(); at recordEvent(Event ev) are my Singleton.getInstance().unlock(); will be able to enter getInstance() code and unlock?
More likely than not, yes there can be deadlocks. What happens if an error occurs during database.getFile or sendViaHTTP? There is no try/finally pattern to ensure Lock.unlock is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With