Java Code Examples for org.ehcache.CacheManager#close()

The following examples show how to use org.ehcache.CacheManager#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestEhcache.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
@Test
public void testTem() {
    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("preConfigured",
       CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)))
    .build();

    cacheManager.init();

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

    Cache<Long, String> myCache = cacheManager.createCache("myCache",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)));

    myCache.put(1L, "da one!");
    myCache.putIfAbsent(0L, "ee");
    String value = myCache.get(1L);

    System.out.println("Value is " + value);
    cacheManager.removeCache("preConfigured");
    cacheManager.close();
}
 
Example 2
Source File: TieringTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTieredStore() throws Exception {
  CacheConfiguration<Long, String> tieredCacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).disk(10L, MemoryUnit.MB))
      .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(new File(System.getProperty("java.io.tmpdir") + "/tiered-cache-data")))
      .withCache("tiered-cache", tieredCacheConfiguration).build(true);

  Cache<Long, String> tieredCache = cacheManager.getCache("tiered-cache", Long.class, String.class);

  tieredCache.put(1L, "one");

  assertThat(tieredCache.get(1L), equalTo("one")); // probably coming from disk
  assertThat(tieredCache.get(1L), equalTo("one")); // probably coming from heap

  cacheManager.close();
}
 
Example 3
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheEventListener() {
  // tag::cacheEventListener[]
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(new ListenerObject(), EventType.CREATED, EventType.UPDATED) // <1>
      .unordered().asynchronous(); // <2>

  final CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("foo",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(10))
              .withService(cacheEventListenerConfiguration) // <3>
      ).build(true);

  final Cache<String, String> cache = manager.getCache("foo", String.class, String.class);
  cache.put("Hello", "World"); // <4>
  cache.put("Hello", "Everyone"); // <5>
  cache.remove("Hello"); // <6>
  // end::cacheEventListener[]

  manager.close();
}
 
Example 4
Source File: IntegrationConfigurationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializers() throws Exception {
  Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/default-serializer.xml"));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);
  cacheManager.init();

  Cache<Long, Double> bar = cacheManager.getCache("bar", Long.class, Double.class);
  bar.put(1L, 1.0);
  assertThat(bar.get(1L), equalTo(1.0));

  Cache<String, String> baz = cacheManager.getCache("baz", String.class, String.class);
  baz.put("1", "one");
  assertThat(baz.get("1"), equalTo("one"));

  Cache<String, Object> bam = cacheManager.createCache("bam", newCacheConfigurationBuilder(String.class, Object.class, heap(10)).build());
  bam.put("1", "one");
  assertThat(bam.get("1"), equalTo((Object)"one"));

  cacheManager.close();
}
 
Example 5
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoDefaultThreadPoolFails() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addPool("foo", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(executionServiceConfiguration)
      .build(true);

  try {
    cacheManager.createCache("testCache",
        CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
            .build());
    fail("expected IllegalStateException");
  } catch (IllegalStateException ise) {
    // expected
  }

  cacheManager.close();
}
 
Example 6
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultThreadPoolFailsWithExplicitConfig() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addDefaultPool("dflt", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(new CacheEventDispatcherFactoryConfiguration("foo"))
      .using(executionServiceConfiguration)
      .build(true);

  try {
    cacheManager.createCache("testCache",
        CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
            .build());
    fail("expected IllegalStateException");
  } catch (IllegalStateException ise) {
    // expected
  }

  cacheManager.close();
}
 
Example 7
Source File: WriteBehindProviderFactoryTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAddingWriteBehindConfigurationAtCacheLevel() {
  CacheManagerBuilder<CacheManager> cacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  WriteBehindConfiguration<?> writeBehindConfiguration = WriteBehindConfigurationBuilder.newBatchedWriteBehindConfiguration(Long.MAX_VALUE, SECONDS, 1)
      .concurrencyLevel(3)
      .queueSize(10)
      .build();
  Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (SampleLoaderWriter.class);
  CacheManager cacheManager = cacheManagerBuilder.build(true);
  final Cache<Long, String> cache = cacheManager.createCache("cache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(100))
          .withService(writeBehindConfiguration)
          .withService(new DefaultCacheLoaderWriterConfiguration(klazz))
          .build());
  Collection<ServiceConfiguration<?, ?>> serviceConfiguration = cache.getRuntimeConfiguration()
      .getServiceConfigurations();
  assertThat(serviceConfiguration, IsCollectionContaining.<ServiceConfiguration<?, ?>>hasItem(instanceOf(WriteBehindConfiguration.class)));
  cacheManager.close();
}
 
