批量存储信息
import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; public class MonitorStoreService4 extends Thread{ static final Logger logger = Logger.getLogger(MonitorStoreService4.class); LinkedList<List<Properties>> storeQueue = new LinkedList<List<Properties>>(); List<Properties> current = new LinkedList<Properties>(); boolean isRun = true; Object lock = new Object(); static int waitOvertime = 1000 * 30; static int currntMaxSize = 500; public void run(){ MonitorDao dao = new MonitorDao(); while(isRun){ synchronized(lock){ logger.debug("run() wait"); try{ lock.wait(waitOvertime); }catch(Exception ex){} } while(!storeQueue.isEmpty()){ List<Properties> item = storeQueue.removeFirst(); logger.debug("run() storeQueue.save."); if(!dao.save(item)){ storeQueue.addLast(item); } } } if(!storeQueue.isEmpty()){ List<Properties> item = storeQueue.removeFirst(); logger.debug("run() storeQueue.save."); if(!dao.save(item)){ } } if(!current.isEmpty()){ List<Properties> item = current; logger.debug("run() current.save."); if(!dao.save(item)){ } } logger.debug("run() shutdown."); } // synchronized public boolean append(Properties data){ if(!isRun) return false; if(current.size()>=currntMaxSize){ logger.debug("append() storeQueue.addLast"); storeQueue.addLast(current); current = new LinkedList<Properties>(); synchronized(lock){ lock.notifyAll(); } } // try{ Thread.sleep(1); }catch(Exception ex){} logger.debug("append() current.add"); return current.add(data); } public void shutdown(){ isRun = false; } }
fdkljfdljf
import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; public class MonitorDao { static final Logger logger = Logger.getLogger(MonitorDao.class); public boolean save(List<Properties> ls){ logger.debug("save size:"+ls.size()); for(Properties i:ls){ } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } return true; } }
测试
static void t5(){ MonitorStoreService4 ser = new MonitorStoreService4(); ser.start(); for(int i=0; i<100333; i++){ ser.append(new Properties()); } try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } ser.shutdown(); }
[Java]批量存储信息
时间: 2024-10-05 11:05:11