Question

Say using following function:

getUnique(){
    MyObject obj = getValueFromDb();
    obj.modifyIt();
    obj.commit();
}

When simultaneous call is made to this method several threads share same value of the MyObject, but I expected each thread to have a unique value.

To fix this I used thread synchronizing using class.getInstance().myMethodCall() to get unique value of some property, this solved the purpose, but as simultaneous call comes it reduces the efficiency of function.

Is there some better way to fix this? (Using STRUTS, HIBERNATE3.0)

Was it helpful?

Solution

With Hibernate, each thread has its own session, and each session has a different set of objects. Each thread will thus have its own copy of MyObject. The database will handle concurrent modifications for you. If you want to forbid two threads modifying the same object at the same moment, use optimistic concurrency, with a @Version field, as described in the Hibernate documentation.

Synchronization is not the right tool here, because if your app is clustered or if the object is modified by another app or even another method, the synchronization won't have any effect.

OTHER TIPS

Your assumption that "several threads share same value of the MyObject" is wrong. MyObject is not an instance variable, therefore it won't be shared with other threads.

I would like to say 2 things to you, first is as @Umesh pointed, each thread is having its own copy of MyObject, they are not sharing the copy

and secondly, the function getValueFromDb() is also external, Have you ensured that getValueFromDb() is also synchronized. if Not? then you should synchronize it too.

Also, what is inside myMethodCall()??? Does it return the same value which getValueFromDb() returns??

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top