Example 8
Source File: ThreadPoolsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultThreadPoolSucceedsWithoutConfig() throws Exception {
  PooledExecutionServiceConfiguration executionServiceConfiguration = new PooledExecutionServiceConfiguration();
  executionServiceConfiguration.addDefaultPool("dflt", 2, 4);
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(executionServiceConfiguration)
      .build(true);

  cacheManager.createCache("testCache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
          .build());

  cacheManager.close();
}
 
Example 9
Source File: XAGettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testXACacheWithXMLConfig() throws Exception {
  // tag::testXACacheWithXMLConfig[]
  BitronixTransactionManager transactionManager =
      TransactionManagerServices.getTransactionManager(); // <1>

  URL myUrl = this.getClass().getResource("/docs/configs/xa-getting-started.xml"); // <2>
  Configuration xmlConfig = new XmlConfiguration(myUrl); // <3>
  CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); // <4>
  myCacheManager.init();

  myCacheManager.close();
  transactionManager.shutdown();
  // end::testXACacheWithXMLConfig[]
}
 
Example 10
Source File: XAGettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleXACache() throws Exception {
  // tag::testSimpleXACache[]
  BitronixTransactionManager transactionManager =
      TransactionManagerServices.getTransactionManager(); // <1>

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class)) // <2>
      .withCache("xaCache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, // <3>
                                                          ResourcePoolsBuilder.heap(10)) // <4>
          .withService(new XAStoreConfiguration("xaCache")) // <5>
          .build()
      )
      .build(true);

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

  transactionManager.begin(); // <6>
  {
    xaCache.put(1L, "one"); // <7>
  }
  transactionManager.commit(); // <8>

  cacheManager.close();
  transactionManager.shutdown();
  // end::testSimpleXACache[]
}
 
Example 11
Source File: GettingStarted.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void configuringEventProcessing() {
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
      .newEventListenerConfiguration(ListenerObject.class, EventType.EVICTED).ordered().synchronous();
  // tag::configuringEventProcessingQueues[]
  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                                                                        ResourcePoolsBuilder.heap(5L))
      .withDispatcherConcurrency(10) // <1>
      .withEventListenersThreadPool("listeners-pool")
      .build();
  // end::configuringEventProcessingQueues[]
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
      .build(true);
  cacheManager.close();
}
 
Example 12
Source File: EventNotificationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiThreadedSyncNotifications() throws InterruptedException {
  CacheConfiguration<Number, Number> cacheConfiguration = newCacheConfigurationBuilder(Number.class, Number.class,
      newResourcePoolsBuilder()
          .heap(10L, EntryUnit.ENTRIES))
      .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
      .build(true);
  Cache<Number, Number> cache = cacheManager.getCache("cache", Number.class, Number.class);
  cache.getRuntimeConfiguration()
      .registerCacheEventListener(listener1, EventOrdering.UNORDERED, EventFiring.SYNCHRONOUS, EnumSet
          .of(EventType.CREATED, EventType.EVICTED));

  Thread[] operators = new Thread[10];
  for (int i = 0; i < 10; i++) {
    operators[i] = new Thread(new CachePutOperator(cache, i), "CACHE-PUT-OPERATOR_" + i);
    operators[i].start();
  }
  for (int i = 0; i < 10; i++) {
    operators[i].join();
  }

  int entryCount = 0;
  for (Cache.Entry<Number, Number> entry : cache) {
    entryCount++;
  }

  cacheManager.close();

  assertEquals(100, listener1.created.get());
  assertEquals(100 - entryCount, listener1.evicted.get());
}
 
