Java Code Examples for org.ehcache.Cache#put()

The following examples show how to use org.ehcache.Cache#put() . 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: CacheCopierTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyValueOnWrite() throws Exception {
  CacheConfiguration<Long, Person> cacheConfiguration = baseConfig
      .withService(new DefaultCopierConfiguration<>(PersonOnWriteCopier.class, DefaultCopierConfiguration.Type.VALUE))
      .build();

  Cache<Long, Person> cache = cacheManager.createCache("cache", cacheConfiguration);

  Person original = new Person("Bar", 24);
  cache.put(1l, original);

  Person retrieved = cache.get(1l);
  assertNotSame(original, retrieved);
  assertThat(retrieved.name, equalTo("Bar"));
  assertThat(retrieved.age, equalTo(24));

  original.age = 56;
  retrieved = cache.get(1l);
  assertThat(retrieved.age, equalTo(24));

  assertSame(cache.get(1l), cache.get(1l));
}
 
Example 2
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testAgedBatchedIsWritten() throws Exception {
  WriteBehindTestLoaderWriter<String, String> loaderWriter = new WriteBehindTestLoaderWriter<>();
  CacheLoaderWriterProvider cacheLoaderWriterProvider = getMockedCacheLoaderWriterProvider(loaderWriter);

  try (CacheManager cacheManager = managerBuilder().using(cacheLoaderWriterProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testAgedBatchedIsWritten", configurationBuilder()
      .withLoaderWriter(loaderWriter)
      .withService(newBatchedWriteBehindConfiguration(1, SECONDS, 2).build())
      .build());

    CountDownLatch latch = new CountDownLatch(1);
    loaderWriter.setLatch(latch);

    testCache.put("key1", "value");

    if (latch.await(10, SECONDS)) {
      assertThat(loaderWriter.getValueList("key1"), contains("value"));
    } else {
      fail("Took too long to write, assuming batch is not going to be written");
    }
  }
}
 
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: ClusteredCacheExpirationTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNoExpirationPropagatedToHigherTiers() throws CachePersistenceException {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = cacheManagerBuilder(ExpiryPolicyBuilder.noExpiration());

  try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) {

    Map<String, TierStatistics> tierStatistics = statisticsService.getCacheStatistics(CLUSTERED_CACHE).getTierStatistics();
    TierStatistics onheap = tierStatistics.get("OnHeap");
    TierStatistics offheap = tierStatistics.get("OffHeap");

    Cache<Long, String> cache = cacheManager.getCache(CLUSTERED_CACHE, Long.class, String.class);
    for (long i = 0; i < 30; i++) {
      cache.put(i, "value"); // store on the cluster
      cache.get(i); // push it up on heap and offheap tier
    }

    assertThat(onheap.getMappings()).isEqualTo(10);
    assertThat(offheap.getMappings()).isEqualTo(20);
  }
}
 
Example 5
Source File: SimpleEhcacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleRemove2Args() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)));

  testCache.put(1, "one");

  assertThat(testCache.remove(1, "one_"), is(false));
  assertThat(testCache.get(1), is(notNullValue()));
  assertThat(testCache.remove(1, "one"), is(true));
  assertThat(testCache.get(1), is(nullValue()));
}
 
Example 6
Source File: AbstractWriteBehindTestBase.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteBehindQueueSize() throws Exception {

  class TestWriteBehindProvider extends WriteBehindProviderFactory.Provider {

    private WriteBehind<?, ?> writeBehind = null;

    @Override
    @SuppressWarnings("unchecked")
    public <K, V> WriteBehind<K, V> createWriteBehindLoaderWriter(CacheLoaderWriter<K, V> cacheLoaderWriter, WriteBehindConfiguration<?> configuration) {
      this.writeBehind = super.createWriteBehindLoaderWriter(cacheLoaderWriter, configuration);
      return (WriteBehind<K, V>) writeBehind;
    }

    public WriteBehind<?, ?> getWriteBehind() {
      return writeBehind;
    }
  }

  TestWriteBehindProvider writeBehindProvider = new TestWriteBehindProvider();
  WriteBehindTestLoaderWriter<String, String> loaderWriter = new WriteBehindTestLoaderWriter<>();

  try (CacheManager cacheManager = managerBuilder().using(writeBehindProvider).build(true)) {
    Cache<String, String> testCache = cacheManager.createCache("testAgedBatchedIsWritten", configurationBuilder()
      .withService(new DefaultCacheLoaderWriterConfiguration(loaderWriter))
      .withService(newBatchedWriteBehindConfiguration(5, SECONDS, 2).build())
      .build());

    testCache.put("key1", "value1");
    assertThat(writeBehindProvider.getWriteBehind().getQueueSize(), is(1L));
    testCache.put("key2", "value2");

  }
}
 
