JPA synchronizing entity accessors
Here's the setup: the entity class has the collection of other entities that is loaded lazily. The trick is, I need to perform some data-related work (for example, I want to calculate certain checksum with the elements of collection).
The trick here is that I want to avoid at all costs the race conditions like: "someone has updated the entity while I was making my data calculations". In the normal circumstances I'll just declare getter/setter synchronized and will be happy with it. BUT a开发者_JS百科s far as I understand, if the other thread decides to update the entity state from the database, while I'm in the middle of calculating my checksum it will completely ignore the "synchronized" methods (it will access the field directly).
I might be wrong tough. So the question is: is there any way to "lock" the access to the part of the entity or to the whole entity itself for the time of initial checksum calculations?
Thanks in advance! P.S. If you need a code snippet to illustrate the problem - just let me know. So far I think the question is pretty clear.
I might be wrong tough. So the question is: is there any way to "lock" the access to the part of the entity or to the whole entity itself for the time of initial checksum calculations?
JPA 2.0 supports pessimistic concurrency and you can read an entity and lock the corresponding row at the database level (note that the mentioned linked predates the final version of the JPA 2.0 specification and doesn't reflect all the possible values of the LockMode
enum, but you get the idea).
And if you are using JPA 1.0, I'm afraid you'll have to use native SQL to perform the equivalent SELECT ... FOR UPDATE
.
References
- JPA 2.0 specification
- Section 3.4.4 "Lock Modes"
You can also use @Version on an attribute of your Entity (works in JPA 1.0)
http://java.dzone.com/articles/jpa-20-concurrency-and-locking
精彩评论