com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.Builder Java Examples

The following examples show how to use com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap.Builder. 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: LeastRecentlyUsedTransienceManager.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
LeastRecentlyUsedTransienceManager(int minimunSize, int maximunSize, int concurrencyLevel, TransienceMonitor monitor) {
    Builder<K, T> builder = new Builder<>();
    builder.initialCapacity(minimunSize);
    builder.maximumWeightedCapacity(maximunSize);
    builder.concurrencyLevel(concurrencyLevel);
    if (monitor != null) {
        builder.listener(new EvictionListener<K, T>() {

            public void onEviction(K key, T value) {
                monitor.notifyExchanged(key, value);
            };

        });
    }
    this.transience = builder.build();
}
 
Example #2
Source File: UtilCache.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/** Constructor which specifies the cacheName as well as the sizeLimit, expireTime and useSoftReference.
 * The passed sizeLimit, expireTime and useSoftReference will be overridden by values from cache.properties if found.
 * @param sizeLimit The sizeLimit member is set to this value
 * @param expireTimeMillis The expireTime member is set to this value
 * @param cacheName The name of the cache.
 * @param useSoftReference Specifies whether or not to use soft references for this cache.
 */
private UtilCache(String cacheName, int sizeLimit, int maxInMemory, long expireTimeMillis, boolean useSoftReference, String propName, String... propNames) {
    this.name = cacheName;
    this.sizeLimit = sizeLimit;
    this.maxInMemory = maxInMemory;
    this.expireTimeNanos = TimeUnit.NANOSECONDS.convert(expireTimeMillis, TimeUnit.MILLISECONDS);
    this.useSoftReference = useSoftReference;
    setPropertiesParams(propName);
    setPropertiesParams(propNames);
    int maxMemSize = this.maxInMemory;
    if (maxMemSize == 0) {
        maxMemSize = sizeLimit;
    }
    if (maxMemSize == 0) {
        memoryTable = new ConcurrentHashMap<>();
    } else {
        memoryTable = new Builder<Object, CacheLine<V>>()
        .maximumWeightedCapacity(maxMemSize)
        .listener(this)
        .build();
    }
}
 
Example #3
Source File: UtilCache.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public void setMaxInMemory(int newInMemory) {
    this.maxInMemory = newInMemory;
    Map<Object, CacheLine<V>> oldmap = this.memoryTable;

    if (newInMemory > 0) {
        if (this.memoryTable instanceof ConcurrentLinkedHashMap<?, ?>) {
            ((ConcurrentLinkedHashMap<?, ?>) this.memoryTable).setCapacity(newInMemory);
            return;
        }
        this.memoryTable =new Builder<Object, CacheLine<V>>()
                .maximumWeightedCapacity(newInMemory)
                .build();
    } else {
        this.memoryTable = new ConcurrentHashMap<>();
    }

    this.memoryTable.putAll(oldmap);
}
 
Example #4
Source File: MultiThreadedTest.java    From concurrentlinkedhashmap with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "builder")
public void weightedConcurrency(Builder<Integer, List<Integer>> builder) {
  final ConcurrentLinkedHashMap<Integer, List<Integer>> map = builder
      .weigher(Weighers.<Integer>list())
      .maximumWeightedCapacity(threads)
      .concurrencyLevel(threads)
      .build();
  final Queue<List<Integer>> values = new ConcurrentLinkedQueue<List<Integer>>();
  for (int i = 1; i <= threads; i++) {
    Integer[] array = new Integer[i];
    Arrays.fill(array, Integer.MIN_VALUE);
    values.add(Arrays.asList(array));
  }
  executeWithTimeOut(map, new Callable<Long>() {
    @Override public Long call() throws Exception {
      return timeTasks(threads, new Runnable() {
        @Override public void run() {
          List<Integer> value = values.poll();
          for (int i = 0; i < iterations; i++) {
            map.put(i % 10, value);
          }
        }
      });
    }
  });
}
 
Example #5
Source File: MultiThreadedTest.java    From concurrentlinkedhashmap with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "builder")
public void concurrency(Builder<Integer, Integer> builder) {
  List<Integer> keys = newArrayList();
  Random random = new Random();
  for (int i = 0; i < iterations; i++) {
    keys.add(random.nextInt(iterations / 100));
  }
  final List<List<Integer>> sets = shuffle(threads, keys);
  final ConcurrentLinkedHashMap<Integer, Integer> map = builder
      .maximumWeightedCapacity(capacity())
      .concurrencyLevel(threads)
      .build();
  executeWithTimeOut(map, new Callable<Long>() {
    @Override public Long call() throws Exception {
      return timeTasks(threads, new Thrasher(map, sets));
    }
  });
}
 
