Java Code Examples for java.util.concurrent.ConcurrentHashMap#clear()

The following examples show how to use java.util.concurrent.ConcurrentHashMap#clear() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
public void removeChannelContext(String inboundName, String subscriberPath, InboundWebsocketChannelContext ctx) {
    ConcurrentHashMap<String, List<InboundWebsocketChannelContext>> subscriberPathMap = inboundSubscriberPathMap
            .get(inboundName);
    List<InboundWebsocketChannelContext> listContext = subscriberPathMap.get(subscriberPath);
    for (Object context : listContext.toArray()) {
        if (((InboundWebsocketChannelContext) context).getChannelIdentifier().equals(ctx.getChannelIdentifier())) {
            listContext.remove(context);
            break;
        }
    }
    if (listContext.isEmpty()) {
        listContext.clear();
        subscriberPathMap.remove(subscriberPath);
    }
    if (subscriberPathMap.isEmpty()) {
        subscriberPathMap.clear();
        inboundSubscriberPathMap.remove(inboundName);
    }
}
 
Example 2
Source Project: SuitAgent   File: CacheByTimeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取缓存数据
 * @param key
 * @return
 * 未设置或缓存有效时间已过都会返回null
 */
public static Object getCache(String key) {
    synchronized (key.intern()){
        if (StringUtils.isNotEmpty(key)){
            ConcurrentHashMap<Long,CacheValue> cache = CATCH.get(key);
            if (cache != null){
                Optional<Long> cacheTime = cache.keySet().stream().findFirst();
                if (cacheTime.isPresent()){
                    CacheValue cacheValue = cache.get(cacheTime.get());
                    long now = System.currentTimeMillis();
                    if ((now - cacheTime.get()) < (cacheValue.getValidTime() * 1000)){
                        return cacheValue.getValue();
                    }else {
                        //缓存失效
                        cache.clear();
                        CATCH.put(key,cache);
                    }
                }
            }
        }
        return null;
    }
}
 
Example 3
public MismatchedImportsDetectorCache()
{
    pathReferences = new ConcurrentHashMap<PsiFile, ConcurrentHashMap<String, String>>();

    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            for(ConcurrentHashMap<String, String> map : pathReferences.values())
            {
                map.clear();
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                Logger.getLogger(MismatchedImportsDetectorCache.class).warn("thread interrupted ", e);
            }
        }
    };
    service.scheduleWithFixedDelay(runnable, 0, 5, TimeUnit.SECONDS);
}
 
Example 4
/**
 * Free direct thread local buffer allocated for Direct IO user's threads.
 */
private void freeDirectBuffers() {
    ConcurrentHashMap<Long, Thread> buffers = managedBuffers;

    if (buffers == null)
        return;

    managedBuffers = null;

    if (log.isDebugEnabled())
        log.debug("Direct IO buffers to be freed: " + buffers.size());

    for (Map.Entry<Long, Thread> next : buffers.entrySet()) {
        Thread th = next.getValue();
        Long addr = next.getKey();

        if (log.isDebugEnabled())
            log.debug(String.format("Free Direct IO buffer [address=%d; Thread=%s; alive=%s]",
                addr, th != null ? th.getName() : "", th != null && th.isAlive()));

        AlignedBuffers.free(addr);
    }

    buffers.clear();
}
 
Example 5
Source Project: Tomcat8-Source-Read   File: StatementCache.java    License: MIT License 5 votes vote down vote up
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    @SuppressWarnings("unchecked")
    ConcurrentHashMap<CacheKey,CachedStatement> statements =
        (ConcurrentHashMap<CacheKey,CachedStatement>)con.getAttributes().get(STATEMENT_CACHE_ATTR);

    if (statements!=null) {
        for (Map.Entry<CacheKey, CachedStatement> p : statements.entrySet()) {
            closeStatement(p.getValue());
        }
        statements.clear();
    }

    super.disconnected(parent, con, finalizing);
}
 
Example 6
Source Project: SuitAgent   File: CacheByTimeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 设置缓存(指定缓存有效时间)
 * @param key
 * @param value
 * @param validTime
 */
