下面列出了java.util.concurrent.ConcurrentHashMap#clear ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
/**
* 获取缓存数据
* @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;
}
}
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);
}
/**
* 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();
}
@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);
}
/**
* 设置缓存(指定缓存有效时间)
* @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);
}
}
}
@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);
}
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();
}
}
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();
}
}
@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);
}
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();
}
}
@ManagedOperation
public void cleanErrors() {
for (ConcurrentHashMap<String, LongCounter> v : errorCounterMap.values()) {
v.clear();
}
errorCount.set(0);
m_errors.clearErrorList();
}
/**
* 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));
}
@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);
}
}
@Override
public void clear() {
for (ConcurrentHashMap<K, V> segment : segments) {
segment.clear();
}
}
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;
}
/**
* clear removes all pairs
*/
public void testClear() {
ConcurrentHashMap map = map5();
map.clear();
assertEquals(0, map.size());
}
@Override
public void process(ConcurrentHashMap<K, V> impl) {
impl.clear();
}
/**
* clear removes all pairs
*/
public void testClear() {
ConcurrentHashMap map = map5();
map.clear();
assertEquals(0, map.size());
}
@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);
}