views:

18

answers:

1

Hello guys,

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 as 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.

+2  A: 

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"
Pascal Thivent
*If* you are using a JPA 2.0 implementation, I might expand a bit if required. But I prefer to wait for a confirmation before doing so.
Pascal Thivent
Please do, I'm using the JPA 2.0 Toplink implementation. Thank you for your answer anyway.
Juriy
@Juriy I will (a bit later). Meanwhile, downloading the spec and reading the section I mentioned would be a very good idea :) PS: I guess you meant EclipseLink, TopLink is a JPA 1.0 implementation.
Pascal Thivent
Thanks, I think I can make it from the point. Basically the main problem for me now is that I thought I'm working with JPA 2.0 while it was 1.0...
Juriy
@Juriy Then you'll have to use a native query and a `SELECT ... FOR UPDATE`
Pascal Thivent