Java Code Examples for java.util.concurrent.ConcurrentMap#isEmpty()

The following examples show how to use java.util.concurrent.ConcurrentMap#isEmpty() . 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: FileBasedLockStrategy.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
/**
 * Determine the state of the lockfile.
 *
 * Must be called from within a synchronized block.
 *
 * Three possibilities exist: - The lock is held by the current thread (>0) - The lock is held
 * by one or more different threads (-1) - The lock is not held at all (0).
 *
 * @param file
 *            file to lock
 * @param forThread
 *            thread for which lock status is being queried
 */
private int hasLock(File file, Thread forThread) {
    ConcurrentMap<Thread, Integer> locksPerThread = currentLockHolders.get(file);
    if (locksPerThread == null) {
        return 0;
    }
    if (locksPerThread.isEmpty()) {
        return 0;
    }
    Integer counterObj = locksPerThread.get(forThread);
    int counter = (counterObj == null) ? 0 : counterObj;
    if (counter > 0) {
        return counter;
    } else {
        return -1;
    }
}
 
Example 2
Source File: CLIServerMain.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * Create a record map of classes implementing IMonitoringRecord interface out
 * of libraries with such classes and a textual mapping file.
 *
 * @return A record map. null is never returned as a call of usage terminates
 *         the program.
 * @throws IOException
 *             if an error occured reading the mapping file
 * @throws CLIConfigurationErrorException
 *             if a configuration error occured
 */
private ConcurrentMap<Integer, Class<? extends IMonitoringRecord>> createRecordMap()
		throws IOException, CLIConfigurationErrorException {
	if (this.libraries.length > 0) {
		if (this.mappingFile != null) {
			final ConcurrentMap<Integer, Class<? extends IMonitoringRecord>> recordMap = this.readMapping();
			if (recordMap.isEmpty()) {
				throw new CLIConfigurationErrorException(
						"At least one mapping must be specified in the mapping file.");
			}
			return recordMap;
		} else {
			throw new CLIConfigurationErrorException("Mapping file is required.");
		}
	} else {
		throw new CLIConfigurationErrorException("At least one library reference is required.");
	}
}
 
Example 3
Source File: ExtensionLoader.java    From neural with MIT License 6 votes vote down vote up
private synchronized void loadExtensionClasses() {
    if (init) {
        return;
    }
    if (extensionClasses == null) {
        extensionClasses = new ConcurrentHashMap<>();
    }

    for (String prefix : DIR_PREFIX_LIST) {
        ConcurrentMap<String, Class<T>> tempExtensionClasses = this.loadExtensionClasses(prefix);
        if (!tempExtensionClasses.isEmpty()) {
            extensionClasses.putAll(tempExtensionClasses);
        }
    }

    singletonInstances = new ConcurrentHashMap<>();
    init = true;
}
 
Example 4
Source File: CachedImpl.java    From roncoo-adminlte-springmvc with Apache License 2.0 6 votes vote down vote up
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 5
Source File: HttpHandler.java    From smartacus-mqtt-broker with Apache License 2.0 5 votes vote down vote up
private void getTopics(ChannelHandlerContext ctx, FullHttpRequest req) {
    ArrayList<TopicVO> vos = new ArrayList<>();
    ConcurrentMap<String, List<ClientSub>> topicSubers = PostMan.topicSubers;
    if(null !=topicSubers && !topicSubers.isEmpty()){
        topicSubers.forEach((k,v)->{
            TopicVO  vo=new TopicVO();
            vo.setTopic(k);
            List<SubClient>  scList= Lists.newArrayList();
            if(!v.isEmpty()){
                v.forEach(e->{
                    SubClient client=new SubClient();
                    client.setClientId(e.getClientId());
                    client.setQos(e.getSubQos());
                    scList.add(client);
                });
            }
            vo.setClientList(scList);
            vos.add(vo);
        });
    }
    // 1.设置响应
    Result result= new Result<Object>().ok(vos);
    FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK,
            Unpooled.copiedBuffer(JSONObject.toJSONString(result), CharsetUtil.UTF_8));
    resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
    // 2.发送
    // 注意必须在使用完之后,close channel
    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}
 
