Java Code Examples for java.util.concurrent.ConcurrentHashMap.get()

The following are Jave code examples for showing how to use get() of the java.util.concurrent.ConcurrentHashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: tomcat7   File: SlowQueryReport.java   View Source Code Vote up 8 votes
protected QueryStats getQueryStats(String sql) {
    if (sql==null) sql = "";
    ConcurrentHashMap<String,QueryStats> queries = SlowQueryReport.this.queries;
    if (queries==null) {
        if (log.isWarnEnabled()) log.warn("Connection has already been closed or abandoned");
        return null;
    }
    QueryStats qs = queries.get(sql);
    if (qs == null) {
        qs = new QueryStats(sql);
        if (queries.putIfAbsent(sql,qs)!=null) {
            qs = queries.get(sql);
        } else {
            //we added a new element, see if we need to remove the oldest
            if (queries.size() > maxQueries) {
                removeOldest(queries);
            }
        }
    }
    return qs;
}
 
Example 2
Project: improved-journey   File: FileTailer.java   View Source Code Vote up 7 votes
public FileTailer(IFileTailerListener listener, ConcurrentHashMap<String, String> prop) {
	this.listener = listener;
	this.prop = prop;
	/**
	 * 对n个source实例,配置n个快照文件
	 */
	this.snapShotMarkDirPath = prop.get("backupFileDirPath");
	this.snapShotMarkPath = prop.get("backupFileDirPath")+File.separator+"mark.txt";
	this.backupDB = new MD5File(snapShotMarkDirPath);
	this.clearTimeInterval = Long.parseLong(prop.get("clearTimeInterval"));
	pattern = Pattern.compile(prop.get("regexFileName"));//必须能匹配上实时文件,也能匹配由实时文件产生的新文件
	this.tailFile = new File(prop.get("fileRootDir")+File.separator+prop.get("filePrefix")+prop.get("fileSuffix"));
	logger.info("开始执行:initMarkData()");
	try {
		this.initMarkData();
	} catch (IOException e) {
		logger.error("加载本地快照文件失败!",e);
	}
	logger.info("结束执行:initMarkData()");
}
 
Example 3
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: RebalanceLockManager.java   View Source Code Vote up 7 votes
private boolean isLocked(final String group, final MessageQueue mq, final String clientId) {
    ConcurrentHashMap<MessageQueue, LockEntry> groupValue = this.mqLockTable.get(group);
    if (groupValue != null) {
        LockEntry lockEntry = groupValue.get(mq);
        if (lockEntry != null) {
            boolean locked = lockEntry.isLocked(clientId);
            if (locked) {
                lockEntry.setLastUpdateTimestamp(System.currentTimeMillis());
            }

            return locked;
        }
    }

    return false;
}
 
Example 4
Project: rmq4note   File: RebalanceLockManager.java   View Source Code Vote up 7 votes
/**
 * LockEntry 为consumer端 clientId 的实体,该方法用来判断group下的mq是否被
 * 指定的clientId锁着,并且获取锁不过时
 * @param group
 * @param mq
 * @param clientId
 * @return
 */
private boolean isLocked(final String group, final MessageQueue mq, final String clientId) {
    ConcurrentHashMap<MessageQueue, LockEntry> groupValue = this.mqLockTable.get(group);
    if (groupValue != null) {
        LockEntry lockEntry = groupValue.get(mq);
        if (lockEntry != null) {
            boolean locked = lockEntry.isLocked(clientId);
            if (locked) {
                lockEntry.setLastUpdateTimestamp(System.currentTimeMillis());
            }

            return locked;
        }
    }

    return false;
}
 