Example 13
Source File: EventNotificationTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiThreadedSyncAsyncNotificationsWithOffheap() throws InterruptedException {
  AsynchronousListener asyncListener = new AsynchronousListener();
  asyncListener.resetLatchCount(100);

  CacheConfiguration<Number, Number> cacheConfiguration = newCacheConfigurationBuilder(Number.class, Number.class,
      newResourcePoolsBuilder()
              .heap(10L, EntryUnit.ENTRIES).offheap(10, MemoryUnit.MB))
      .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
      .build(true);
  Cache<Number, Number> cache = cacheManager.getCache("cache", Number.class, Number.class);
  cache.getRuntimeConfiguration().registerCacheEventListener(asyncListener, EventOrdering.UNORDERED, EventFiring.ASYNCHRONOUS, EnumSet
      .of(EventType.CREATED, EventType.EXPIRED));

  cache.getRuntimeConfiguration().registerCacheEventListener(listener1, EventOrdering.ORDERED, EventFiring.SYNCHRONOUS, EnumSet
      .of(EventType.CREATED, EventType.EXPIRED));

  Thread[] operators = new Thread[10];
  for (int i = 0; i < 10; i++) {
    operators[i] = new Thread(new CachePutOperator(cache, i), "CACHE-PUT-OPERATOR_" + i);
    operators[i].start();
  }
  for (int i = 0; i < 10; i++) {
    operators[i].join();
  }
  cacheManager.close();

  assertEquals(100, listener1.created.get());
  assertEquals(100, asyncListener.created.get());
}
 
Example 14
Source File: DefaultCacheLoaderWriterProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAddingCacheLoaderWriterConfigurationAtCacheLevel() {
  CacheManagerBuilder<CacheManager> cacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder();
  Class<CacheLoaderWriter<?, ?>> klazz = (Class<CacheLoaderWriter<?, ?>>) (Class) (MyLoader.class);
  CacheManager cacheManager = cacheManagerBuilder.build(true);
  final Cache<Long, String> cache = cacheManager.createCache("cache",
      CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(100))
          .withService(new DefaultCacheLoaderWriterConfiguration(klazz))
          .build());
  Collection<ServiceConfiguration<?, ?>> serviceConfiguration = cache.getRuntimeConfiguration()
      .getServiceConfigurations();
  assertThat(serviceConfiguration, IsCollectionContaining.<ServiceConfiguration<?, ?>>hasItem(instanceOf(DefaultCacheLoaderWriterConfiguration.class)));
  cacheManager.close();
}
 
Example 15
Source File: SimpleClusteredCacheByXmlTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testViaXml() throws Exception {
  final Configuration configuration = new XmlConfiguration(this.getClass().getResource(SIMPLE_CLUSTER_XML));
  final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration);

  assertThat(cacheManager, is(instanceOf(PersistentCacheManager.class)));

  cacheManager.init();

  final Cache<Long, String> cache = cacheManager.getCache("simple-cache", Long.class, String.class);
  assertThat(cache, is(not(nullValue())));

  cacheManager.close();
}
 
Example 16
Source File: TestEhcache.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Test
public void cacheConfigTest() {
    CacheConfiguration<Long, String> usesConfiguredInCacheConfig = CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Long.class, String.class,
                    ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, MemoryUnit.KB).offheap(10,
                            MemoryUnit.MB))
            .withSizeOfMaxObjectGraph(1000).withSizeOfMaxObjectSize(1000, MemoryUnit.B).build();

    CacheConfiguration<Long, String> usesDefaultSizeOfEngineConfig = CacheConfigurationBuilder
            .newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                    .heap(10, MemoryUnit.KB).offheap(10, MemoryUnit.MB))
            .build();

    CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B).withDefaultSizeOfMaxObjectGraph(2000)
            .withCache("usesConfiguredInCache", usesConfiguredInCacheConfig)
            .withCache("usesDefaultSizeOfEngine", usesDefaultSizeOfEngineConfig).build(true);

    Cache<Long, String> usesConfiguredInCache = cacheManager.getCache("usesConfiguredInCache", Long.class,
            String.class);
    usesConfiguredInCache.put(1L, "one");
    
    // assertThat(usesConfiguredInCache.get(1L), equalTo("one"));

    Cache<Long, String> usesDefaultSizeOfEngine = cacheManager.getCache("usesDefaultSizeOfEngine", Long.class,
            String.class);
    usesDefaultSizeOfEngine.put(1L, "one");
    // assertThat(usesDefaultSizeOfEngine.get(1L), equalTo("one"));

    cacheManager.close();
}
 