Example 6
Source File: ConsumerManager.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public void scanNotActiveChannel() {
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> next = it.next();
        String group = next.getKey();
        ConsumerGroupInfo consumerGroupInfo = next.getValue();
        ConcurrentMap<Channel, ClientChannelInfo> channelInfoTable =
            consumerGroupInfo.getChannelInfoTable();

        Iterator<Entry<Channel, ClientChannelInfo>> itChannel = channelInfoTable.entrySet().iterator();
        while (itChannel.hasNext()) {
            Entry<Channel, ClientChannelInfo> nextChannel = itChannel.next();
            ClientChannelInfo clientChannelInfo = nextChannel.getValue();
            long diff = System.currentTimeMillis() - clientChannelInfo.getLastUpdateTimestamp();
            if (diff > getChannelExpiredTimeout()) {
                log.warn(
                    "SCAN: remove expired channel from ConsumerManager consumerTable. channel={}, consumerGroup={}",
                    RemotingHelper.parseChannelRemoteAddr(clientChannelInfo.getChannel()), group);
                RemotingUtil.closeChannel(clientChannelInfo.getChannel());
                itChannel.remove();
            }
        }

        if (channelInfoTable.isEmpty()) {
            log.warn(
                "SCAN: remove expired channel from ConsumerManager consumerTable, all clear, consumerGroup={}",
                group);
            it.remove();
        }
    }
}
 
Example 7
Source File: ConsumerOffsetManager.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
private boolean offsetBehindMuchThanData(final String topic, ConcurrentMap<Integer, Long> table) {
    Iterator<Entry<Integer, Long>> it = table.entrySet().iterator();
    boolean result = !table.isEmpty();

    while (it.hasNext() && result) {
        Entry<Integer, Long> next = it.next();
        long minOffsetInStore = this.brokerController.getMessageStore().getMinOffsetInQueue(topic, next.getKey());
        long offsetInPersist = next.getValue();
        result = offsetInPersist <= minOffsetInStore;
    }

    return result;
}
 
Example 8
Source File: ConsumerOffsetManager.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
private boolean offsetBehindMuchThanData(final String topic, ConcurrentMap<Integer, Long> table) {
    Iterator<Entry<Integer, Long>> it = table.entrySet().iterator();
    boolean result = !table.isEmpty();

    while (it.hasNext() && result) {
        Entry<Integer, Long> next = it.next();
        long minOffsetInStore = this.brokerController.getMessageStore().getMinOffsetInQueue(topic, next.getKey());
        long offsetInPersist = next.getValue();
        result = offsetInPersist <= minOffsetInStore;
    }

    return result;
}
 
Example 9
Source File: ConsumerSequenceManager.java    From qmq with Apache License 2.0 5 votes vote down vote up
void remove(String subject, String group, String consumerId) {
    final ConcurrentMap<ConsumerGroup, ConsumerSequence> consumers = sequences.get(consumerId);
    if (consumers == null) return;

    consumers.remove(new ConsumerGroup(subject, group));
    if (consumers.isEmpty()) {
        sequences.remove(consumerId);
    }
}
 
Example 10
Source File: DefaultYangSchemaRegistry.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Removes schema node from schema map.
 *
 * @param removableNode schema node which needs to be removed
 */
private void removeSchemaNode(YangSchemaNode removableNode) {
    String name = removableNode.getName();
    String revName = name;
    String date = getDateInStringFormat(removableNode);
    if (date != null) {
        revName = name + AT + date;
    }
    ConcurrentMap<String, YangSchemaNode> revMap = yangSchemaStore.get(name);
    if (revMap != null && !revMap.isEmpty() && revMap.size() != 1) {
        revMap.remove(revName);
    } else {
        yangSchemaStore.remove(removableNode.getName());
    }
}
 
Example 11
Source File: ConsumerManager.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
public void scanNotActiveChannel() {
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> next = it.next();
        String group = next.getKey();
        ConsumerGroupInfo consumerGroupInfo = next.getValue();
        ConcurrentMap<Channel, ClientChannelInfo> channelInfoTable =
            consumerGroupInfo.getChannelInfoTable();

        Iterator<Entry<Channel, ClientChannelInfo>> itChannel = channelInfoTable.entrySet().iterator();
        while (itChannel.hasNext()) {
            Entry<Channel, ClientChannelInfo> nextChannel = itChannel.next();
            ClientChannelInfo clientChannelInfo = nextChannel.getValue();
            long diff = System.currentTimeMillis() - clientChannelInfo.getLastUpdateTimestamp();
            if (diff > CHANNEL_EXPIRED_TIMEOUT) {
                log.warn(
                    "SCAN: remove expired channel from ConsumerManager consumerTable. channel={}, consumerGroup={}",
                    RemotingHelper.parseChannelRemoteAddr(clientChannelInfo.getChannel()), group);
                RemotingUtil.closeChannel(clientChannelInfo.getChannel());
                itChannel.remove();
            }
        }

        if (channelInfoTable.isEmpty()) {
            log.warn(
                "SCAN: remove expired channel from ConsumerManager consumerTable, all clear, consumerGroup={}",
                group);
            it.remove();
        }
    }
}
 
