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

The following examples show how to use java.util.concurrent.ConcurrentHashMap#clear() . 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: WebsocketSubscriberPathManager.java    From micro-integrator with Apache License 2.0 7 votes vote down vote up
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 File: CacheByTimeUtil.java    From SuitAgent with 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
Source File: LinuxNativeIoPluginProvider.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: MismatchedImportsDetectorCache.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
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 5
Source File: HttpCacheClientTest.java    From bazel with 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 6
Source File: StatementCache.java    From Tomcat8-Source-Read with 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 7
Source File: ConcurrentHashMapTest.java    From j2objc with 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 8
Source File: SessionizerErrorManager.java    From realtime-analytics with GNU General Public License v2.0 5 votes vote down vote up
@ManagedOperation
public void cleanErrors() {
    for (ConcurrentHashMap<String, LongCounter> v : errorCounterMap.values()) {
        v.clear();
    }
    errorCount.set(0);
    m_errors.clearErrorList();
}
 
Example 9
Source File: DoubleKeyValueMap.java    From AndroidStudyDemo with GNU General Public License v2.0 5 votes vote down vote up
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 File: StatementCache.java    From tomcatsrc with 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
Source File: DoubleKeyValueMap.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
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
Source File: DoubleKeyValueMap.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
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 13
Source File: StatementCache.java    From Tomcat7.0.67 with 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 14
Source File: CacheByTimeUtil.java    From SuitAgent with 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 15
Source File: SharedMap.java    From pravega-samples with Apache License 2.0 4 votes vote down vote up
@Override
public void process(ConcurrentHashMap<K, V> impl) {
    impl.clear();
}
 
Example 16
Source File: ConcurrentHashMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * clear removes all pairs
 */
public void testClear() {
    ConcurrentHashMap map = map5();
    map.clear();
    assertEquals(0, map.size());
}
 
Example 17
Source File: ReferenceCountingReadOnlyIndexReaderFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
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 18
Source File: ConcurrentHashMapTest.java    From j2objc with 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 19
Source File: MinaMessageQueueTest.java    From gameserver with 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);
}
 
Example 20
Source File: DelayedHashMap.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public void clear() {
    for (ConcurrentHashMap<K, V> segment : segments) {
        segment.clear();
    }
}