Java Code Examples for org.cache2k.Cache#get()

The following examples show how to use org.cache2k.Cache#get() . 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: CacheLoaderTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloadAll() throws Exception {
  final AtomicInteger countLoad =  new AtomicInteger();
  Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {
    @Override
    public void extend(final Cache2kBuilder<Integer, Integer> b) {
      b .loader(new CacheLoader<Integer, Integer>() {
        @Override
        public Integer load(final Integer key) throws Exception {
          return countLoad.incrementAndGet();
        }
      });
    }
  });
  c.get(5);
  CompletionWaiter w = new CompletionWaiter();
  c.reloadAll(toIterable(5, 6), w);
  w.awaitCompletion();
  assertEquals(3, countLoad.get());
  c.reloadAll(toIterable(5, 6), null);
  c.reloadAll(Collections.EMPTY_SET, null);
}
 
Example 2
Source File: EntryProcessorTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void load_changeRefreshTimeInLoaderNoRecord() {
  final long _probeTime = 4711;
  Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {
    @Override
    public void extend(final Cache2kBuilder<Integer, Integer> b) {
      b.wrappingLoader(new AdvancedCacheLoader<Integer, LoadDetail<Integer>>() {
          @Override
          public LoadDetail<Integer> load(final Integer key, final long startTime,
                                          final CacheEntry<Integer,
                                            LoadDetail<Integer>> currentEntry) throws Exception {
            return Loaders.wrapRefreshedTime(key, _probeTime);
          }
        });
    }
  });
  c.get(1);
  c.invoke(1, new EntryProcessor<Integer, Integer, Object>() {
    @Override
    public Object process(final MutableCacheEntry<Integer, Integer> e) {
      assertEquals(0, e.getRefreshedTime());
      return null;
    }
  });
}
 
Example 3
Source File: BasicCacheTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
public void testGetWithSource() {
  CacheLoader<String,Integer> _lengthCountingSource = new CacheLoader<String, Integer>() {
    @Override
    public Integer load(String o) {
      return o.length();
    }
  };
  Cache<String,Integer> c =
    Cache2kBuilder.of(String.class, Integer.class)
      .loader(_lengthCountingSource)
      .eternal(true)
      .build();
  int v = c.get("hallo");
  v = c.get("long string");
  c.close();
}
 
Example 4
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
/**
 * Switch keep data off.
 * Should this refuse operation right away since suppressException and keepDataAfterExpired
 * makes no sense in combination? No, since load requests should suppress exceptions, too.
 */
@Test(expected = RuntimeException.class)
public void testNoSuppressExceptionShortExpiry() {
  BasicCacheTest.OccasionalExceptionSource src = new BasicCacheTest.OccasionalExceptionSource();
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .expireAfterWrite(TestingParameters.MINIMAL_TICK_MILLIS, TimeUnit.MILLISECONDS)
    .retryInterval(TestingParameters.MINIMAL_TICK_MILLIS, TimeUnit.MILLISECONDS)
    .suppressExceptions(true)
    .keepDataAfterExpired(false)
    .loader(src)
    .build();
  c.get(2);
  await(new Condition() {
    @Override
    public boolean check() throws Exception {
      return getInfo().getExpiredCount() > 0;
    }
  });
  c.get(2);
  fail("not reached");
}
 
Example 5
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuppressExceptionLongExpiryAndReload() {
  BasicCacheTest.OccasionalExceptionSource src = new BasicCacheTest.OccasionalExceptionSource();
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .expireAfterWrite(TestingParameters.MAX_FINISH_WAIT_MILLIS, TimeUnit.MINUTES)
    .retryInterval(TestingParameters.MINIMAL_TICK_MILLIS, TimeUnit.MILLISECONDS)
    .suppressExceptions(true)
    .loader(src)
    .build();
  c.get(2);
  syncLoad(new LoaderStarter() {
    @Override
    public void startLoad(final CacheOperationCompletionListener l) {
      c.reloadAll(toIterable(2), l);
    }
  });
  await(new Condition() {
    @Override
    public boolean check() throws Exception {
      return getInfo().getSuppressedExceptionCount() > 0;
    }
  });
  c.get(2);
}
 