Example 5
Project: openjdk-jdk10   File: SunFontManager.java   View Source Code Vote up 6 votes
protected static void registerCompositeFont(String compositeName,
                                            String[] componentFileNames,
                                            String[] componentNames,
                                            int numMetricsSlots,
                                            int[] exclusionRanges,
                                            int[] exclusionMaxIndex,
                                            boolean defer,
                                            ConcurrentHashMap<String, Font2D>
                                            altNameCache) {

    CompositeFont cf = new CompositeFont(compositeName,
                                         componentFileNames,
                                         componentNames,
                                         numMetricsSlots,
                                         exclusionRanges,
                                         exclusionMaxIndex, defer,
                                         SunFontManager.getInstance());

    /* if the cache has an existing composite for this case, make
     * its handle point to this new font.
     * This ensures that when the altNameCache that is passed in
     * is the global mapNameCache - ie we are running as an application -
     * that any statically created java.awt.Font instances which already
     * have a Font2D instance will have that re-directed to the new Font
     * on subsequent uses. This is particularly important for "the"
     * default font instance, or similar cases where a UI toolkit (eg
     * Swing) has cached a java.awt.Font. Note that if Swing is using
     * a custom composite APIs which update the standard composites have
     * no effect - this is typically the case only when using the Windows
     * L&F where these APIs would conflict with that L&F anyway.
     */
    Font2D oldFont =altNameCache.get(compositeName.toLowerCase(Locale.ENGLISH));
    if (oldFont instanceof CompositeFont) {
        oldFont.handle.font2D = cf;
    }
    altNameCache.put(compositeName.toLowerCase(Locale.ENGLISH), cf);
}
 
Example 6
Project: weex-uikit   File: WXSliderNeighbor.java   View Source Code Vote up 6 votes
/**
 * we do it in a hack way.
 * travel the dom tree, to get how many children does this slider-neighbor have.
 *
 * @return
 */
private int getNeighborChildrenCount() {

    try {
        WXDomManager domManager = WXSDKManager.getInstance().getWXDomManager();
        Field domRegistriesField = domManager.getClass().getDeclaredField("mDomRegistries");
        domRegistriesField.setAccessible(true);
        ConcurrentHashMap<String, Object> domRegistriesMap = (ConcurrentHashMap<String, Object>) domRegistriesField.get(domManager);
        Object domStatement = domRegistriesMap.get(getInstanceId()); // WXDomStatement
        Field mRegistryField = domStatement.getClass().getDeclaredField("mRegistry");
        mRegistryField.setAccessible(true);
        ConcurrentHashMap<String, WXDomObject> mRegistryMap = (ConcurrentHashMap<String, WXDomObject>) mRegistryField.get(domStatement);
        for(WXDomObject domObject : mRegistryMap.values()) {
            if(domObject.getType().equalsIgnoreCase(WXBasicComponentType.SLIDER_NEIGHBOR)) {
                int sum = 0;
                for (int i = 0,count = domObject.getChildCount(); i < count; i++) {
                    if(domObject.getChild(i) instanceof WXIndicator.IndicatorDomNode) {
                        continue;
                    }
                    sum++;
                }
                return sum;
            }
        }
    } catch (Exception e) {
        // ignore
    }

    return -1;

}
 
Example 7
Project: NYBus   File: NYBusDriver.java   View Source Code Vote up 6 votes
/**
 * Update methods in set.
 *
 * @param targetObject    the target object.
 * @param subscribeMethod the subscribe method.
 * @param mTargetMap      the target map.
 */
private void updateMethodInSet(Object targetObject,
                               SubscriberHolder subscribeMethod,
                               ConcurrentHashMap<Object, ConcurrentHashMap<String,
                                       SubscriberHolder>> mTargetMap) {
    ConcurrentHashMap<String, SubscriberHolder> methodSet = mTargetMap.get(targetObject);
    methodSet.put(subscribeMethod.getKeyForSubscribeHolderMap(), subscribeMethod);
}
 
Example 8
Project: OpenJSharp   File: SunFontManager.java   View Source Code Vote up 6 votes
protected static void registerCompositeFont(String compositeName,
                                            String[] componentFileNames,
                                            String[] componentNames,
                                            int numMetricsSlots,
                                            int[] exclusionRanges,
                                            int[] exclusionMaxIndex,
                                            boolean defer,
                                            ConcurrentHashMap<String, Font2D>
                                            altNameCache) {

    CompositeFont cf = new CompositeFont(compositeName,
                                         componentFileNames,
                                         componentNames,
                                         numMetricsSlots,
                                         exclusionRanges,
                                         exclusionMaxIndex, defer,
                                         SunFontManager.getInstance());

    /* if the cache has an existing composite for this case, make
     * its handle point to this new font.
     * This ensures that when the altNameCache that is passed in
     * is the global mapNameCache - ie we are running as an application -
     * that any statically created java.awt.Font instances which already
     * have a Font2D instance will have that re-directed to the new Font
     * on subsequent uses. This is particularly important for "the"
     * default font instance, or similar cases where a UI toolkit (eg
     * Swing) has cached a java.awt.Font. Note that if Swing is using
     * a custom composite APIs which update the standard composites have
     * no effect - this is typically the case only when using the Windows
     * L&F where these APIs would conflict with that L&F anyway.
     */
    Font2D oldFont = (Font2D)
        altNameCache.get(compositeName.toLowerCase(Locale.ENGLISH));
    if (oldFont instanceof CompositeFont) {
        oldFont.handle.font2D = cf;
    }
    altNameCache.put(compositeName.toLowerCase(Locale.ENGLISH), cf);
}
 