Example 12
Source File: DeadlockThreadRegistry.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Long> getDeadlockedThreadIdSet() {
    final ConcurrentMap<Long, Object> deadlockedThreadIdMap = this.deadlockedThreadIdMap;
    if (deadlockedThreadIdMap.isEmpty()) {
        return Collections.emptySet();
    }

    return new HashSet<Long>(deadlockedThreadIdMap.keySet());
}
 
Example 13
Source File: AbstractZookeeperClient.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public synchronized void removeChildListener(String path, ChildListener listener) {
	ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
	if (listeners != null) {
		TargetChildListener targetListener = listeners.remove(listener);
		if (targetListener != null) {
			removeTargetChildListener(path, targetListener);
		}
		if (listeners.isEmpty()) {
			childListeners.remove(path);
		}
	}
}
 
Example 14
Source File: ConsumerManager.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public void scanNotActiveChannel() {
    Iterator<Entry<String, ConsumerGroupInfo>> it = this.consumerTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConsumerGroupInfo> next = it.next();
        String group = next.getKey();
        ConsumerGroupInfo consumerGroupInfo = next.getValue();
        ConcurrentMap<Channel, ClientChannelInfo> channelInfoTable =
            consumerGroupInfo.getChannelInfoTable();

        Iterator<Entry<Channel, ClientChannelInfo>> itChannel = channelInfoTable.entrySet().iterator();
        while (itChannel.hasNext()) {
            Entry<Channel, ClientChannelInfo> nextChannel = itChannel.next();
            ClientChannelInfo clientChannelInfo = nextChannel.getValue();
            long diff = System.currentTimeMillis() - clientChannelInfo.getLastUpdateTimestamp();
            if (diff > CHANNEL_EXPIRED_TIMEOUT) {
                log.warn(
                    "SCAN: remove expired channel from ConsumerManager consumerTable. channel={}, consumerGroup={}",
                    RemotingHelper.parseChannelRemoteAddr(clientChannelInfo.getChannel()), group);
                RemotingUtil.closeChannel(clientChannelInfo.getChannel());
                itChannel.remove();
            }
        }

        if (channelInfoTable.isEmpty()) {
            log.warn(
                "SCAN: remove expired channel from ConsumerManager consumerTable, all clear, consumerGroup={}",
                group);
            it.remove();
        }
    }
}
 
Example 15
Source File: ConsumerOffsetManager.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
private boolean offsetBehindMuchThanData(final String topic, ConcurrentMap<Integer, Long> table) {
    Iterator<Entry<Integer, Long>> it = table.entrySet().iterator();
    boolean result = !table.isEmpty();

    while (it.hasNext() && result) {
        Entry<Integer, Long> next = it.next();
        long minOffsetInStore = this.brokerController.getMessageStore().getMinOffsetInQueue(topic, next.getKey());
        long offsetInPersist = next.getValue();
        result = offsetInPersist <= minOffsetInStore;
    }

    return result;
}
 
Example 16
Source File: GridDhtTxAbstractEnlistFuture.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @return {@code True} if in-flight batches map is empty.
 */
private boolean noPendingRequests() {
    if (F.isEmpty(pending))
        return true;

    for (ConcurrentMap<Integer, Batch> e : pending.values()) {
        if (!e.isEmpty())
            return false;
    }

    return true;
}
 