Example #6
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "builder")
public void evict_weighted(Builder<Integer, Collection<Integer>> builder) {
  ConcurrentLinkedHashMap<Integer, Collection<Integer>> map = builder
      .weigher(Weighers.<Integer>collection())
      .maximumWeightedCapacity(10)
      .build();

  map.put(1, asList(1, 2));
  map.put(2, asList(3, 4, 5, 6, 7));
  map.put(3, asList(8, 9, 10));
  assertThat(map.weightedSize(), is(10L));

  // evict (1)
  map.put(4, asList(11));
  assertThat(map.containsKey(1), is(false));
  assertThat(map.weightedSize(), is(9L));

  // evict (2, 3)
  map.put(5, asList(12, 13, 14, 15, 16, 17, 18, 19, 20));
  assertThat(map.weightedSize(), is(10L));

  assertThat(map, is(valid()));
}
 
Example #7
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 6 votes vote down vote up
@Test
public void evict_efficiency() {
  Map<String, String> expected = new CacheFactory()
      .maximumCapacity((int) capacity())
      .makeCache(CacheType.LinkedHashMap_Lru_Sync);
  Map<String, String> actual = new Builder<String, String>()
      .maximumWeightedCapacity(capacity())
      .build();

  Generator generator = new ScrambledZipfianGenerator(10 * capacity());
  List<String> workingSet = createWorkingSet(generator, 10 * (int) capacity());

  EfficiencyRun runExpected = determineEfficiency(expected, workingSet);
  EfficiencyRun runActual = determineEfficiency(actual, workingSet);

  String reason = String.format("Expected [%s] but was [%s]", runExpected, runActual);
  assertThat(reason, runActual.hitCount, is(runExpected.hitCount));
}
 
Example #8
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "builder")
public void evict_lru(Builder<Integer, Integer> builder) {
  ConcurrentLinkedHashMap<Integer, Integer> map = builder
      .maximumWeightedCapacity(10)
      .build();
  warmUp(map, 0, 10);
  checkContainsInOrder(map, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

  // re-order
  checkReorder(map, asList(0, 1, 2), 3, 4, 5, 6, 7, 8, 9, 0, 1, 2);

  // evict 3, 4, 5
  checkEvict(map, asList(10, 11, 12), 6, 7, 8, 9, 0, 1, 2, 10, 11, 12);

  // re-order
  checkReorder(map, asList(6, 7, 8), 9, 0, 1, 2, 10, 11, 12, 6, 7, 8);

  // evict 9, 0, 1
  checkEvict(map, asList(13, 14, 15), 2, 10, 11, 12, 6, 7, 8, 13, 14, 15);

  assertThat(map, is(valid()));
}
 
Example #9
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test
public void evict_alwaysDiscard() {
  ConcurrentLinkedHashMap<Integer, Integer> map = new Builder<Integer, Integer>()
      .maximumWeightedCapacity(0)
      .listener(listener)
      .build();
  warmUp(map, 0, 100);

  assertThat(map, is(valid()));
  verify(listener, times(100)).onEviction(anyInt(), anyInt());
}
 
Example #10
Source File: WeigherTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "builder")
public void put_withNoOverflow(Builder<Integer, Integer> builder) {
  ConcurrentLinkedHashMap<Integer, Integer> map = builder
      .maximumWeightedCapacity(MAXIMUM_CAPACITY)
      .weigher(weigher)
      .build();
  doReturn(Integer.MAX_VALUE).when(weigher).weightOf(anyInt());
  map.putAll(ImmutableMap.of(1, 1, 2, 2));
  map.weightedSize.set(MAXIMUM_CAPACITY);

  map.put(3, 3);
  assertThat(map.size(), is(2));
  assertThat(map.weightedSize(), is(MAXIMUM_CAPACITY));
}
 
Example #11
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test
public void evict() {
  ConcurrentLinkedHashMap<Integer, Integer> map = new Builder<Integer, Integer>()
      .maximumWeightedCapacity(10)
      .listener(listener)
      .build();
  warmUp(map, 0, 20);

  assertThat(map, is(valid()));
  assertThat(map.size(), is(10));
  assertThat(map.weightedSize(), is(10L));
  verify(listener, times(10)).onEviction(anyInt(), anyInt());
}
 
