Chan
Chan

Reputation: 2641

Hibernate Concurrency issue in Java SE application

I am building a Java SE application that is powered by Hibernate. Mainly many Java SE instances would run and there would be many Hibernate Session factories. When one client machine insert an Object to the datasource, other clients won't see it unless I clear the cache. Is there a better mechanism to use in this case? Below is my cache clearing method.

public static void clearCache() {
        HibernateHelper.beginTranscation();
        HibernateHelper.getCurrentSession().clear();
        HibernateHelper.getSessionFactory().evictQueries();
        try {
            Map<String, ClassMetadata> classesMetadata = HibernateHelper
                    .getSessionFactory().getAllClassMetadata();
            for (String entityName : classesMetadata.keySet()) {
                HibernateHelper.getSessionFactory().evictEntity(entityName);
            }
        } catch (Exception e) {
        }
        HibernateHelper.commit();
    }

Please note the fact that I am using the Second Level cache (Memcache) and Query cache as well.

Upvotes: 0

Views: 215

Answers (1)

Santosh
Santosh

Reputation: 17893

The way you are using the L2 cache might cause data inconsistency as your application is using multiple session factories and hence it's distributed and needs distributed cache.

Here is how your system looks

enter image description here

OR

Alternatively you can have a central memcache server which each of the client (with the help of memcached client ) will use. (One memcached used by all users )

The basic requirement is that the changes committed by one user/session factory should be visible to the other users/session factory for leveraging the cache. The code sample given by you is not helpful as it will clean the L2 cache every time a transaction commits. This is anyways done by L2 cache or session cache.

so my suggestions would be

  1. Don't use L2 cache at all hence no local memcache. You are not leveraging it anyways as you are cleaning the cache after every transaction.
  2. If at all L2 cache is needed, use a distributed cache (which is slightly complicated) OR use a single memcached server for all.

Please check this link as well.

Upvotes: 1

Related Questions