Java异步存储数据线程

package com.panda.core.db.asyncdb;

import com.panda.core.db.impl.MongoDBService;
import com.panda.core.db.model.IEntity;
import org.mongodb.morphia.dao.DAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 异步存储数据
 * Created by Lovell on 9/26/16.
 */

public class DBThread implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(DBThread.class);

    private DBQueue queue;

    public DBThread(DBQueue queue) {
        this.queue = queue;
    }
    @SuppressWarnings("uncheck")
    @Override
    public void run() {
        while(true) {
            try {
                int queueSize = queue.size();
                if (queueSize == 0) {
                    waitThead();
                } else {
                    IEntity entity = queue.pop();
                    if (entity == null) continue;

                    DAO dao = MongoDBService.getInstance().getDao(entity.getClass());
                    dao.save(entity);
                    if(queueSize>1000){
                        logger.warn("db queue size is then 1000,queueSize={}",queueSize);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    /**
     * 等待线程
     */
    private void waitThead() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
    }
}

你可能感兴趣的:(Java)