public static void setCache(String key,Object value,int validTime) {
    synchronized (key.intern()){
        if (StringUtils.isNotEmpty(key) && value != null){
            ConcurrentHashMap<Long,CacheValue> cache = CATCH.get(key);
            if (cache == null){
                cache = new ConcurrentHashMap<>();
            }
            cache.clear();
            cache.put(System.currentTimeMillis(),new CacheValue(validTime,value));
            CATCH.put(key,cache);
        }
    }
}
 
Example 7
Source Project: Tomcat7.0.67   File: StatementCache.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    @SuppressWarnings("unchecked")
    ConcurrentHashMap<String,CachedStatement> statements =
        (ConcurrentHashMap<String,CachedStatement>)con.getAttributes().get(STATEMENT_CACHE_ATTR);

    if (statements!=null) {
        for (Map.Entry<String, CachedStatement> p : statements.entrySet()) {
            closeStatement(p.getValue());
        }
        statements.clear();
    }

    super.disconnected(parent, con, finalizing);
}
 
Example 8
public void clear() {
    if (k1_k2V_map.size() > 0) {
        for (ConcurrentHashMap<K2, V> k2V_map : k1_k2V_map.values()) {
            k2V_map.clear();
        }
        k1_k2V_map.clear();
    }
}
 
Example 9
public void clear() {
    if (k1_k2V_map.size() > 0) {
        for (ConcurrentHashMap<K2, V> k2V_map : k1_k2V_map.values()) {
            k2V_map.clear();
        }
        k1_k2V_map.clear();
    }
}
 
Example 10
Source Project: tomcatsrc   File: StatementCache.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    @SuppressWarnings("unchecked")
    ConcurrentHashMap<CacheKey,CachedStatement> statements =
        (ConcurrentHashMap<CacheKey,CachedStatement>)con.getAttributes().get(STATEMENT_CACHE_ATTR);

    if (statements!=null) {
        for (Map.Entry<CacheKey, CachedStatement> p : statements.entrySet()) {
            closeStatement(p.getValue());
        }
        statements.clear();
    }

    super.disconnected(parent, con, finalizing);
}
 
Example 11
public void clear() {
    if (k1_k2V_map.size() > 0) {
        for (ConcurrentHashMap<K2, V> k2V_map : k1_k2V_map.values()) {
            k2V_map.clear();
        }
        k1_k2V_map.clear();
    }
}
 
Example 12
@ManagedOperation
public void cleanErrors() {
    for (ConcurrentHashMap<String, LongCounter> v : errorCounterMap.values()) {
        v.clear();
    }
    errorCount.set(0);
    m_errors.clearErrorList();
}
 
Example 13
Source Project: j2objc   File: ConcurrentHashMapTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Maps with same contents are equal
 */
public void testEquals() {
    ConcurrentHashMap map1 = map5();
    ConcurrentHashMap map2 = map5();
    assertEquals(map1, map2);
    assertEquals(map2, map1);
    map1.clear();
    assertFalse(map1.equals(map2));
    assertFalse(map2.equals(map1));
}
 
Example 14
Source Project: bazel   File: HttpCacheClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadAtMostOnce() throws Exception {
  ServerChannel server = null;
  try {
    ConcurrentHashMap<String, byte[]> cacheContents = new ConcurrentHashMap<>();
    server = testServer.start(new HttpCacheServerHandler(cacheContents));

    HttpCacheClient blobStore =
        createHttpBlobStore(server, /* timeoutSeconds= */ 1, /* credentials= */ null);

    ByteString data = ByteString.copyFrom("foo bar", StandardCharsets.UTF_8);
    Digest digest = DIGEST_UTIL.compute(data.toByteArray());
    blobStore.uploadBlob(digest, data).get();

    assertThat(cacheContents).hasSize(1);
    String cacheKey = "/cas/" + digest.getHash();
    assertThat(cacheContents).containsKey(cacheKey);
    assertThat(cacheContents.get(cacheKey)).isEqualTo(data.toByteArray());

    // Clear the remote cache contents
    cacheContents.clear();

    blobStore.uploadBlob(digest, data).get();

    // Nothing should have been uploaded again.
    assertThat(cacheContents).isEmpty();

  } finally {
    testServer.stop(server);
  }
}
 