Example 9
Project: rmq4note   File: ConsumerOffsetManager.java   View Source Code Vote up 6 votes
public long queryOffset(final String group, final String topic, final int queueId) {
    // [email protected]
    String key = topic + TOPIC_GROUP_SEPARATOR + group;
    ConcurrentHashMap<Integer, Long> map = this.offsetTable.get(key);
    if (null != map) {
        Long offset = map.get(queueId);
        if (offset != null)
            return offset;
    }

    return -1;
}
 
Example 10
Project: mango   File: ZookeeperRegistry.java   View Source Code Vote up 6 votes
@Override
protected void doSubscribe(final URL url, final NotifyListener listener) {
    try {
        clientLock.lock();

        ConcurrentHashMap<NotifyListener, IZkChildListener> childChangeListeners = serviceListeners.get(url);
        if (childChangeListeners == null) {
            serviceListeners.putIfAbsent(url, new ConcurrentHashMap<NotifyListener, IZkChildListener>());
            childChangeListeners = serviceListeners.get(url);
        }
        IZkChildListener zkChildListener = childChangeListeners.get(listener);
        if (zkChildListener == null) {
            childChangeListeners.putIfAbsent(listener, new IZkChildListener() {
                @Override
                public void handleChildChange(String parentPath, List<String> currentChilds) {

                    listener.notify(getUrl(), childrenNodeToUrls(parentPath, currentChilds));
                    logger.info(String.format("[ZookeeperRegistry] service list change: path=%s, currentChilds=%s", parentPath, currentChilds.toString()));
                }
            });
            zkChildListener = childChangeListeners.get(listener);
        }

        // 防止旧节点未正常注销
        removeNode(url, ZkNodeType.CLIENT);
        createNode(url, ZkNodeType.CLIENT);

        String serverTypePath = ZkUtils.toNodeTypePath(url, ZkNodeType.SERVER);
        zkClient.subscribeChildChanges(serverTypePath, zkChildListener);
        logger.info(String.format("[ZookeeperRegistry] subscribe service: path=%s, info=%s", ZkUtils.toNodePath(url, ZkNodeType.SERVER), url.toFullUri()));
    } catch (Throwable e) {
        throw new RpcFrameworkException(String.format("Failed to subscribe %s to zookeeper(%s), cause: %s", url, getUrl(), e.getMessage()), e);
    } finally {
        clientLock.unlock();
    }
}
 
Example 11
Project: rmq4note   File: RebalanceLockManager.java   View Source Code Vote up 5 votes
public boolean tryLock(final String group, final MessageQueue mq, final String clientId) {

        if (!this.isLocked(group, mq, clientId)) {
            try {
                this.lock.lockInterruptibly();
                try {
                    ConcurrentHashMap<MessageQueue, LockEntry> groupValue = this.mqLockTable.get(group);
                    if (null == groupValue) {
                        groupValue = new ConcurrentHashMap<>(32);
                        this.mqLockTable.put(group, groupValue);
                    }

                    LockEntry lockEntry = groupValue.get(mq);
                    if (null == lockEntry) {
                        lockEntry = new LockEntry();
                        lockEntry.setClientId(clientId);
                        groupValue.put(mq, lockEntry);
                        log.info("tryLock, message queue not locked, I got it. Group: {} NewClientId: {} {}", //
                            group, //
                            clientId, //
                            mq);
                    }

                    if (lockEntry.isLocked(clientId)) {
                        lockEntry.setLastUpdateTimestamp(System.currentTimeMillis());
                        return true;
                    }

                    String oldClientId = lockEntry.getClientId();

                    if (lockEntry.isExpired()) {
                        lockEntry.setClientId(clientId);
                        lockEntry.setLastUpdateTimestamp(System.currentTimeMillis());
                        log.warn(
                            "tryLock, message queue lock expired, I got it. Group: {} OldClientId: {} NewClientId: {} {}", //
                            group, //
                            oldClientId, //
                            clientId, //
                            mq);
                        return true;
                    }

                    log.warn(
                        "tryLock, message queue locked by other client. Group: {} OtherClientId: {} NewClientId: {} {}", //
                        group, //
                        oldClientId, //
                        clientId, //
                        mq);
                    return false;
                } finally {
                    this.lock.unlock();
                }
            } catch (InterruptedException e) {
                log.error("putMessage exception", e);
            }
        } else {

        }

        return true;
    }
 