Example 17
Source File: DefaultMessageStore.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 4 votes vote down vote up
public void cleanExpiredConsumerQueue() {
    // CommitLog的最小Offset
    long minCommitLogOffset = this.commitLog.getMinOffset();

    Iterator<Entry<String, ConcurrentMap<Integer, ConsumeQueue>>> it = this.consumeQueueTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConcurrentMap<Integer, ConsumeQueue>> next = it.next();
        String topic = next.getKey();
        if (!topic.equals(ScheduleMessageService.SCHEDULE_TOPIC)) {
            ConcurrentMap<Integer, ConsumeQueue> queueTable = next.getValue();
            Iterator<Entry<Integer, ConsumeQueue>> itQT = queueTable.entrySet().iterator();
            while (itQT.hasNext()) {
                Entry<Integer, ConsumeQueue> nextQT = itQT.next();
                long maxCLOffsetInConsumeQueue = nextQT.getValue().getLastOffset();

                // maxCLOffsetInConsumeQueue==-1有可能正好是索引文件刚好创建的那一时刻,此时不清除数据
                if (maxCLOffsetInConsumeQueue == -1) {
                    log.warn("maybe ConsumeQueue was created just now. topic={} queueId={} maxPhysicOffset={} minLogicOffset={}.", //
                        nextQT.getValue().getTopic(), //
                        nextQT.getValue().getQueueId(), //
                        nextQT.getValue().getMaxPhysicOffset(), //
                        nextQT.getValue().getMinLogicOffset());
                } else if (maxCLOffsetInConsumeQueue < minCommitLogOffset) {
                    log.info(
                        "cleanExpiredConsumerQueue: {} {} consumer queue destroyed, minCommitLogOffset: {} maxCLOffsetInConsumeQueue: {}", //
                        topic, //
                        nextQT.getKey(), //
                        minCommitLogOffset, //
                        maxCLOffsetInConsumeQueue);

                    DefaultMessageStore.this.commitLog.removeQueueFromTopicQueueTable(nextQT.getValue().getTopic(),
                        nextQT.getValue().getQueueId());

                    nextQT.getValue().destroy();
                    itQT.remove();
                }
            }

            if (queueTable.isEmpty()) {
                log.info("cleanExpiredConsumerQueue: {},topic destroyed", topic);
                it.remove();
            }
        }
    }
}
 
Example 18
Source File: GridIoManager.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Override public void onTimeout() {
    GridMessageListener lsnr = listenerGet0(topic);

    if (lsnr != null) {
        long delta = 0;

        if (skipOnTimeout) {
            while (true) {
                delta = 0;

                boolean unwind = false;

                synchronized (this) {
                    if (!msgs.isEmpty()) {
                        delta = U.currentTimeMillis() - lastTs;

                        if (delta >= timeout)
                            unwind = true;
                    }
                }

                if (unwind)
                    unwindMessageSet(this, lsnr);
                else
                    break;
            }
        }

        // Someone is still listening to messages, so delay set removal.
        endTime = endTime(timeout - delta);

        ctx.timeout().addTimeoutObject(this);

        return;
    }

    if (log.isDebugEnabled())
        log.debug("Removing message set due to timeout: " + this);

    ConcurrentMap<UUID, GridCommunicationMessageSet> map = msgSetMap.get(topic);

    if (map != null) {
        boolean rmv;

        synchronized (map) {
            rmv = map.remove(nodeId, this) && map.isEmpty();
        }

        if (rmv)
            msgSetMap.remove(topic, map);
    }
}
 
Example 19
Source File: KillCommandsTests.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Test cancel of the scan query.
 *
 * @param cli Client node.
 * @param srvs Server nodes.
 * @param qryCanceler Query cancel closure.
 */