Example 6
Source File: WeigherTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void weightAccountedForWithLoader() {
  long _size = 1;
  Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .eternal(true)
    .entryCapacity(-1)
    .weigher(new Weigher<Integer, Integer>() {
      @Override
      public long weigh(final Integer key, final Integer value) {
        return 1;
      }
    })
    .maximumWeight(_size)
    .loader(new IdentIntSource())
    .strictEviction(true)
    .build();
  c.get(1);
  c.get(1);
  assertEquals(1, countEntriesViaIteration());
}
 
Example 7
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void testNeverSuppressWithRetryInterval0() {
  BasicCacheTest.OccasionalExceptionSource src = new BasicCacheTest.OccasionalExceptionSource();
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .expireAfterWrite(TestingParameters.MAX_FINISH_WAIT_MILLIS, TimeUnit.MINUTES)
    .retryInterval(0, TimeUnit.MILLISECONDS)
    .suppressExceptions(true)
    .loader(src)
    .build();
  c.get(2);
  syncLoad(new LoaderStarter() {
    @Override
    public void startLoad(final CacheOperationCompletionListener l) {
      c.reloadAll(toIterable(2), l);
    }
  });
  assertEquals(0, getInfo().getSuppressedExceptionCount());
  assertEquals(2, getInfo().getLoadCount());
}
 
Example 8
Source File: EntryProcessorTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void setException_propagation() {
  final String _TEXT = "set inside process";
  Cache<Integer, Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {
    @Override
    public void extend(final Cache2kBuilder<Integer, Integer> b) {
      b.retryInterval(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    }
  });
  c.invoke(KEY, new EntryProcessor<Integer, Integer, Object>() {
    @Override
    public Object process(final MutableCacheEntry<Integer, Integer> e) throws Exception {
      e.setException(new IllegalStateException(_TEXT));
      return null;
    }
  });
  try {
    c.get(KEY);
    fail();
  } catch (CacheLoaderException ex) {
    assertTrue(ex.getCause().toString().contains(_TEXT));
  }
}
 
Example 9
Source File: WeigherTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void weightUpdatedWithLoader() {
  long _size = 2;
  Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .eternal(true)
    .entryCapacity(-1)
    .weigher(new Weigher<Integer, Integer>() {
      @Override
      public long weigh(final Integer key, final Integer value) {
        return value;
      }
    })
    .maximumWeight(_size)
    .loader(new PatternLoader(1, 1, 100, 1))
    .strictEviction(true)
    .build();
  c.get(1);
  c.get(2);
  assertEquals(2, countEntriesViaIteration());
  reload(2); // 100
  assertEquals(1, countEntriesViaIteration());
  assertTrue("the entry that is updated is never removed", c.containsKey(2));
  reload(1);
  assertEquals(1, countEntriesViaIteration());
  assertFalse("the other entry is removed", c.containsKey(2));
}
 
Example 10
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
@Test
public void refresh_secondTimerEvent_allIsCleared() throws InterruptedException {
  final int KEY = 1;
  final CountingLoader _LOADER = new CountingLoader();
  final long _EXPIRY = 123;
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .refreshAhead(true)
    .expireAfterWrite(_EXPIRY, TimeUnit.MILLISECONDS)
    .loader(_LOADER)
    .keepDataAfterExpired(false)
    .build();
  c.get(KEY);
  await(new Condition() {
    @Override
    public boolean check() throws Exception {
      return getInfo().getTimerEventCount() == 2;
    }
  });
  await(new Condition() {
    @Override
    public boolean check() throws Exception {
      return getInfo().getSize() == 0;
    }
  });
  assertEquals(2, _LOADER.getCount());
}
 
Example 11
Source File: CacheLoaderTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
/**
 * Check that non runtime exceptions from the async loader are wrapped.
 */
@Test
public void testAsyncLoaderExceptionWrapped() {
  final AtomicInteger loaderCalled = new AtomicInteger();
  Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {
    @Override
    public void extend(final Cache2kBuilder<Integer, Integer> b) {
      b.loader(new AsyncCacheLoader<Integer, Integer>() {
        @Override
        public void load(final Integer key,
                         final Context<Integer, Integer> ctx, final Callback<Integer> callback)
          throws Exception {
          loaderCalled.incrementAndGet();
          throw new IOException("test exception");
        }
      });
    }
  });
  try {
    Integer v = c.get(1);
    fail("exception expected");
  } catch (CacheLoaderException expected) {
  } catch (Throwable other) {
    assertNull("unexpected exception", other);
  }
}
 
