Reputation: 4433
I have got a session bean method that uses Hibernate to add child to a indexed collection of an entity. However, since there may be multiple threads accessing the method at the same time, in some weird cases it happened that a duplicate index will be assigned to different children (bug in Hibernate? I don't know).
To prevent it, I would like to try to lock the whole entity as well as it's collection so other threads would not be able to modify it while another thread is updating it. I know we can set lock mode to an entity, but how about a collection? Can it lock any other transactions from adding a new child?
Please enlighten me! Thanks in advance.
Upvotes: 0
Views: 511
Reputation: 1574
Maybe you could try to use synchronized collection wrappers. You can use the static methods in Collections class (Collections). For example:
List<String> myList = Collections.synchronizedList(new List<String>());
As for locking at entity level, a synchronized code block locked on the entity should do the trick.
synchronized (entityInstance)
{
...
}
Upvotes: 2