Question

I have always used Singleton pattern creating apps with SQLite, but now I wonder if would it be best to use locks like this:

class DatabaseHelper {
    Object lock
    SQLiteDatabase db;

    // more properties....

    public void insert(BusinessEntity entity) {
         synchronized(lock) {
             db.insert(BusinessEntity.TABLE_NAME, // more params...
         }
    }

}

Since so far I have always used a singleton, I have never worried about a query not executing cause of multiple connection to the same DB, but as I understand, a lock would also solve this.

What is the better approach here and why? And also, is that synchronized example all right? I've never used synchronized before so I'm not sure it is all right.

Was it helpful?

Solution

Singleton and Lock are 2 different concepts and are not interrelated. Lock acquire on object level but not on the class level. it does not matter that object is singleton object or normal object.

Singleton

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Please note singleton pattern will not apply lock on the object. For example 2 different threads are sharing the same single object reference and can call the different method on that single object simultaneously.

Lock

Lock means, we are restricting to access the same resource(object) by 2 different thread simultaneously. Java implemented the lock concept using the synchronized blocks or synchronized method.

Note : in your code example you are acquiring lock on the "lock" object (i.e. synchronized(lock) ) but not on the "db" object. To acquire lock on the db object you will have to change the code to

synchronized(db){
......
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top