Example 12
Project: GitHub   File: DoubleKeyValueMap.java   View Source Code Vote up 5 votes
public V get(K1 key1, K2 key2) {
    ConcurrentHashMap<K2, V> k2_v = k1_k2V_map.get(key1);
    return k2_v == null ? null : k2_v.get(key2);
}
 
Example 13
Project: TechnicalAnalysisTool   File: MarketDataTreeViewNode.java   View Source Code Vote up 5 votes
/**
 * Update the tmp Fm by using the keyword
 * @param keyword 
 */
private void updateTmpFm(String keyword) {
    tmpFm.emptyAll();
    ConcurrentHashMap<String, ConcurrentSkipListSet<Market>> data = fm.getFinancialMarketData();
    String marketCode = selectedMarketProperty.getValue().toUpperCase();
    String marketType = selectedMarketTypeProperty.getValue();
    if (marketCode == null || marketCode.isEmpty()) {
        //do nothing
        return;
    }
    else {
        if (data.get(marketType) != null) {
            Market market = fm.getMarket(selectedMarketTypeProperty.getValue(), marketCode);
            
            if (market == null) {
                //do nothing
                return;
            } else {
                Iterator<String> iterator = market.getData().keySet().iterator();
                while (iterator.hasNext()) {
                    String OHLCCode = iterator.next();
                    if (OHLCCode.startsWith(keyword)){
                        if (tmpFm.getMarket(selectedMarketTypeProperty.getValue(), marketCode) == null){
                            Market tmpMarket = new Market(marketCode, market.getChartType(), market.getCountryName());
                            tmpFm.addMarket(selectedMarketTypeProperty.getValue(), tmpMarket);
                        }
                        Iterator<OHLC> ohlcIterator = market.getOHLC(OHLCCode).iterator();
                        while(ohlcIterator.hasNext()) {
                            if (tmpFm.getMarket(marketType, marketCode) != null) {
                                tmpFm.getMarket(marketType, marketCode).addOHLC(OHLCCode, ohlcIterator.next());
                            }else {
                                tmpFm.initMarket(marketType, marketCode, market.getCountryName(), market.getChartType());
                                tmpFm.getMarket(marketType, marketCode).addOHLC(OHLCCode, ohlcIterator.next());
                            }
                        }
                    }
                }
            }
        }
        else {
            //do nothing
            return;
        }
    }
}
 