public static void doTestScanQueryCancel(IgniteEx cli, List<IgniteEx> srvs, Consumer<T3<UUID, String, Long>> qryCanceler) {
    IgniteCache<Object, Object> cache = cli.cache(DEFAULT_CACHE_NAME);

    QueryCursor<Cache.Entry<Object, Object>> qry1 = cache.query(new ScanQuery<>().setPageSize(PAGE_SZ));
    Iterator<Cache.Entry<Object, Object>> iter1 = qry1.iterator();

    // Fetch first entry and therefore caching first page.
    assertNotNull(iter1.next());

    List<List<?>> scanQries0 = execute(srvs.get(0),
        "SELECT ORIGIN_NODE_ID, CACHE_NAME, QUERY_ID FROM SYS.SCAN_QUERIES");

    assertEquals(1, scanQries0.size());

    UUID originNodeId = (UUID)scanQries0.get(0).get(0);
    String cacheName = (String)scanQries0.get(0).get(1);
    long qryId = (Long)scanQries0.get(0).get(2);

    // Opens second query.
    QueryCursor<Cache.Entry<Object, Object>> qry2 = cache.query(new ScanQuery<>().setPageSize(PAGE_SZ));
    Iterator<Cache.Entry<Object, Object>> iter2 = qry2.iterator();

    // Fetch first entry and therefore caching first page.
    assertNotNull(iter2.next());

    // Cancel first query.
    qryCanceler.accept(new T3<>(originNodeId, cacheName, qryId));

    // Fetch all cached entries. It's size equal to the {@code PAGE_SZ * NODES_CNT}.
    for (int i = 0; i < PAGE_SZ * srvs.size() - 1; i++)
        assertNotNull(iter1.next());

    // Fetch of the next page should throw the exception.
    assertThrowsWithCause(iter1::next, IgniteCheckedException.class);

    // Checking that second query works fine after canceling first.
    for (int i = 0; i < PAGE_SZ * PAGE_SZ - 1; i++)
        assertNotNull(iter2.next());

    // Checking all server node objects cleared after cancel.
    for (int i = 0; i < srvs.size(); i++) {
        IgniteEx ignite = srvs.get(i);

        int cacheId = CU.cacheId(DEFAULT_CACHE_NAME);

        GridCacheContext<?, ?> ctx = ignite.context().cache().context().cacheContext(cacheId);

        ConcurrentMap<UUID, ? extends GridCacheQueryManager<?, ?>.RequestFutureMap> qryIters =
            ctx.queries().queryIterators();

        assertTrue(qryIters.size() <= 1);

        if (qryIters.isEmpty())
            return;

        GridCacheQueryManager<?, ?>.RequestFutureMap futs = qryIters.get(cli.localNode().id());

        assertNotNull(futs);
        assertFalse(futs.containsKey(qryId));
    }
}
 
Example 20
Source File: DefaultMessageStore.java    From rocketmq-4.3.0 with Apache License 2.0 4 votes vote down vote up
public void cleanExpiredConsumerQueue() {
//        从commitLog中获取最小的offset=》
        long minCommitLogOffset = this.commitLog.getMinOffset();

        Iterator<Entry<String, ConcurrentMap<Integer, ConsumeQueue>>> it = this.consumeQueueTable.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, ConcurrentMap<Integer, ConsumeQueue>> next = it.next();
            String topic = next.getKey();
            if (!topic.equals(ScheduleMessageService.SCHEDULE_TOPIC)) {
                ConcurrentMap<Integer, ConsumeQueue> queueTable = next.getValue();
                Iterator<Entry<Integer, ConsumeQueue>> itQT = queueTable.entrySet().iterator();
                while (itQT.hasNext()) {
                    Entry<Integer, ConsumeQueue> nextQT = itQT.next();
//                    获取消息队列的lastOffset=》
                    long maxCLOffsetInConsumeQueue = nextQT.getValue().getLastOffset();

                    if (maxCLOffsetInConsumeQueue == -1) {
                        log.warn("maybe ConsumeQueue was created just now. topic={} queueId={} maxPhysicOffset={} minLogicOffset={}.",
                            nextQT.getValue().getTopic(),
                            nextQT.getValue().getQueueId(),
                            nextQT.getValue().getMaxPhysicOffset(),
                            nextQT.getValue().getMinLogicOffset());
//                        正常情况下应该等于,如果是小于说明有的消息队列已过期
                    } else if (maxCLOffsetInConsumeQueue < minCommitLogOffset) {
                        log.info(
                            "cleanExpiredConsumerQueue: {} {} consumer queue destroyed, minCommitLogOffset: {} maxCLOffsetInConsumeQueue: {}",
                            topic,
                            nextQT.getKey(),
                            minCommitLogOffset,
                            maxCLOffsetInConsumeQueue);

//                        按topic和queueId删除topic和queue的offset=》
                        DefaultMessageStore.this.commitLog.removeQueueFromTopicQueueTable(nextQT.getValue().getTopic(),
                            nextQT.getValue().getQueueId());

                        nextQT.getValue().destroy();
//                      消息队列销毁了,消息队列所在元素删除
                        itQT.remove();
                    }
                }

                if (queueTable.isEmpty()) {
                    log.info("cleanExpiredConsumerQueue: {},topic destroyed", topic);
//                  topic销毁了,消息队列所在的元素删除
                    it.remove();
                }
            }
        }
    }