Example 12
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuppressExceptionImmediateExpiry() throws Exception {
  BasicCacheTest.OccasionalExceptionSource src = new BasicCacheTest.OccasionalExceptionSource();
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .expireAfterWrite(0, TimeUnit.MINUTES)
    .retryInterval(TestingParameters.MINIMAL_TICK_MILLIS, TimeUnit.MILLISECONDS)
    .resilienceDuration(Long.MAX_VALUE, TimeUnit.MILLISECONDS)
    .keepDataAfterExpired(true)
    .loader(src)
    .build();
  c.get(2);
  c.get(2);
  assertEquals(1, getInfo().getSuppressedExceptionCount());
}
 
Example 13
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testRefreshIfAlreadyExpiredLoadTime() {
  final int _COUNT = 3;
  Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
    .refreshAhead(true)
    .eternal(true)
    .expiryPolicy(new ExpiryPolicy<Integer, Integer>() {
      @Override
      public long calculateExpiryTime(final Integer key, final Integer value, final long loadTime, final CacheEntry<Integer, Integer> oldEntry) {
        return loadTime;
      }
    })
    .loader(new IdentIntSource())
    .build();
  c.get(1);
  c.get(2);
  c.get(3);
  await("All refreshed", new Condition() {
    @Override
    public boolean check() {
      return getInfo().getRefreshCount() + getInfo().getRefreshFailedCount() >= _COUNT;
    }
  });
  await("All expired", new Condition() {
    @Override
    public boolean check() {
      return getInfo().getExpiredCount() >= _COUNT;
    }
  });
}
 
Example 14
Source File: CacheLoaderTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Check that exception isn't blocking anything
 */
@Test
public void testAsyncLoaderException() {
  final AtomicInteger loaderCalled = new AtomicInteger();
  Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {
    @Override
    public void extend(final Cache2kBuilder<Integer, Integer> b) {
      b.loader(new AsyncCacheLoader<Integer, Integer>() {
        @Override
        public void load(final Integer key, final Context<Integer, Integer> ctx, final Callback<Integer> callback) {
          loaderCalled.incrementAndGet();
          throw new ExpectedException();
        }
      });
    }
  });
  try {
    Integer v = c.get(1);
    fail("exception expected");
  } catch (CacheLoaderException expected) {
    assertTrue(expected.getCause() instanceof ExpectedException);
  } catch (Throwable other) {
    assertNull("unexpected exception", other);
  }
  c.put(1, 1);
  assertNotNull(c.get(1));
}
 