Example 7
Source File: OverSizeMappingTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testOverSizedObjectGetsReturnedFromLowerTier() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withDefaultSizeOfMaxObjectSize(500, MemoryUnit.B)
      .withDefaultSizeOfMaxObjectGraph(1000)
      .build(true);

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

  Cache<String, String> objectSizeCache = cacheManager.createCache("objectSize",
      objectSize);

  objectSizeCache.put("key1", getOverSizedObject());
  assertThat(objectSizeCache.get("key1"), equalTo(getOverSizedObject()));

  CacheConfiguration<String, ObjectSizeGreaterThanN> objectGraphSize = CacheConfigurationBuilder
      .newCacheConfigurationBuilder(String.class, ObjectSizeGreaterThanN.class,
          newResourcePoolsBuilder()
              .heap(100, MemoryUnit.KB).offheap(10, MemoryUnit.MB).build())
      .build();

  Cache<String, ObjectSizeGreaterThanN> objectGraphSizeCache = cacheManager.createCache("objectGraphSize",
      objectGraphSize);

  objectGraphSizeCache.put("key1", getObjectSizeGreaterThanN(1002));
  assertThat(objectGraphSizeCache.get("key1"), equalTo(getObjectSizeGreaterThanN(1002)));

}
 
Example 8
Source File: SimpleEhcacheTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleReplace3Args() throws Exception {
  Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)));

  testCache.put(1, "one");

  assertThat(testCache.replace(1, "one_", "one@"), is(false));
  assertThat(testCache.replace(1, "one", "one#"), is(true));
  assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one#"));
  assertThat(testCache.replace(2, "two", "two#"), is(false));
}
 
Example 9
Source File: BasicClusteredCacheOpsTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void basicCacheCRUD() throws Exception {
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder
      = CacheManagerBuilder.newCacheManagerBuilder()
      .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.getConnectionURI().resolve("/crud-cm"))
          .autoCreate(server -> server.defaultServerResource("primary-server-resource")));
  final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  try {
    CacheConfiguration<Long, String> config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
        ResourcePoolsBuilder.newResourcePoolsBuilder()
            .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB))).build();

    Cache<Long, String> cache = cacheManager.createCache("clustered-cache", config);
    cache.put(1L, "The one");
    assertThat(cache.containsKey(2L), is(false));
    cache.put(2L, "The two");
    assertThat(cache.containsKey(2L), is(true));
    cache.put(1L, "Another one");
    cache.put(3L, "The three");
    assertThat(cache.get(1L), equalTo("Another one"));
    assertThat(cache.get(2L), equalTo("The two"));
    assertThat(cache.get(3L), equalTo("The three"));
    cache.remove(1L);
    assertThat(cache.get(1L), is(nullValue()));

    cache.clear();
    assertThat(cache.get(1L), is(nullValue()));
    assertThat(cache.get(2L), is(nullValue()));
    assertThat(cache.get(3L), is(nullValue()));
  } finally {
    cacheManager.close();
  }
}
 
Example 10
Source File: SimpleOsgiTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static void testEhcache3AsBundle() {
  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
    .withCache("myCache", newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .build())
    .build(true);

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

  myCache.put(42L, "DaAnswer!");
  assertEquals("DaAnswer!", myCache.get(42L));
}
 
Example 11
Source File: ClusteredOsgiTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static void testProgrammaticClusteredCache(OsgiTestUtils.Cluster cluster) throws Throwable {
  try (PersistentCacheManager cacheManager = newCacheManagerBuilder()
    .with(cluster(cluster.getConnectionUri()).autoCreate(c -> c))
    .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder().with(clusteredDedicated("main", 2, MemoryUnit.MB))))
    .build(true)) {

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

    cache.put(1L, "value");
    assertThat(cache.get(1L), is("value"));
  }
}
 
Example 12
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore("Works but by sending a really low level exception. Need to be fixed to get the expected CachePersistenceException")
public void testTerminationBeforeCacheManagerDestroyCache() throws Exception {
  CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
                  .autoCreate(server -> server.defaultServerResource("primary-server-resource")))
          .withCache("simple-cache",
              CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                  ResourcePoolsBuilder.newResourcePoolsBuilder()
                      .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB))));
  PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false);
  cacheManager.init();

  Cache<Long, String> cache = cacheManager.getCache("simple-cache", Long.class, String.class);
  cache.put(1L, "un");
  cache.put(2L, "deux");
  cache.put(3L, "trois");

  cacheManager.removeCache("simple-cache");

  CLUSTER.get().getClusterControl().terminateAllServers();

  assertExceptionOccurred(CachePersistenceException.class,
    new TimeLimitedTask<Void>(ofSeconds(10)) {
      @Override
      Void runTask() throws Exception {
        cacheManager.destroyCache("simple-cache");
        return null;
      }
    });
}
 
