Java非同期ストレージデータキュー

5924 ワード

package com.panda.core.db.asyncdb;

import com.panda.core.db.model.IEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 *            
 * Created by Lovell on 16/6/20.
 */
public class DBQueue {
    private static Logger logger = LoggerFactory.getLogger(DBQueue.class);
    private BlockingQueue blockingQueue = new LinkedBlockingQueue();
    private Map, Serializable> entities = new ConcurrentHashMap, Serializable>();

    /**
     *         
     */
    public void add(IEntity entity) {
        String key = entity.getClass().getSimpleName() + "#" + entity.getId();
        if (blockingQueue.contains(key)) {
            try {
                blockingQueue.offer(key, 1, TimeUnit.SECONDS);
            }catch (InterruptedException e) {
                e.printStackTrace();
                logger.error("db queue is full error...");
            }
        }
        entities.put(key, entity);
    }
    /**
     *          
     */
    public IEntity pop() {
        String id = blockingQueue.poll();
        return (IEntity) entities.remove(id);
    }

    /**
     *      
     */
    public int size() {
        return blockingQueue.size();
    }
}