I agree that the simplest (but not most effective) solution is to make sure that the data access methods are synchronized on the same object, and doing that is easiest by ensuring that the data class is a singleton.

I have synchronized all methods in my data singleton class except for two, lock and unlock, because concurrent work simply did not work when update and lock (for different clients) were synchronized on the same object.

The data class methods lock and unlock use an underlying class LockManager (holding the lock map), and I chose then to synchronize the methods lock and unlock in LockManager instead of in Data. So locking will synchronize on another object.

Now I'm wondering...will this really be safe? ..since the LockManager class is not a singleton. I believe it should, since the only reference to LockManager is inside Data, which is a singleton. The LockManager object is initialized only once, when Data is initialized.

Does this approach seem ok?

Vlad Djordan

Greenhorn

Posts: 15

posted 6 years ago

Hi Mikael,

Now I'm wondering...will this really be safe? ..since the LockManager class is not a singleton. I believe it should, since the only reference to LockManager is inside Data, which is a singleton. The LockManager object is initialized only once, when Data is initialized.

I would go a step further myself and declare the LockManager with default access so that it is only visible from the package your Data class is in. Essentially, your design is still gearing towards instantiating the LockManager once and it just seems logical to me to make it a Singleton as well. I don't believe there is anything wrong with your approach, but you should test the locking mechanism thoroughly.

I only method synchronized create() and find() methods, while all the others were block synchronized, and it was all implemented in the Data class and I managed to provide concurrent record access to my database structure.

Mikael, even though your LockManager class does not explicitly implement the Singleton pattern, there's certainly just one instance of it in the entire application, since the object's life cycle is controlled by a Singleton object. So synchronizing its methods is safe too. But, just for the sake of security, run these tests on your Data class.

Vlad Djordan wrote:I would go a step further myself and declare the LockManager with default access so that it is only visible from the package your Data class is in.