Example 14
Project: airgram   File: SecretChatHelper.java   View Source Code Vote up 5 votes
protected void processUpdateEncryption(TLRPC.TL_updateEncryption update, ConcurrentHashMap<Integer, TLRPC.User> usersDict) {
    final TLRPC.EncryptedChat newChat = update.chat;
    long dialog_id = ((long) newChat.id) << 32;
    TLRPC.EncryptedChat existingChat = MessagesController.getInstance().getEncryptedChatDB(newChat.id);

    if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) {
        int user_id = newChat.participant_id;
        if (user_id == UserConfig.getClientUserId()) {
            user_id = newChat.admin_id;
        }
        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
        if (user == null) {
            user = usersDict.get(user_id);
        }
        newChat.user_id = user_id;
        final TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
        dialog.id = dialog_id;
        dialog.unread_count = 0;
        dialog.top_message = 0;
        dialog.last_message_date = update.date;

        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                MessagesController.getInstance().dialogs_dict.put(dialog.id, dialog);
                MessagesController.getInstance().dialogs.add(dialog);
                MessagesController.getInstance().putEncryptedChat(newChat, false);
                MessagesController.getInstance().sortDialogs(null);
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
            }
        });
        MessagesStorage.getInstance().putEncryptedChat(newChat, user, dialog);
        SecretChatHelper.getInstance().acceptSecretChat(newChat);
    } else if (newChat instanceof TLRPC.TL_encryptedChat) {
        if (existingChat != null && existingChat instanceof TLRPC.TL_encryptedChatWaiting && (existingChat.auth_key == null || existingChat.auth_key.length == 1)) {
            newChat.a_or_b = existingChat.a_or_b;
            newChat.user_id = existingChat.user_id;
            SecretChatHelper.getInstance().processAcceptedSecretChat(newChat);
        } else if (existingChat == null && startingSecretChat) {
            delayedEncryptedChatUpdates.add(update);
        }
    } else {
        final TLRPC.EncryptedChat exist = existingChat;
        if (exist != null) {
            newChat.user_id = exist.user_id;
            newChat.auth_key = exist.auth_key;
            newChat.key_create_date = exist.key_create_date;
            newChat.key_use_count_in = exist.key_use_count_in;
            newChat.key_use_count_out = exist.key_use_count_out;
            newChat.ttl = exist.ttl;
            newChat.seq_in = exist.seq_in;
            newChat.seq_out = exist.seq_out;
        }
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (exist != null) {
                    MessagesController.getInstance().putEncryptedChat(newChat, false);
                }
                MessagesStorage.getInstance().updateEncryptedChat(newChat);
                NotificationCenter.getInstance().postNotificationName(NotificationCenter.encryptedChatUpdated, newChat);
            }
        });
    }
}
 
Example 15
Project: alfresco-repository   File: ReferenceCountingReadOnlyIndexReaderFactory.java   View Source Code Vote up 5 votes
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 16
Project: OpenJSharp   File: FileFontStrike.java   View Source Code Vote up 5 votes
private Point2D.Float getGlyphMetrics(int glyphCode, boolean getImage) {
    Point2D.Float metrics = new Point2D.Float();

    // !!! or do we force sgv user glyphs?
    if (glyphCode >= INVISIBLE_GLYPHS) {
        return metrics;
    }
    long glyphPtr;
    if (getImageWithAdvance && getImage) {
        /* A heuristic optimisation says that for most cases its
         * worthwhile retrieving the image at the same time as the
         * metrics. So here we get the image data even if its not
         * already cached.
         */
        glyphPtr = getGlyphImagePtr(glyphCode);
    } else {
         glyphPtr = getCachedGlyphPtr(glyphCode);
    }
    if (glyphPtr != 0L) {
        metrics = new Point2D.Float();
        metrics.x = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.xAdvanceOffset);
        metrics.y = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.yAdvanceOffset);
        /* advance is currently in device space, need to convert back
         * into user space.
         * This must not include the translation component. */
        if (invertDevTx != null) {
            invertDevTx.deltaTransform(metrics, metrics);
        }
    } else {
        /* We sometimes cache these metrics as they are expensive to
         * generate for large glyphs.
         * We never reach this path if we obtain images with advances.
         * But if we do not obtain images with advances its possible that
         * we first obtain this information, then the image, and never
         * will access this value again.
         */
        Integer key = Integer.valueOf(glyphCode);
        Point2D.Float value = null;
        ConcurrentHashMap<Integer, Point2D.Float> glyphMetricsMap = null;
        if (glyphMetricsMapRef != null) {
            glyphMetricsMap = glyphMetricsMapRef.get();
        }
        if (glyphMetricsMap != null) {
            value = glyphMetricsMap.get(key);
            if (value != null) {
                metrics.x = value.x;
                metrics.y = value.y;
                /* already in user space */
                return metrics;
            }
        }
        if (value == null) {
            fileFont.getGlyphMetrics(pScalerContext, glyphCode, metrics);
            /* advance is currently in device space, need to convert back
             * into user space.
             */
            if (invertDevTx != null) {
                invertDevTx.deltaTransform(metrics, metrics);
            }
            value = new Point2D.Float(metrics.x, metrics.y);
            /* We aren't synchronizing here so it is possible to
             * overwrite the map with another one but this is harmless.
             */
            if (glyphMetricsMap == null) {
                glyphMetricsMap =
                    new ConcurrentHashMap<Integer, Point2D.Float>();
                glyphMetricsMapRef =
                    new SoftReference<ConcurrentHashMap<Integer,
                    Point2D.Float>>(glyphMetricsMap);
            }
            glyphMetricsMap.put(key, value);
        }
    }
    return metrics;
}
 
