All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.alibaba.rocketmq.common.queue.ConcurrentTreeMap Maven / Gradle / Ivy

package com.alibaba.rocketmq.common.queue;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.rocketmq.common.constant.LoggerName;


/**
 * thread safe
 * 
 * @auther lansheng.zj
 */
public class ConcurrentTreeMap {
    private static final Logger log = LoggerFactory.getLogger(LoggerName.BrokerLoggerName);

    private TreeMap tree;
    private RoundQueue roundQueue;
    private final ReentrantLock lock;


    public ConcurrentTreeMap(int capacity, Comparator comparator) {
        tree = new TreeMap(comparator);
        roundQueue = new RoundQueue(capacity);
        lock = new ReentrantLock(true);
    }


    public Map.Entry pollFirstEntry() {
        lock.lock();
        try {
            return tree.pollFirstEntry();
        }
        finally {
            lock.unlock();
        }
    }


    public V putIfAbsentAndRetExsit(K key, V value) {
        lock.lock();
        try {
            if (roundQueue.put(key)) {
                V exsit = tree.get(key);
                if (null == exsit) {
                    tree.put(key, value);
                    exsit = value;
                }
                log.warn("putIfAbsentAndRetExsit success. {}", key);
                return exsit;
            }
            // 已经存在
            else {
                V exsit = tree.get(key);
                return exsit;
            }
        }
        finally {
            lock.unlock();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy