users@glassfish.java.net

The OptimisticLockException is related to Session Cache of Toplink Essentials

From: Wu Jie <wujie_at_cn.fujitsu.com>
Date: Thu, 09 Oct 2008 15:53:48 +0800

Hi Peter
Hi GF) Dev Teams,
Hi Everyone,

I encountered OptimisticLockException when running JPA app wich
enables session cache. I looked into the runtime and found that
the cause of OptimisticLockException seems to be related to the
session cache. and when I disabled session cache the app ran
successfully.

The app I used is attached. and steps of exception repoduction
is following.
=======================================================================
1. asadmin start-database
2. asadmin start-domain
3. asadmin deploy --retrieve . sample-ear.ear
4. appclient -client sample-earClient.jar create-role testrole
5. appclient -client sample-earClient.jar create-user testuser testrole
6. appclient -client sample-earClient.jar get-user testuser
7. appclient -client sample-earClient.jar delete-user testuser

Test env:
- Windows
- JDK 6 Update 4
- GlassFish V2 UR1 b09d

JDBC Resource: "Jdbc/__default" of GF by default.
=======================================================================

It seems that the entity verison of step 5 is difference from the one
of step 6, so when execute step 7 OptimisticLockException occured.

In my opinion the exception cause is following.
Exception Patern :
1. Transaction Begin
2. Entity Persist
3. EntityManager.flush()
4. Entity Update
5. Tranction End(commit)
6. Read and Update for the same Entity in other Transaction

The update of step 4 is committed to database in step 5. because
the entity of step 4 is the same to the one in the session cache
which is produced by step 3, the result of step 4 does not update
the session cache(the old version remains in session cache). so
when step 6 obtains the entity in seesion cahce and update it
OptimisticLockException occurs.

[How To Avert OptimisticLockException]
there are 3 ways following.
A. Before step 6, invoking EntityManager.refresh().
B. Using TopLink-specific refresh hint When executes step 6
C. Disable session cache

Is there any other ways to avert the OptimisticLockException ?
Could you please give me some suggestion or comment and any help
is appreciated.

Thanks
-Wu