Example 17
Project: openjdk-jdk10   File: FileFontStrike.java   View Source Code Vote up 5 votes
private Point2D.Float getGlyphMetrics(int glyphCode, boolean getImage) {
    Point2D.Float metrics = new Point2D.Float();

    // !!! or do we force sgv user glyphs?
    if (glyphCode >= INVISIBLE_GLYPHS) {
        return metrics;
    }
    long glyphPtr;
    if (getImageWithAdvance && getImage) {
        /* A heuristic optimisation says that for most cases its
         * worthwhile retrieving the image at the same time as the
         * metrics. So here we get the image data even if its not
         * already cached.
         */
        glyphPtr = getGlyphImagePtr(glyphCode);
    } else {
         glyphPtr = getCachedGlyphPtr(glyphCode);
    }
    if (glyphPtr != 0L) {
        metrics = new Point2D.Float();
        metrics.x = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.xAdvanceOffset);
        metrics.y = StrikeCache.unsafe.getFloat
            (glyphPtr + StrikeCache.yAdvanceOffset);
        /* advance is currently in device space, need to convert back
         * into user space.
         * This must not include the translation component. */
        if (invertDevTx != null) {
            invertDevTx.deltaTransform(metrics, metrics);
        }
    } else {
        /* We sometimes cache these metrics as they are expensive to
         * generate for large glyphs.
         * We never reach this path if we obtain images with advances.
         * But if we do not obtain images with advances its possible that
         * we first obtain this information, then the image, and never
         * will access this value again.
         */
        Integer key = Integer.valueOf(glyphCode);
        Point2D.Float value = null;
        ConcurrentHashMap<Integer, Point2D.Float> glyphMetricsMap = null;
        if (glyphMetricsMapRef != null) {
            glyphMetricsMap = glyphMetricsMapRef.get();
        }
        if (glyphMetricsMap != null) {
            value = glyphMetricsMap.get(key);
            if (value != null) {
                metrics.x = value.x;
                metrics.y = value.y;
                /* already in user space */
                return metrics;
            }
        }
        if (value == null) {
            fileFont.getGlyphMetrics(pScalerContext, glyphCode, metrics);
            /* advance is currently in device space, need to convert back
             * into user space.
             */
            if (invertDevTx != null) {
                invertDevTx.deltaTransform(metrics, metrics);
            }
            value = new Point2D.Float(metrics.x, metrics.y);
            /* We aren't synchronizing here so it is possible to
             * overwrite the map with another one but this is harmless.
             */
            if (glyphMetricsMap == null) {
                glyphMetricsMap =
                    new ConcurrentHashMap<Integer, Point2D.Float>();
                glyphMetricsMapRef =
                    new SoftReference<ConcurrentHashMap<Integer,
                    Point2D.Float>>(glyphMetricsMap);
            }
            glyphMetricsMap.put(key, value);
        }
    }
    return metrics;
}
 
