4.4. Optimistic concurrency control
The only approach that is consistent with high concurrency and high scalability is optimistic concurrency control with versioning. Version checking uses version numbers, or timestamps, to detect conflicting updates (and to prevent lost updates). Hibernate provides for three possible approaches to writing application code that uses optimistic concurrency. The use cases we show are in the context of long application transactions but version checking also has the benefit of preventing lost updates in single database transactions.
4.4.1. Application version checking
In an implementation without much help from the persistence mechanism, each interaction with the database occurs in a new
EntityManagerand the developer is responsible for reloading all persistent instances from the database before manipulating them. This approach forces the application to carry out its own version checking to ensure application transaction isolation. This approach is the least efficient in terms of database access. It is the approach most similar to EJB2 entities:
// foo is an instance loaded by a previous entity manager em = factory.createEntityManager(); EntityTransaction t = em.getTransaction(); t.begin(); int oldVersion = foo.getVersion(); Foo dbFoo = em.find( foo.getClass(), foo.getKey() ); // load the current state if ( dbFoo.getVersion()!=foo.getVersion() ) throw new StaleObjectStateException("Message", oldVersion); dbFoo.setProperty("bar"); t.commit(); em.close();
versionproperty is mapped using
@Version, and the entity manager will automatically increment it during flush if the entity is dirty.
Of course, if you are operating in a low-data-concurrency environment and don't require version checking, you may use this approach and just skip the version check. In that case, last commit wins will be the default strategy for your long application transactions. Keep in mind that this might confuse the users of the application, as they might experience lost updates without error messages or a chance to merge conflicting changes.
Clearly, manual version checking is only feasible in very trivial circumstances and not practical for most applications. Often not only single instances, but complete graphs of modified ojects have to be checked. Hibernate offers automatic version checking with either detached instances or an extended entity manager and persistence context as the design paradigm.