Example #12
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "builder")
public void evict_maximumCapacity(Builder<Integer, Integer> builder) {
  ConcurrentLinkedHashMap<Integer, Integer> map = builder
      .maximumWeightedCapacity(MAXIMUM_CAPACITY)
      .build();
  map.put(1, 2);
  map.capacity.set(MAXIMUM_CAPACITY);
  map.weightedSize.set(MAXIMUM_CAPACITY);

  map.put(2, 3);
  assertThat(map.weightedSize(), is(MAXIMUM_CAPACITY));
  assertThat(map, is(equalTo(singletonMap(2, 3))));
}
 
Example #13
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test
public void evict_alreadyRemoved() throws Exception {
  final ConcurrentLinkedHashMap<Integer, Integer> map = new Builder<Integer, Integer>()
      .maximumWeightedCapacity(1)
      .listener(listener)
      .build();
  map.put(0, 0);
  map.evictionLock.lock();
  try {
    Node<Integer, Integer> node = map.data.get(0);
    checkStatus(map, node, ALIVE);
    new Thread() {
      @Override public void run() {
        map.put(1, 1);
        assertThat(map.remove(0), is(0));
      }
    }.start();
    await().untilCall(to((Map<?, ?>) map).containsKey(0), is(false));
    checkStatus(map, node, RETIRED);
    map.drainBuffers();

    checkStatus(map, node, DEAD);
    assertThat(map.containsKey(1), is(true));
    verify(listener, never()).onEviction(anyInt(), anyInt());
  } finally {
    map.evictionLock.unlock();
  }
}
 
Example #14
Source File: MemoryLeakTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void beforeMemoryLeakTest() {
  ThreadFactory threadFactory = new ThreadFactoryBuilder()
      .setPriority(Thread.MAX_PRIORITY)
      .setDaemon(true)
      .build();
  statusExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory);
  statusExecutor.scheduleAtFixedRate(newStatusTask(),
      statusInterval, statusInterval, SECONDS);
  map = new Builder<Long, Long>()
      .maximumWeightedCapacity(threads)
      .build();
}
 
Example #15
Source File: BuilderTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test
public void listener_withCustom() {
  Builder<Integer, Integer> builder = new Builder<Integer, Integer>()
      .maximumWeightedCapacity(capacity())
      .listener(listener);
  assertThat(builder.build().listener, is(sameInstance(listener)));
}
 
Example #16
Source File: WeigherTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "builder", expectedExceptions = IllegalArgumentException.class)
public void put_withNegativeWeight(Builder<Integer, Integer> builder) {
  ConcurrentLinkedHashMap<Integer, Integer> map = builder
      .maximumWeightedCapacity(capacity())
      .weigher(weigher).build();
  when(weigher.weightOf(anyInt())).thenReturn(-1);
  map.put(1, 2);
}
 
Example #17
Source File: WeigherTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "builder", expectedExceptions = IllegalArgumentException.class)
public void put_withZeroWeight(Builder<Integer, Integer> builder) {
  ConcurrentLinkedHashMap<Integer, Integer> map = builder
      .maximumWeightedCapacity(capacity())
      .weigher(weigher).build();
  doReturn(0).when(weigher).weightOf(anyInt());
  map.put(1, 2);
}
 
Example #18
Source File: CacheMatrix.java    From jstarcraft-ai with Apache License 2.0 5 votes vote down vote up
public CacheMatrix(int minimunSize, int maximunSize, int concurrencyLevel) {
    Builder<Integer, MathVector> builder = new Builder<>();
    builder.initialCapacity(minimunSize);
    builder.maximumWeightedCapacity(maximunSize);
    builder.concurrencyLevel(concurrencyLevel);
    builder.listener(new EvictionListener<Integer, MathVector>() {

        public void onEviction(Integer key, MathVector value) {
        };

    });
    this.cache = builder.build();
}
 
Example #19
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
private void checkDecreasedCapacity(long newMaxCapacity) {
  ConcurrentLinkedHashMap<Integer, Integer> map = new Builder<Integer, Integer>()
      .maximumWeightedCapacity(capacity())
      .listener(listener)
      .build();
  warmUp(map, 0, capacity());
  map.setCapacity(newMaxCapacity);

  assertThat(map, is(valid()));
  assertThat(map.size(), is(equalTo((int) newMaxCapacity)));
  assertThat(map.capacity(), is(equalTo(newMaxCapacity)));
  verify(listener, times((int) (capacity() - newMaxCapacity))).onEviction(anyInt(), anyInt());
}
 