Example 18
Project: cljbuck   File: Main.java   View Source Code Vote up 5 votes
public void run(final String[] args, final JsonKeyPair mainStart) throws InterruptedException, ExecutionException, IOException {
    final Workspace workspace = new Workspace().findRoot();
    final File targetDir = new File(workspace.getOutputDir());
    targetDir.mkdirs();
    tracer = Tracer.create(workspace.getOutputDir());
    tracer.start();

    tracer.info(mainStart);

    final ArrayList<Callable<Integer>> tasks = new ArrayList<>();
    final SourceCache cache = SourceCache.create(tracer);
    final ReadWriterQueue globCh = new ReadWriterQueue();
    final ReadWriterQueue pathCh = new ReadWriterQueue();
    final ReadWriterQueue cacheCh = new ReadWriterQueue();
    final ReadWriterQueue tokenCh = new ReadWriterQueue();
    final ReadWriterQueue ruleCh = new ReadWriterQueue();

    globCh.write(Glob.create(workspace.getPath(), "**/CLJ"));
    close(globCh);


    tasks.add(new FindFilesTask(tracer, globCh, pathCh, workspace.getPath(), READER_TASKS));
    for (int i = 0; i < READER_TASKS; i++) {
        tasks.add(new ReadFileTask(tracer, pathCh, cacheCh, cache, LEXER_TASKS/READER_TASKS));
    }

    for (int i = 0; i < LEXER_TASKS; i++) {
        tasks.add(new LexerTask(tracer, cacheCh, tokenCh, cache, new BuildFile()));
    }

    tasks.add(new RuleEmitterTask(tracer, tokenCh, ruleCh, workspace, LEXER_TASKS));
    pool = Executors.newFixedThreadPool(tasks.size());

    int rc = 0;
    final List<Future<Integer>> results = pool.invokeAll(tasks);

    for (final Future<Integer> f : results) {
        rc |= f.get();
    }

    if (0 != rc) {
        exit(tracer, rc);
    }

    final ArrayList<Rules> buildRules = new ArrayList<>();

    for (final Object o : ruleCh.toArray()) {
        final Rules rule = (Rules) o;
        if (null != rule) {
            buildRules.add(rule);
        }
    }

    try {
        final ClassPath classPath = new ClassPath();
        final BuildGraph buildGraph = new Rules().graph(tracer, buildRules.toArray(new Rules[0]));

        final ArrayList<String> argList = new ArrayList<>(Arrays.asList(args));
        final ConcurrentHashMap<String, Command> commandList = commandList(tracer, buildGraph, classPath, workspace);

        if (args.length < 1) {
            printUsage(System.out, commandList);
            exit(tracer, RC_USAGE);
        }

        final String arg1 = argList.remove(ARG1);
        final Command cmd = commandList.get(arg1);

        if (null == cmd) {
            printUsage(System.out, commandList);
            exit(tracer, RC_USAGE);
        }

        rc = cmd.exec(argList);

        exit(tracer, rc);
    } catch (Exception e) {
        e.printStackTrace();
        exit(tracer, RC_EXCEPTION);
    }
}
 
Example 19
Project: rmq4note   File: RebalanceLockManager.java   View Source Code Vote up 5 votes
public void unlockBatch(final String group, final Set<MessageQueue> mqs, final String clientId) {
    try {
        this.lock.lockInterruptibly();
        try {
            ConcurrentHashMap<MessageQueue, LockEntry> groupValue = this.mqLockTable.get(group);
            if (null != groupValue) {
                for (MessageQueue mq : mqs) {
                    LockEntry lockEntry = groupValue.get(mq);
                    if (null != lockEntry) {
                        if (lockEntry.getClientId().equals(clientId)) {
                            groupValue.remove(mq);
                            log.info("unlockBatch, Group: {} {} {}",
                                group,
                                mq,
                                clientId);
                        } else {
                            log.warn("unlockBatch, but mq locked by other client: {}, Group: {} {} {}",
                                lockEntry.getClientId(),
                                group,
                                mq,
                                clientId);
                        }
                    } else {
                        log.warn("unlockBatch, but mq not locked, Group: {} {} {}",
                            group,
                            mq,
                            clientId);
                    }
                }
            } else {
                log.warn("unlockBatch, group not exist, Group: {} {}",
                    group,
                    clientId);
            }
        } finally {
            this.lock.unlock();
        }
    } catch (InterruptedException e) {
        log.error("putMessage exception", e);
    }
}
 
Example 20
Project: DAA_Converter   File: ReadHits.java   View Source Code Vote up 4 votes
public void add(Hit h, SparseString gi, int frame) {

		if (!hitMap.containsKey(gi))
			hitMap.put(gi, new ConcurrentHashMap<Integer, Vector<Hit>>());
		ConcurrentHashMap<Integer, Vector<Hit>> frameMap = hitMap.get(gi);

		if (!frameMap.containsKey(frame))
			frameMap.put(frame, new Vector<Hit>());
		Vector<Hit> hits = frameMap.get(frame);

		hits.add(h);

	}