Example 17
Source File: XmlConfigTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_config_loaded() throws Exception {
  CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(new XmlConfiguration(getClass().getClassLoader().getResource(xml)));
  myCacheManager.init();
  try {
    DefaultManagementRegistryConfiguration registryConfiguration = null;

    for (ServiceCreationConfiguration<?, ?> configuration : myCacheManager.getRuntimeConfiguration().getServiceCreationConfigurations()) {
      if (configuration instanceof DefaultManagementRegistryConfiguration) {
        registryConfiguration = (DefaultManagementRegistryConfiguration) configuration;
        break;
      }
    }

    assertThat(registryConfiguration, is(not(nullValue())));

    // 1st test: CM alia not set, so generated
    if (xml.endsWith("-1.xml")) {
      expectedConfiguration.setCacheManagerAlias(registryConfiguration.getContext().get("cacheManagerName"));
    }

    assertThat(registryConfiguration.getCacheManagerAlias(), equalTo(expectedConfiguration.getCacheManagerAlias()));
    assertThat(registryConfiguration.getCollectorExecutorAlias(), equalTo(expectedConfiguration.getCollectorExecutorAlias()));
    assertThat(registryConfiguration.getContext(), equalTo(expectedConfiguration.getContext()));
    assertThat(registryConfiguration.getTags(), equalTo(expectedConfiguration.getTags()));

  } finally {
    myCacheManager.close();
  }
}
 
Example 18
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCloseWhenRuntimeCacheCreationFails() throws Exception {
  Store.Provider storeProvider = mock(Store.Provider.class);
  when(storeProvider.rank(any(Set.class), any(Collection.class))).thenReturn(1);
  doThrow(new Error("Test EhcacheManager close.")).when(storeProvider).createStore(any(Store.Configuration.class), ArgumentMatchers.<ServiceConfiguration>any());

  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  final CacheManager cacheManager = new EhcacheManager(config, Arrays.asList(
      storeProvider,
      mock(CacheLoaderWriterProvider.class),
      mock(WriteBehindProvider.class),
      mock(CacheEventDispatcherFactory.class),
      mock(CacheEventListenerProvider.class),
      mock(LocalPersistenceService.class),
      mock(ResilienceStrategyProvider.class)
  ));

  cacheManager.init();

  CacheConfiguration<Long, String> cacheConfiguration = new TestCacheConfig<>(Long.class, String.class);

  try {
    cacheManager.createCache("cache", cacheConfiguration);
    fail();
  } catch (Error err) {
    assertThat(err.getMessage(), equalTo("Test EhcacheManager close."));
  }

  cacheManager.close();
  assertThat(cacheManager.getStatus(), is(Status.UNINITIALIZED));

}
 
Example 19
Source File: EhcacheManagerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2000L)
public void testCloseWhenCacheCreationFailsDuringInitialization() throws Exception {
  Store.Provider storeProvider = mock(Store.Provider.class);
  when(storeProvider.rank(any(Set.class), any(Collection.class))).thenReturn(1);
  doThrow(new Error("Test EhcacheManager close.")).when(storeProvider).createStore(any(Store.Configuration.class), ArgumentMatchers.<ServiceConfiguration>any());

  CacheConfiguration<Long, String> cacheConfiguration = new TestCacheConfig<>(Long.class, String.class);
  Map<String, CacheConfiguration<?, ?>> caches = newCacheMap();
  caches.put("cache1", cacheConfiguration);
  DefaultConfiguration config = new DefaultConfiguration(caches, null);
  final CacheManager cacheManager = new EhcacheManager(config, Arrays.asList(
      storeProvider,
      mock(CacheLoaderWriterProvider.class),
      mock(WriteBehindProvider.class),
      mock(CacheEventDispatcherFactory.class),
      mock(CacheEventListenerProvider.class),
      mock(LocalPersistenceService.class),
      mock(ResilienceStrategyProvider.class)
  ));

  final CountDownLatch countDownLatch = new CountDownLatch(1);

  Executors.newSingleThreadExecutor().submit(() -> {
    try {
      cacheManager.init();
    } catch (Error err) {
      assertThat(err.getMessage(), equalTo("Test EhcacheManager close."));
      countDownLatch.countDown();
    }
  });
  countDownLatch.await();
  try {
    cacheManager.close();
  } catch (IllegalStateException e) {
    assertThat(e.getMessage(), is("Close not supported from UNINITIALIZED"));
  }
  assertThat(cacheManager.getStatus(), is(Status.UNINITIALIZED));

}
 
Example 20
Source File: EHCacheUtil.java    From webChat with Apache License 2.0 4 votes vote down vote up
public void closeCache(CacheManager manager,String configureName){
    manager.removeCache(configureName);
    manager.close();
}