Example 15
Source Project: jstarcraft-core   File: DelayedHashMap.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void clear() {
    for (ConcurrentHashMap<K, V> segment : segments) {
        segment.clear();
    }
}
 
Example 16
private <T> T manageCache(ConcurrentHashMap<Integer, WithUseCount<T>> cache, Accessor<T> accessor, int n, FieldSelector fieldSelector, int limit) throws IOException
{
    Integer key = Integer.valueOf(n);
    WithUseCount<T> value = cache.get(key);
    if (value == null)
    {
        T made = accessor.get(n, fieldSelector);
        value = new WithUseCount<T>(made, n);
        cache.put(key, value);

        // resize

        if (limit >= 0)
        {
            if (cache.size() >= limit)
            {
                HashMap<Integer, WithUseCount<T>> keep = new HashMap<Integer, WithUseCount<T>>();
                WithUseCount<T>[] existing = new WithUseCount[0];
                synchronized (cache)
                {
                    existing = cache.values().toArray(existing);
                    cache.clear();
                }
                Arrays.sort(existing);

                for (WithUseCount<T> current : existing)
                {
                    keep.put(Integer.valueOf(current.doc), current);
                    if ((current.count.get() == 0) || (keep.size() > (limit / 4)))
                    {
                        break;
                    }
                }
                keep.put(key, value);
                cache.putAll(keep);
            }
        }
    }
    else
    {
        value.count.getAndIncrement();
    }
    return value.object;
}
 
Example 17
/**
 * clear removes all pairs
 */
public void testClear() {
    ConcurrentHashMap map = map5();
    map.clear();
    assertEquals(0, map.size());
}
 
Example 18
Source Project: pravega-samples   File: SharedMap.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void process(ConcurrentHashMap<K, V> impl) {
    impl.clear();
}
 
Example 19
Source Project: j2objc   File: ConcurrentHashMapTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * clear removes all pairs
 */
public void testClear() {
    ConcurrentHashMap map = map5();
    map.clear();
    assertEquals(0, map.size());
}
 
Example 20
Source Project: gameserver   File: MinaMessageQueueTest.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testTryToCreateMessageClient() throws Exception {
	SessionRawMessage rawLocalMessage = createSessionRawMessage(40, 20000);
	SessionRawMessage rawRemoteMessage = createSessionRawMessage(40, 20001);
	
	MinaMessageQueue messageQueue = (MinaMessageQueue)MinaMessageQueue.getInstance();
	TestUtil.setPrivateFieldValue("localMessageServerId", messageQueue, "localhost:10000");
	ConcurrentHashMap<String, MessageClient> messageClientMap = 
			(ConcurrentHashMap<String, MessageClient>)
			TestUtil.getPrivateFieldValue("messageClientMap", messageQueue);
	messageClientMap.clear();
	
	LinkedBlockingQueue internalMessageQueue = (LinkedBlockingQueue)createNiceMock(LinkedBlockingQueue.class);
	internalMessageQueue.put(anyObject());
	expectLastCall().anyTimes();
	Object oldMessageQueue = TestUtil.getPrivateFieldValue("messageQueue", messageQueue);
	TestUtil.setPrivateFieldValue("messageQueue", messageQueue, internalMessageQueue);
	
	GameContext gameContext = GameContext.getTestInstance();
	SessionManager sessionManager = createNiceMock(SessionManager.class);
	//Create the fake machine id
	String fakeMachineId = "www.baidu.com:80";
	expect(sessionManager.findSessionMachineId(anyObject(SessionKey.class))).andReturn(fakeMachineId);
	TestUtil.setPrivateFieldValue("sessionManager", gameContext, sessionManager);
	
	MessageClient messageClient = createMock(MessageClient.class);
	
	assertEquals(0, messageClientMap.keySet().size());
	
	replay(messageClient);
	replay(internalMessageQueue);
	replay(sessionManager);
	
	messageQueue.sessionWrite(rawLocalMessage.getSessionkey(), rawLocalMessage);
	
	verify(messageClient);
	verify(internalMessageQueue);
	verify(sessionManager);
	
	assertEquals(1, messageClientMap.keySet().size());
	assertTrue(messageClientMap.get(fakeMachineId) != null );
	
	TestUtil.setPrivateFieldValue("messageQueue", messageQueue, oldMessageQueue);
}