Example 13
Source File: BasicClusteredLoaderWriterTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoaderWriterMultipleClients() {

  TestCacheLoaderWriter loaderWriter = new TestCacheLoaderWriter();

  CacheConfiguration<Long, String> cacheConfiguration = getCacheConfiguration(loaderWriter);

  try (CacheManager cacheManager1 = CacheManagerBuilder
          .newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("cache-1", cacheConfiguration)
          .build(true)) {

    try (CacheManager cacheManager2 = CacheManagerBuilder
      .newCacheManagerBuilder()
      .with(cluster(CLUSTER_URI).autoCreate(c -> c))
      .withCache("cache-1", cacheConfiguration)
      .build(true)) {

      Cache<Long, String> client1 = cacheManager1.getCache("cache-1", Long.class, String.class);
      Cache<Long, String> client2 = cacheManager2.getCache("cache-1", Long.class, String.class);

      client1.put(1L, "1");
      client2.put(1L, "2");

      assertThat(client1.get(1L), is("2"));
      assertThat(loaderWriter.storeMap.get(1L), is("2"));

      client1.remove(1L);

      assertThat(client2.get(1L), nullValue());
      assertThat(loaderWriter.storeMap.get(1L), nullValue());
    }
  }
}
 
Example 14
Source File: Tiering.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void updateResourcesAtRuntime() throws InterruptedException {
  ListenerObject listener = new ListenerObject();
  CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder
    .newEventListenerConfiguration(listener, EventType.EVICTED).unordered().synchronous();

  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
    ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES))
    .withService(cacheEventListenerConfiguration)
    .build();

  CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration)
    .build(true);

  Cache<Long, String> cache = cacheManager.getCache("cache", Long.class, String.class);
  for(long i = 0; i < 20; i++ ){
    cache.put(i, "Hello World");
  }
  assertThat(listener.evicted(), is(10));

  cache.clear();
  listener.resetEvictionCount();

  // tag::updateResourcesAtRuntime[]
  ResourcePools pools = ResourcePoolsBuilder.newResourcePoolsBuilder().heap(20L, EntryUnit.ENTRIES).build(); // <1>
  cache.getRuntimeConfiguration().updateResourcePools(pools); // <2>
  assertThat(cache.getRuntimeConfiguration().getResourcePools()
    .getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L));
  // end::updateResourcesAtRuntime[]

  for(long i = 0; i < 20; i++ ){
    cache.put(i, "Hello World");
  }
  assertThat(listener.evicted(), is(0));

  cacheManager.close();
}
 
Example 15
Source File: TerminatedServerTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * If the server goes down, the client should not freeze on a server call. It should timeout and answer using
 * the resilience strategy. Whatever the number of calls is done afterwards.
 *
 * @throws Exception
 */
@Test
public void testTerminationFreezesTheClient() throws Exception {
  Duration readOperationTimeout = Duration.ofMillis(100);

  try(PersistentCacheManager cacheManager =
        CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER.get().getConnectionURI().resolve("/").resolve(testName.getMethodName()))
            .timeouts(TimeoutsBuilder.timeouts()
              .read(readOperationTimeout))
            .autoCreate(server -> server.defaultServerResource("primary-server-resource")))
          .withCache("simple-cache",
            CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder()
                .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB))))
          .build(true)) {

    Cache<Long, String> cache = cacheManager.getCache("simple-cache", Long.class, String.class);
    cache.put(1L, "un");

    CLUSTER.get().getClusterControl().terminateAllServers();

    // Fill the inflight queue and check that we wait no longer than the read timeout
    for (int i = 0; i < CLIENT_MAX_PENDING_REQUESTS; i++) {
      cache.get(1L);
    }

    // The resilience strategy will pick it up and not exception is thrown
    new TimeLimitedTask<Void>(readOperationTimeout.multipliedBy(2)) { // I multiply by 2 to let some room after the expected timeout
      @Override
      Void runTask() {
        cache.get(1L); // the call that could block
        return null;
      }
    }.run();

  } catch(StateTransitionException e) {
    // On the cacheManager.close(), it waits for the lease to expire and then throw this exception
  }
}
 