Example 15
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testValueExpireExceptionsEternal() {
  IntCountingCacheSource g = new IntCountingCacheSource() {
    @Override
    public Integer load(final Integer o) {
      incrementLoadCalledCount();
      if (o == 99) {
        throw new RuntimeException("ouch");
      }
      return o;
    }
  };
  final Cache<Integer, Integer> c = cache = builder(Integer.class, Integer.class)
    .loader(g)
    .expireAfterWrite(Long.MAX_VALUE / 2, TimeUnit.MILLISECONDS)
    .retryInterval(Long.MAX_VALUE, TimeUnit.MILLISECONDS)
    .build();
  assertEquals("no miss", 0, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("one miss", 1, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("one miss", 1, g.getLoaderCalledCount());
  CacheEntry<Integer,Integer> e = c.getEntry(99);
  entryHasException(e);
  assertEquals(RuntimeException.class, e.getException().getClass());
  assertEquals("two miss", 2, g.getLoaderCalledCount());
  assertTrue(((InternalCache) c).getEntryState(99).contains("nextRefreshTime=ETERNAL"));
}
 
Example 16
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Switching to eternal means exceptions expire immediately.
 */
@Test
public void testEternal_keepData() throws Exception {
  IntCountingCacheSource g = new IntCountingCacheSource() {
    @Override
    public Integer load(final Integer o) {
      incrementLoadCalledCount();
      if (o == 99) {
        throw new RuntimeException("ouch");
      }
      return o;
    }
  };
  final Cache<Integer, Integer> c = cache = builder(Integer.class, Integer.class)
    .loader(g)
    .eternal(true)
    .keepDataAfterExpired(true)
    .build();
  assertEquals("no miss", 0, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("one miss", 1, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("one miss", 1, g.getLoaderCalledCount());
  assertTrue(((InternalCache) c).getEntryState(1802).contains("nextRefreshTime=ETERNAL"));
  try {
    Integer obj = c.get(99);
    fail("exception expected");
  } catch (CacheLoaderException ex) {
    assertTrue("no expiry on exception", !ex.toString().contains(EXPIRY_MARKER));
    assertTrue(ex.getCause() instanceof RuntimeException);
  }
  assertEquals("miss", 2, g.getLoaderCalledCount());
  assertTrue(((InternalCache) c).getEntryState(99).contains("state=4"));
  CacheEntry<Integer, Integer> e = c.getEntry(99);
  entryHasException(e);
  assertEquals(RuntimeException.class, e.getException().getClass());
  assertEquals("miss", 3, g.getLoaderCalledCount());
}
 
Example 17
Source File: ExpiryTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
private void checkAlwaysLoaded(final IntCountingCacheSource g, final Cache<Integer, Integer> c) {
  assertEquals("no miss yet", 0, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("one miss yet", 1, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("additional miss", 2, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("additional miss", 3, g.getLoaderCalledCount());
  c.get(1802);
  assertEquals("additional miss", 4, g.getLoaderCalledCount());
}
 
Example 18
Source File: CacheLoaderTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncLoaderContextProperties_withException() {
  final AtomicInteger loaderCalled = new AtomicInteger();
  Cache<Integer,Integer> c = target.cache(new CacheRule.Specialization<Integer, Integer>() {
    @Override
    public void extend(final Cache2kBuilder<Integer, Integer> b) {
      b.expireAfterWrite(TestingParameters.MAX_FINISH_WAIT_MILLIS, TimeUnit.MILLISECONDS);
      b.loader(new AsyncCacheLoader<Integer, Integer>() {
        @Override
        public void load(final Integer key, final Context<Integer, Integer> ctx, final Callback<Integer> callback) {
          int cnt = loaderCalled.getAndIncrement();
          if (cnt == 0) {
            assertNull(ctx.getCurrentEntry());
          } else {
            assertNull(ctx.getCurrentEntry().getValue());
            assertNotNull(ctx.getCurrentEntry().getException());
          }
          callback.onLoadFailure(new ExpectedException());
        }
      });
    }
  });
  try {
    Integer v = c.get(1);
    fail("exception expected");
  } catch (CacheLoaderException ex) {
    assertTrue(ex.getCause() instanceof ExpectedException);
  }
  assertNotNull("exception cached", c.peekEntry(1).getException());
  reload(c, 1);
}
 
Example 19
Source File: RejectNullValueTest.java    From cache2k with Apache License 2.0 4 votes vote down vote up
@Test(expected = CacheLoaderException.class)
public void get_expiryPolicy_exception() {
  Cache<Integer, Integer> c = target.cache();
  c.get(8);
}
 
Example 20
Source File: SlowExpiryTest.java    From cache2k with Apache License 2.0 4 votes vote down vote up
@Test
public void testExceptionExpirySuppressTwiceWaitForExceptionExpiry() throws Exception {
  final long _EXCEPTION_EXPIRY_MILLIS =  TestingParameters.MINIMAL_TICK_MILLIS;
  final BasicCacheTest.OccasionalExceptionSource src = new BasicCacheTest.PatternExceptionSource(false, true, false);
  final Cache<Integer, Integer> c = builder(Integer.class, Integer.class)
      .expireAfterWrite(0, TimeUnit.MINUTES)
      .retryInterval(_EXCEPTION_EXPIRY_MILLIS, TimeUnit.MILLISECONDS)
      .resilienceDuration(33, TimeUnit.MINUTES)
      .keepDataAfterExpired(true)
      .loader(src)
      .build();
  int _exceptionCount = 0;
  try {
    c.get(1);
  } catch (CacheLoaderException e) {
    _exceptionCount++;
  }
  assertEquals("no exception", 0, _exceptionCount);
  c.get(2); // value is fetched
  within(_EXCEPTION_EXPIRY_MILLIS)
    .work(new Runnable() {
      @Override
      public void run() {
        c.get(2); // exception gets suppressed
      }
    })
    .check(new Runnable() {
      @Override
      public void run() {
        InternalCacheInfo inf = getInfo();
        assertEquals(1, inf.getSuppressedExceptionCount());
        assertEquals(1, inf.getLoadExceptionCount());
        assertNotNull(src.key2count.get(2));
      }
    });
  await(TestingParameters.MAX_FINISH_WAIT_MILLIS, new Condition() {
    @Override
    public boolean check() {
      c.get(2); // value is fetched, again if expired
      return src.key2count.get(2).get() == 3;
    }
  });
}