Chetan Kinger
Chetan Kinger

Reputation: 15212

NullPointerException while creating two different caches on a Terracotta cluster

I am currently using the enterprise version of EhCache for implementing caching in our application. As explained here, I am creating two different cache instances programmatically by using the following constructor in my EhCache class which I use to manage EhCache creation :

public class EhCache implements ICacheAccess {    

    private String name;
    private Cache ehCache;
    private CacheAttributes attrs;

    public EhCache(final String name, final CacheAttributes attrs) {
                this.name = name;
                this.attrs = attrs;

                Configuration configuration = new Configuration();


                TerracottaClientConfiguration terracottaConfig 
                    = new TerracottaClientConfiguration();

                configuration.addTerracottaConfig(terracottaConfig);

                final CacheConfiguration cfg = new CacheConfiguration(name, attrs.cacheSize)          
                    .eternal(attrs.eternal).terracotta(new TerracottaConfiguration())
                    .timeToLiveSeconds(attrs.timeToLiveSeconds)
                    .timeToIdleSeconds(attrs.timeToIdleSeconds)
                    .statistics(attrs.statistics).overflowToOffHeap(true).maxBytesLocalOffHeap(200,MemoryUnit.MEGABYTES);

                configuration.addCache(cfg);    


                CacheConfiguration defaultCache = new CacheConfiguration("default",
                        1000).eternal(false);
                configuration.addDefaultCache(defaultCache);

                CacheManager mgr = CacheManager.create(configuration);        
                ehCache = mgr.getCache(name);        
                LOGGER.log("ehcache is "+ehCache);           
            } 
}

I then use the following method to create two instances of my EhCache class :

public void testCreateCache(String name) {
        CacheAttributes attrs = new CacheAttributes();        
                attrs.timeToIdleSeconds = 0;
                attrs.timeToLiveSeconds = 0;

        Cache cache = new EhCache(name, attrs);
    }

I call the above method twice in my main method :

testCreateCache("cache1");
testCreateCache("cache2");

cache 1 is created successfully but cache2 is null.

If I interchange the order in which I create the caches :

 testCreateCache("cache2");
 testCreateCache("cache1");

cache 2 is created successfully but cache1 is null.

I am unable to understand why this happens. The first cache is created successfully but the second cache is always null.

Upvotes: 0

Views: 159

Answers (1)

Jaza
Jaza

Reputation: 86

I think your problem is that you call CacheManager.create() twice since CacheManager is a Singleton. Try to call it once after you have added both the caches to the Configuration object.

Upvotes: 1

Related Questions