Java Code Examples for java.util.concurrent.ConcurrentMap#clear()
The following examples show how to use
java.util.concurrent.ConcurrentMap#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: BaseCached.java From roncoo-education with MIT License | 6 votes |
public void reload() { Long timeStart = System.currentTimeMillis(); ConcurrentMap<K, V> newCached = createNewCahcedObject(); ConcurrentMap<K, V> tempCached = cached; // reload from db reloadFromDb(newCached); if (newCached.isEmpty()) { logger.error(this.getClass().getName() + " reload elements is empty"); return; } try { lock.writeLock().lock(); resetCachedObject(newCached); tempCached.clear(); tempCached = null; } finally { lock.writeLock().unlock(); } logger.warn("缓存更新所使用时间:" + (System.currentTimeMillis() - timeStart) + "ms"); }
Example 2
Source File: Defaults.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Simulates races by modifying the map within the mapping function. */ @Test public void testConcurrentMap_computeIfAbsent_racy() { final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>(); final Long two = 2L; Function<Long,Long> f, g; // race not detected if function returns null f = (k) -> { map.put(two, 42L); return null; }; assertNull(map.computeIfAbsent(two, f)); assertEquals(42L, (long)map.get(two)); map.clear(); f = (k) -> { map.put(two, 42L); return 86L; }; assertEquals(42L, (long)map.computeIfAbsent(two, f)); assertEquals(42L, (long)map.get(two)); // mapping function ignored if value already exists map.put(two, 99L); assertEquals(99L, (long)map.computeIfAbsent(two, f)); assertEquals(99L, (long)map.get(two)); }
Example 3
Source File: CachedImpl.java From roncoo-adminlte-springmvc with Apache License 2.0 | 6 votes |
public void reload() { Long timeStart = System.currentTimeMillis(); ConcurrentMap<K, V> newCached = createNewCahcedObject(); ConcurrentMap<K, V> tempCached = cached; // reload from db reloadFromDb(newCached); if (newCached.isEmpty()) { logger.error(this.getClass().getName() + " reload elements is empty"); return; } try { lock.writeLock().lock(); resetCachedObject(newCached); tempCached.clear(); tempCached = null; } finally { lock.writeLock().unlock(); } logger.warn("缓存更新所使用时间:" + (System.currentTimeMillis() - timeStart) + "ms"); }
Example 4
Source File: TPStatBuffer.java From joyqueue with Apache License 2.0 | 5 votes |
/** * 清理 */ public void clear() { timer = new AtomicReferenceArray<AtomicLongArray>(length); successTotal.set(0); errorTotal.set(0); sizeTotal.set(0); timeTotal.set(0); // 如果有数据超过了maxTime,则保留map数据,避免创建对象开销 ConcurrentMap<Integer, AtomicLong> exceeds = outstrip.get(); if (exceeds != null) { exceeds.clear(); } }
Example 5
Source File: ExtensionLoaderTest.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Before public void before() throws NoSuchFieldException, IllegalAccessException { Field loaderMap = ExtensionLoaderFactory.class.getDeclaredField("LOADER_MAP"); loaderMap.setAccessible(true); ConcurrentMap<Class, ExtensionLoader> map = ((ConcurrentMap<Class, ExtensionLoader>) loaderMap.get(null)); map.clear(); }
Example 6
Source File: JmsPoolConnectionFactoryTest.java From pooled-jms with Apache License 2.0 | 5 votes |
private void doTestConcurrentCreateGetsUniqueConnection(boolean createOnStart) throws Exception { final int numConnections = 2; final MockJMSConnectionFactory mock = new MockJMSConnectionFactory(); cf = new JmsPoolConnectionFactory(); cf.setConnectionFactory(mock); cf.setMaxConnections(numConnections); cf.start(); final ConcurrentMap<UUID, Connection> connections = new ConcurrentHashMap<>(); final ExecutorService executor = Executors.newFixedThreadPool(numConnections); for (int i = 0; i < numConnections; ++i) { executor.execute(new Runnable() { @Override public void run() { try { JmsPoolConnection pooled = (JmsPoolConnection) cf.createConnection(); MockJMSConnection wrapped = (MockJMSConnection) pooled.getConnection(); connections.put(wrapped.getConnectionId(), pooled); } catch (JMSException e) { } } }); } executor.shutdown(); assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS)); assertEquals("Should have all unique connections", numConnections, connections.size()); connections.clear(); cf.stop(); }
Example 7
Source File: PooledConnectionFactoryTest.java From pooled-jms with Apache License 2.0 | 5 votes |
@Test(timeout = 60000) public void testConcurrentCreateGetsUniqueConnection() throws Exception { final JmsPoolConnectionFactory cf = createPooledConnectionFactory(); try { final int numConnections = 2; cf.setMaxConnections(numConnections); cf.start(); final ConcurrentMap<ConnectionId, Connection> connections = new ConcurrentHashMap<ConnectionId, Connection>(); final ExecutorService executor = Executors.newFixedThreadPool(numConnections); for (int i = 0; i < numConnections; ++i) { executor.execute(new Runnable() { @Override public void run() { try { JmsPoolConnection pooled = (JmsPoolConnection) cf.createConnection(); ActiveMQConnection amq = (ActiveMQConnection) pooled.getConnection(); connections.put(amq.getConnectionInfo().getConnectionId(), pooled); } catch (JMSException e) { } } }); } executor.shutdown(); assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS)); assertEquals("Should have all unique connections", numConnections, connections.size()); connections.clear(); } finally { cf.stop(); } }
Example 8
Source File: AbstractAuthorizationGrant.java From oxAuth with MIT License | 5 votes |
private static <T extends AbstractToken> void put(ConcurrentMap<String, T> p_map, List<T> p_list) { p_map.clear(); if (p_list != null && !p_list.isEmpty()) { for (T t : p_list) { p_map.put(t.getCode(), t); } } }
Example 9
Source File: MapCache.java From component-runtime with Apache License 2.0 | 5 votes |
public <A, B> void evictIfNeeded(final ConcurrentMap<A, B> cache, final int maxSize) { if (maxSize < 0) { cache.clear(); return; } while (cache.size() > maxSize) { final Iterator<Map.Entry<A, B>> iterator = cache.entrySet().iterator(); if (iterator.hasNext()) { iterator.remove(); } } }
Example 10
Source File: XmlTransformer.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Release Transformer instance in cache. Previously (before 6.0.0) the cache stored transformers, now it stores templates. * * @param templates * The XML templates * @param strStyleSheetId * The StyleSheet Id */ private void releaseTemplates( Templates templates, String strStyleSheetId ) { if ( TRANSFORMER_POOL_SIZE > 0 ) { Templates result = null; ConcurrentMap<String, Templates> transformerList = null; int nTransformerListIndex = 0; do { transformerList = transformersPoolList.get( nTransformerListIndex ); nTransformerListIndex++; // This set of action is not performed atomically but it can not cause problems if ( transformerList.size( ) < MAX_TRANSFORMER_SIZE ) { result = transformerList.putIfAbsent( strStyleSheetId, templates ); } else { // Aggressive release ( speed up GC ) transformerList.clear( ); AppLogService.info( "XmlTransformer : cache is full, you may need to increase cache size." ); } } while ( ( result != null ) && ( nTransformerListIndex < TRANSFORMER_POOL_SIZE ) ); } }
Example 11
Source File: XmlTransformer.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Remove all Templates instance from cache. Previously (before 6.0.0) the cache stored transformers, now it stores templates. */ public static void cleanTransformerList( ) { for ( ConcurrentMap<String, Templates> transformerList : transformersPoolList ) { transformerList.clear( ); } }
Example 12
Source File: BaseContext.java From incubator-batchee with Apache License 2.0 | 5 votes |
public void endContext(Long key) { final ConcurrentMap<Contextual<?>, Instance<?>> storage = storages.remove(key); if (storage == null) { return; } for (final Map.Entry<Contextual<?>, Instance<?>> entry : storage.entrySet()) { final Instance<?> instance = entry.getValue(); Contextual.class.cast(entry.getKey()).destroy(instance.value, instance.cc); } storage.clear(); }
Example 13
Source File: AbstractConfigRule.java From light with Apache License 2.0 | 5 votes |
public boolean delConfig(Object ...objects) throws Exception { Map<String, Object> inputMap = (Map<String, Object>) objects[0]; Map<String, Object> data = (Map<String, Object>) inputMap.get("data"); String rid = (String) data.get("@rid"); String host = (String) data.get("host"); String configId = null; String error = null; Map<String, Object> user = (Map<String, Object>) inputMap.get("user"); OrientGraph graph = ServiceLocator.getInstance().getGraph(); try { Vertex config = DbService.getVertexByRid(graph, rid); if(config != null) { Map eventMap = getEventMap(inputMap); Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data"); inputMap.put("eventMap", eventMap); configId = config.getProperty("configId"); eventData.put("configId", configId); } else { error = "@rid " + rid + " doesn't exist on host " + host; inputMap.put("responseCode", 404); } } catch (Exception e) { logger.error("Exception:", e); throw e; } finally { graph.shutdown(); } if(error != null) { inputMap.put("result", error); return false; } else { Map<String, Object> configMap = ServiceLocator.getInstance().getMemoryImage("configMap"); ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)configMap.get("cache"); if(cache != null) { cache.clear(); } return true; } }
Example 14
Source File: AbstractConfigRule.java From light with Apache License 2.0 | 4 votes |
public boolean delHostConfig(Object ...objects) throws Exception { Map<String, Object> inputMap = (Map<String, Object>) objects[0]; Map<String, Object> data = (Map<String, Object>) inputMap.get("data"); String rid = (String) data.get("@rid"); String host = (String) data.get("host"); String configId = null; String error = null; Map<String, Object> user = (Map<String, Object>) inputMap.get("user"); OrientGraph graph = ServiceLocator.getInstance().getGraph(); try { String userHost = (String)user.get("host"); if(userHost != null && !userHost.equals(host)) { error = "You can only delete config from host: " + host; inputMap.put("responseCode", 401); } else { Vertex config = DbService.getVertexByRid(graph, rid); if(config != null) { Map eventMap = getEventMap(inputMap); Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data"); inputMap.put("eventMap", eventMap); eventData.put("host", host); configId = config.getProperty("configId"); eventData.put("configId", configId); } else { error = "@rid " + rid + " doesn't exist on host " + host; inputMap.put("responseCode", 404); } } } catch (Exception e) { logger.error("Exception:", e); throw e; } finally { graph.shutdown(); } if(error != null) { inputMap.put("result", error); return false; } else { // update the branch tree as one of branch has changed. Map<String, Object> configMap = ServiceLocator.getInstance().getMemoryImage("configMap"); ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)configMap.get("cache"); if(cache != null) { cache.clear(); } return true; } }
Example 15
Source File: LocalLoadingCacheTest.java From caffeine with Apache License 2.0 | 4 votes |
public void testStatsNoops() { Caffeine<Object, Object> builder = createCacheBuilder(); LoadingCache<Object, Object> cache = makeCache(builder, identityLoader()); ConcurrentMap<Object, Object> map = cache.asMap(); // modifiable map view assertEquals(EMPTY_STATS, cache.stats()); Object one = new Object(); assertNull(map.put(one, one)); assertSame(one, map.get(one)); assertTrue(map.containsKey(one)); assertTrue(map.containsValue(one)); Object two = new Object(); assertSame(one, map.replace(one, two)); assertTrue(map.containsKey(one)); assertFalse(map.containsValue(one)); Object three = new Object(); assertTrue(map.replace(one, two, three)); assertTrue(map.remove(one, three)); assertFalse(map.containsKey(one)); assertFalse(map.containsValue(one)); assertNull(map.putIfAbsent(two, three)); assertSame(three, map.remove(two)); assertNull(map.put(three, one)); assertNull(map.put(one, two)); assertThat(map).containsEntry(three, one); assertThat(map).containsEntry(one, two); //TODO(user): Confirm with fry@ that this is a reasonable substitute. //Set<Map.Entry<Object, Object>> entries = map.entrySet(); //assertThat(entries).containsExactly( // Maps.immutableEntry(three, one), Maps.immutableEntry(one, two)); //Set<Object> keys = map.keySet(); //assertThat(keys).containsExactly(one, three); //Collection<Object> values = map.values(); //assertThat(values).containsExactly(one, two); map.clear(); assertEquals(EMPTY_STATS, cache.stats()); }
Example 16
Source File: ConcurrentHashMapTest.java From caffeine with Apache License 2.0 | 4 votes |
/** * clear removes all pairs */ public void testClear() { ConcurrentMap map = map5(); map.clear(); assertEquals(0, map.size()); }
Example 17
Source File: AbstractConfigRule.java From light with Apache License 2.0 | 4 votes |
public boolean updHostConfig (Object ...objects) throws Exception { Map<String, Object> inputMap = (Map<String, Object>) objects[0]; Map<String, Object> data = (Map<String, Object>) inputMap.get("data"); String rid = (String) data.get("@rid"); String host = (String) data.get("host"); String configId = null; Map<String, Object> user = (Map<String, Object>) inputMap.get("user"); OrientGraph graph = ServiceLocator.getInstance().getGraph(); try { String userHost = (String)user.get("host"); if(userHost != null && !userHost.equals(host)) { inputMap.put("result", "You can only update config from host: " + host); inputMap.put("responseCode", 401); return false; } else { Vertex config = DbService.getVertexByRid(graph, rid); if(config != null) { Map eventMap = getEventMap(inputMap); Map<String, Object> eventData = (Map<String, Object>)eventMap.get("data"); inputMap.put("eventMap", eventMap); eventData.putAll((Map<String, Object>)inputMap.get("data")); eventData.put("updateDate", new java.util.Date()); eventData.put("updateUserId", user.get("userId")); configId = config.getProperty("configId"); String properties = (String)data.get("properties"); if(properties != null) { Map<String, Object> map = mapper.readValue(properties, new TypeReference<HashMap<String, Object>>() { }); eventData.put("properties", map); } } else { inputMap.put("result", "@rid " + rid + " cannot be found"); inputMap.put("responseCode", 404); return false; } } } catch (Exception e) { logger.error("Exception:", e); throw e; } finally { graph.shutdown(); } Map<String, Object> configMap = ServiceLocator.getInstance().getMemoryImage("configMap"); ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>)configMap.get("cache"); if(cache != null) { cache.clear(); } return true; }
Example 18
Source File: Defaults.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * Simulates races by modifying the map within the remapping function. */ @Test public void testConcurrentMap_compute_racy() { final AtomicBoolean b = new AtomicBoolean(true); final ConcurrentMap<Long,Long> map = new ImplementsConcurrentMap<>(); final Long two = 2L; BiFunction<Long,Long,Long> f, g; // null -> null is a no-op; race not detected f = (k, v) -> { map.put(two, 42L); return null; }; assertNull(map.compute(two, f)); assertEquals(42L, (long)map.get(two)); for (Long val : new Long[] { null, 86L }) { map.clear(); f = (k, v) -> { map.put(two, 42L); return 86L; }; g = (k, v) -> { assertSame(two, k); assertEquals(42L, (long)v); return k + v; }; assertEquals(44L, (long)map.compute(two, twoStep(b, f, g))); assertEquals(44L, (long)map.get(two)); assertTrue(b.get()); f = (k, v) -> { map.remove(two); return val; }; g = (k, v) -> { assertSame(two, k); assertNull(v); return 44L; }; assertEquals(44L, (long)map.compute(two, twoStep(b, f, g))); assertEquals(44L, (long)map.get(two)); assertTrue(map.containsKey(two)); assertTrue(b.get()); f = (k, v) -> { map.remove(two); return val; }; g = (k, v) -> { assertSame(two, k); assertNull(v); return null; }; assertNull(map.compute(two, twoStep(b, f, g))); assertNull(map.get(two)); assertFalse(map.containsKey(two)); assertTrue(b.get()); } }
Example 19
Source File: ContextTracker.java From TNT4J with Apache License 2.0 | 4 votes |
/** * Clear all context keys and values associated with current context * */ public static void clearContext() { ConcurrentMap<String, String> map = CONTEXT.get(); map.clear(); }
Example 20
Source File: TreeCache.java From xian with Apache License 2.0 | 4 votes |
void wasDeleted() throws Exception { ChildData oldChildData = childDataUpdater.getAndSet(this, null); client.clearWatcherReferences(this); ConcurrentMap<String, TreeNode> childMap = childrenUpdater.getAndSet(this,null); if ( childMap != null ) { ArrayList<TreeNode> childCopy = new ArrayList<TreeNode>(childMap.values()); childMap.clear(); for ( TreeNode child : childCopy ) { child.wasDeleted(); } } if ( treeState.get() == TreeState.CLOSED ) { return; } NodeState oldState = nodeStateUpdater.getAndSet(this, NodeState.DEAD); if ( oldState == NodeState.LIVE ) { publishEvent(TreeCacheEvent.Type.NODE_REMOVED, oldChildData); } if ( parent == null ) { // Root node; use an exist query to watch for existence. client.checkExists().usingWatcher(this).inBackground(this).forPath(path); } else { // Remove from parent if we're currently a child ConcurrentMap<String, TreeNode> parentChildMap = parent.children; if ( parentChildMap != null ) { parentChildMap.remove(ZKPaths.getNodeFromPath(path), this); } } }