Example #20
Source File: RedisQualityAttribute.java    From jstarcraft-ai with Apache License 2.0 5 votes vote down vote up
public RedisQualityAttribute(String name, Class<T> type, int minimunSize, int maximunSize, Redisson redisson) {
    this.name = name;
    this.type = type;
    this.indexKey = name + indexSuffix;
    this.sizeKey = name + sizeSuffix;
    Builder<T, Integer> builder = new Builder<>();
    builder.initialCapacity(minimunSize);
    builder.maximumWeightedCapacity(maximunSize);
    this.indexCache = builder.build();
    this.script = redisson.getScript();
    this.indexSignature = script.scriptLoad(indexLua);
    this.sizeAtomic = redisson.getAtomicLong(sizeKey);
}
 
Example #21
Source File: AmqpEventChannel.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
public AmqpEventChannel(EventMode mode, String name, Session session, ContentCodec codec) {
    super(mode, name);
    this.session = session;
    this.codec = codec;
    Builder<Class, MessageProducer> builder = new Builder<>();
    builder.initialCapacity(1000);
    builder.maximumWeightedCapacity(1000);
    this.producers = builder.build();
    this.consumers = new ConcurrentHashMap<>();
}
 
Example #22
Source File: AbstractTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
/** Provides a builder with the capacity set. */
@DataProvider(name = "builder")
public Object[][] providesBuilder() {
  return new Object[][] {{
    new Builder<Object, Object>().maximumWeightedCapacity(capacity())
  }};
}
 
Example #23
Source File: AbstractTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
/** Creates a map that fails if an eviction occurs. */
protected <K, V> ConcurrentLinkedHashMap<K, V> newGuarded() {
  EvictionListener<K, V> guardingListener = guardingListener();
  return new Builder<K, V>()
      .maximumWeightedCapacity(capacity())
      .listener(guardingListener)
      .build();
}
 
Example #24
Source File: EvictionTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "builder", expectedExceptions = IllegalStateException.class)
public void evict_listenerFails(Builder<Integer, Integer> builder) {
  doThrow(new IllegalStateException()).when(listener).onEviction(anyInt(), anyInt());
  ConcurrentLinkedHashMap<Integer, Integer> map = builder
      .maximumWeightedCapacity(0)
      .listener(listener)
      .build();
  try {
    warmUp(map, 0, capacity());
  } finally {
    assertThat(map, is(valid()));
  }
}
 
Example #25
Source File: ConcurrentMapTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
@Test
public void serialize_withCustomSettings() {
  Map<Integer, Collection<Integer>> map = new Builder<Integer, Collection<Integer>>()
      .listener(new SerializableEvictionListener())
      .weigher(Weighers.<Integer>collection())
      .maximumWeightedCapacity(500)
      .initialCapacity(100)
      .concurrencyLevel(32)
      .build();
  map.put(1, singletonList(2));
  assertThat(map, is(reserializable()));
}
 
Example #26
Source File: AbstractTest.java    From concurrentlinkedhashmap with Apache License 2.0 5 votes vote down vote up
private <K, V> ConcurrentLinkedHashMap<K, Iterable<V>> newGuardedWeightedMap() {
  EvictionListener<K, Iterable<V>> guardingListener = guardingListener();
  return new Builder<K, Iterable<V>>()
      .maximumWeightedCapacity(capacity())
      .weigher(Weighers.<V>iterable())
      .listener(guardingListener)
      .build();
}
 
Example #27
Source File: BuilderTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "builder", expectedExceptions = IllegalArgumentException.class)
public void concurrencyLevel_withNegative(Builder<?, ?> builder) {
  builder.concurrencyLevel(-100);
}
 
Example #28
Source File: ConcurrentMapTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "builder")
public void serialize_whenPopulated(Builder<Integer, Integer> builder) {
  Map<Integer, Integer> map = builder.build();
  warmUp(map, 0, capacity());
  assertThat(map, is(reserializable()));
}
 
Example #29
Source File: BuilderTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "builder")
public void weigher_withDefault(Builder<Integer, Integer> builder) {
  assertThat(builder.build().weigher, sameInstance((Object) Weighers.entrySingleton()));
}
 
Example #30
Source File: BuilderTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "builder", expectedExceptions = NullPointerException.class)
public void weigher_withNull_entry(Builder<?, ?> builder) {
  builder.weigher((EntryWeigher<Object, Object>) null);
}