Igor S.
Igor S.

Reputation: 3350

Singleton with Lock - possible deadlock? in java

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?

Upvotes: 3

Views: 1676

Answers (2)

Tim Bender
Tim Bender

Reputation: 20442

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.

Upvotes: 1

user207421
user207421

Reputation: 310860

Deadlocks arise when you acquire locks in different orders. As there is only one actual lock here, the question does not arise.

Your case looks more like a candidate for a read-write lock to me: use read locks to allow maximal concurrency of DBMS operations, and a write lock when you want them to stop and send the file.

Upvotes: 0

Related Questions