Example 16
Source File: DefaultManagementRegistryServiceTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testCanGetStats() {
  String queryStatisticName = "Cache:HitCount";

  CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10))
      .build();

  ManagementRegistryService managementRegistry = new DefaultManagementRegistryService(new DefaultManagementRegistryConfiguration().setCacheManagerAlias("myCM"));

  try(CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .withCache("aCache1", cacheConfiguration)
      .withCache("aCache2", cacheConfiguration)
      .using(managementRegistry)
      .build(true)) {

    Context context1 = Context.empty()
      .with("cacheManagerName", "myCM")
      .with("cacheName", "aCache1");

    Context context2 = Context.empty()
      .with("cacheManagerName", "myCM")
      .with("cacheName", "aCache2");

    Cache<Long, String> cache1 = cacheManager.getCache("aCache1", Long.class, String.class);
    Cache<Long, String> cache2 = cacheManager.getCache("aCache2", Long.class, String.class);

    cache1.put(1L, "one");
    cache2.put(3L, "three");

    cache1.get(1L);
    cache1.get(2L);
    cache2.get(3L);
    cache2.get(4L);

    Builder builder1 = managementRegistry.withCapability("StatisticsCapability")
      .queryStatistic(queryStatisticName)
      .on(context1);

    ContextualStatistics counters = getResultSet(builder1, context1, null, queryStatisticName).getResult(context1);
    Number counterHistory1 = counters.<Number>getLatestSampleValue(queryStatisticName).get();

    assertThat(counters.size()).isEqualTo(1);
    assertThat(counterHistory1.longValue()).isEqualTo(1L);

    Builder builder2 = managementRegistry.withCapability("StatisticsCapability")
      .queryStatistic(queryStatisticName)
      .on(context1)
      .on(context2);
    ResultSet<ContextualStatistics> allCounters = getResultSet(builder2, context1, context2, queryStatisticName);

    assertThat(allCounters.size()).isEqualTo(2);
    assertThat(allCounters.getResult(context1).size()).isEqualTo(1);
    assertThat(allCounters.getResult(context2).size()).isEqualTo(1);

    assertThat(allCounters.getResult(context1).getLatestSampleValue(queryStatisticName).get()).isEqualTo(1L);
    assertThat(allCounters.getResult(context2).getLatestSampleValue(queryStatisticName).get()).isEqualTo(1L);
  }
}
 
Example 17
Source File: XACacheTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testCopiers() throws Exception {
  CacheConfigurationBuilder<Long, String> cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
      newResourcePoolsBuilder()
              .heap(10, EntryUnit.ENTRIES)
              .offheap(10, MemoryUnit.MB)
              .disk(20, MemoryUnit.MB, true));

  cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
      .with(new CacheManagerPersistenceConfiguration(getStoragePath()))
      .withCache("txCache1", cacheConfigurationBuilder
              .withService(new XAStoreConfiguration("txCache1"))
              .withService(new DefaultCopierConfiguration<>(LongCopier.class, DefaultCopierConfiguration.Type.KEY))
              .withService(new DefaultCopierConfiguration<>(StringCopier.class, DefaultCopierConfiguration.Type.VALUE))
              .build()
      )
      .withCache("txCache2", cacheConfigurationBuilder
          .withService(new XAStoreConfiguration("txCache2"))
          .withService(new DefaultCopierConfiguration<>(LongCopier.class, DefaultCopierConfiguration.Type.KEY))
          .withService(new DefaultCopierConfiguration<>(StringCopier.class, DefaultCopierConfiguration.Type.VALUE))
          .build())
      .using(new DefaultTimeSourceService(new TimeSourceConfiguration(testTimeSource)))
      .using(new LookupTransactionManagerProviderConfiguration(BitronixTransactionManagerLookup.class))
      .build(true);

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

  transactionManager.begin();
  {
    txCache1.put(1L, "one");
    txCache2.put(1L, "un");
  }
  transactionManager.commit();


  transactionManager.begin();
  {
    txCache1.put(1L, "eins");
    txCache2.put(1L, "uno");
  }
  transactionManager.commit();


  transactionManager.begin();
  {
    assertThat(txCache1.get(1L), equalTo("eins"));
    assertThat(txCache2.get(1L), equalTo("uno"));
  }
  transactionManager.commit();
}
 
Example 18
Source File: EhcacheBulkMethodsITest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveAll_cache_writer_throws_exception() throws Exception {
  CacheConfigurationBuilder cacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class,
      heap(100));

  CacheLoaderWriterProvider cacheLoaderWriterProvider = mock(CacheLoaderWriterProvider.class);
  CacheLoaderWriter cacheLoaderWriterThatThrows = mock(CacheLoaderWriter.class);
  doThrow(new Exception("Simulating an exception from the cache writer")).when(cacheLoaderWriterThatThrows).deleteAll(ArgumentMatchers.any(Iterable.class));
  when(cacheLoaderWriterProvider.createCacheLoaderWriter(anyString(), ArgumentMatchers.any(CacheConfiguration.class))).thenReturn(cacheLoaderWriterThatThrows);

  CacheManagerBuilder<CacheManager> managerBuilder = CacheManagerBuilder.newCacheManagerBuilder().using(cacheLoaderWriterProvider);
  CacheConfiguration<String, String> cacheConfiguration = cacheConfigurationBuilder.withLoaderWriter(cacheLoaderWriterThatThrows)
          .build();
  CacheManager cacheManager = managerBuilder.withCache("myCache", cacheConfiguration).build(true);

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

  for (int i = 0; i < 3; i++) {
    myCache.put("key" + i, "value" + i);
  }

  doThrow(new RuntimeException("We should not have called .write() but .writeAll()")).when(cacheLoaderWriterThatThrows).write(ArgumentMatchers
      .any(), ArgumentMatchers.any());

  Set<String> fewKeysSet = new HashSet<String>() {
    {
      add("key0");
      add("key2");
    }
  };

  // the call to removeAll
  try {
    myCache.removeAll(fewKeysSet);
    fail();
  } catch (BulkCacheWritingException bcwe) {
    assertThat(bcwe.getFailures().size(), is(2));
    assertThat(bcwe.getSuccesses().size(), is(0));
  }

}
 
Example 19
Source File: BasicClusteredCacheTest.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
@Test
public void testClustered3TierCacheTwoClients() throws Exception {
  final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
      newCacheManagerBuilder()
          .with(cluster(CLUSTER_URI).autoCreate(c -> c))
          .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class,
              ResourcePoolsBuilder.newResourcePoolsBuilder().heap(1, EntryUnit.ENTRIES).offheap(1, MemoryUnit.MB)
                  .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)))
              .withService(new ClusteredStoreConfiguration(Consistency.STRONG)));

  try (PersistentCacheManager cacheManager1 = clusteredCacheManagerBuilder.build(true)) {
    try (PersistentCacheManager cacheManager2 = clusteredCacheManagerBuilder.build(true)) {

      final Cache<Long, String> cache1 = cacheManager1.getCache("clustered-cache", Long.class, String.class);
      final Cache<Long, String> cache2 = cacheManager2.getCache("clustered-cache", Long.class, String.class);

      assertThat(cache2.get(1L), nullValue());
      cache1.put(1L, "value1");
      cache1.put(2L, "value2");
      cache1.put(3L, "value3");
      assertThat(cache2.get(1L), is("value1"));
      assertThat(cache2.get(2L), is("value2"));
      assertThat(cache2.get(3L), is("value3"));
      assertThat(cache2.get(1L), is("value1"));
      assertThat(cache2.get(2L), is("value2"));
      assertThat(cache2.get(3L), is("value3"));
      assertThat(cache1.get(1L), is("value1"));
      assertThat(cache1.get(2L), is("value2"));
      assertThat(cache1.get(3L), is("value3"));
      assertThat(cache1.get(1L), is("value1"));
      assertThat(cache1.get(2L), is("value2"));
      assertThat(cache1.get(3L), is("value3"));
      cache1.put(1L, "value11");
      cache1.put(2L, "value12");
      cache1.put(3L, "value13");
      assertThat(cache2.get(1L), is("value11"));
      assertThat(cache2.get(2L), is("value12"));
      assertThat(cache2.get(3L), is("value13"));
      assertThat(cache2.get(1L), is("value11"));
      assertThat(cache2.get(2L), is("value12"));
      assertThat(cache2.get(3L), is("value13"));
      assertThat(cache1.get(1L), is("value11"));
      assertThat(cache1.get(2L), is("value12"));
      assertThat(cache1.get(3L), is("value13"));
      assertThat(cache1.get(1L), is("value11"));
      assertThat(cache1.get(2L), is("value12"));
      assertThat(cache1.get(3L), is("value13"));
    }
  }
}
 
Example 20
Source File: OnHeapEvictionStrategyTest.java    From ehcache3 with Apache License 2.0 3 votes vote down vote up
@Test
public void noExpiryGet() {
  Cache<Integer, String> cache = createCache(ExpiryPolicyBuilder.noExpiration());

  cache.put(1, "a");

  timeSource.setTimeMillis(Long.MAX_VALUE);

  assertThat(cache.get(1)).isEqualTo("a");
}