quarta-feira, 13 de março de 2013

Hibernate cache 2nd level


Good explanation i find on terracotta site about hibernate cache.

NonstrictReadWrite:
That a simple strategy that will populate the cache from loads only. It will do so in a very simplistic way, namely put everything that's being loaded into the cache. Neither inserts or updates to the database will populate the cache, updates will result in cache invalidation for the key whether the transaction commits or not.
Reads from that cache region are pretty simplistic as well. When the region is asked for a key, it returns its value (so potentially null in case of a miss).

ReadWrite:
This is slightly more complex strategy that will try to behave more correctly and also keep the cache better updated.
The cache will be populated from loads, as for the NonstrictReadWrite. These puts to the cache will happen only if the key wasn't there already, or if, under a write lock, the version check against the old element passes. That encompasses transaction start time of the current transaction. On new entity creation, after the transaction has committed, the dehydrated representation of that entity will be inserted in the cache, checking under a write lock that is was effectively absent before. Updated entities will be updated in the cache after the transaction commits if, again under a write lock, they were present before and no other transaction was holding a lock to them.
Besides that, the ReadWrite strategy will let Hibernate lock keys in the cache. Hibernate will do that when a state is flushed to the database (update or delete), but the transaction hasn't yet committed. As a result, a concurrent transaction trying to access that value will be considered a miss (in case the lock hasn't "expired") and the database will be hit. This lets the database resolve the proper isolation level between those two transactions.

Transactional:
Hibernate will only "stupidly" access the cache: for reads, updates, inserts and all other operations. It will not try to lock anything ever, but rely on the cache to be properly configured to provide the correct transaction isolation. That strategy can only be used within a JTA environment and comes at the XA price. Caches can then either use a Synchronization on the JTA transaction or register as full blown XA resources with the TransactionManager...

Now to what you are actually experiencing: 
With non strict, the cache gets populated from the load and invalidated from the update. Which results in the second entitymanager hitting the database.

With read write, the update by em1 actually updates the cache, so that em2 hits the cache when retrieving the entry.

The same is true for transactional caches.



Java Obfuscate Properties

Hi there how many times we have fuckin stupid commentaries of , hey the code has a password... bullshit you can always get the password... ...