Monday 27 June 2022

Ehcache: Close all the caches and stop all the services managed by this CacheManager

CacheManager#close method close all the Caches known to this CacheManager and stop all the services managed by this CacheManager.

 

Signature

void close() throws StateTransitionException;

 

Example

cacheManager.close();

 

You will get IllegalStateException, when you try to work with caches after CacheManager is closed.

 


CacheManagerCloseDemo.java

 

package com.sample.app;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;

public class CacheManagerCloseDemo {

	public static void main(String[] args) {
		CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);

		cacheManager.createCache("empCache", CacheConfigurationBuilder
				.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build());

		Cache<Long, String> empCache = cacheManager.getCache("empCache", Long.class, String.class);

		System.out.println("empCache : " + empCache);

		System.out.println("CacheManager status : " + cacheManager.getStatus());

		System.out.println("Closing the CacheManager");
		cacheManager.close();

		System.out.println("CacheManager status : " + cacheManager.getStatus());

		System.out.println("\n");

		try {
			empCache.put(1L, "test");
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("\n");
		try {
			// Throws java.lang.IllegalStateException
			empCache = cacheManager.getCache("empCache", Long.class, String.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

 

Output

mpCache : org.ehcache.core.Ehcache@6ebc05a6
CacheManager status : AVAILABLE
Closing the CacheManager
CacheManager status : UNINITIALIZED


java.lang.IllegalStateException: State is UNINITIALIZED
	at org.ehcache.core.StatusTransitioner.checkAvailable(StatusTransitioner.java:60)
	at org.ehcache.core.EhcacheBase.put(EhcacheBase.java:185)
	at com.sample.app.CacheManagerCloseDemo.main(CacheManagerCloseDemo.java:35)


java.lang.IllegalStateException: State is UNINITIALIZED
	at org.ehcache.core.StatusTransitioner.checkAvailable(StatusTransitioner.java:60)
	at org.ehcache.core.EhcacheManager.getCache(EhcacheManager.java:168)
	at com.sample.app.CacheManagerCloseDemo.main(CacheManagerCloseDemo.java:43)

 

 

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment