public void run() { CountDownLatch countDownLatch = new CountDownLatch(1); try{ try{ if(!GlobalConstants.IB_GATEWAY_LOG_URL.equals(logUrl)) { logger.info("change log url : \n old : {} \n new : {}", logUrl, GlobalConstants.IB_GATEWAY_LOG_URL); // 读取重启前上一次读取后遗留的日志 if(logUrl != null && !"".equals(logUrl)) { int res = readLogFile(logUrl); if(res == 0) { logger.info("read last restart success"); anotherDay = false; } else if(res == 1) { logger.info("last restart file not found"); } else { logger.info("last restart file read fail"); } } logUrl = GlobalConstants.IB_GATEWAY_LOG_URL; } } catch (Exception e){ logger.error(e.getMessage(), e); } finally { countDownLatch.countDown(); } countDownLatch.await(); countDownLatch = new CountDownLatch(1); // 判断是否隔天 Date now = new Date(); String stnow = dateOnly.format(now); String stformer = dateOnly.format(startTime); if(!stnow.equals(stformer)) { // 说明隔天了,激活隔天读取机制 anotherDay = true; logger.info("another day"); } try{ if(anotherDay) { String logUrlTemp = logUrl; int index = logUrlTemp.lastIndexOf("."); StringBuilder stringBuilder = new StringBuilder(100); stringBuilder.append(logUrlTemp.substring(0, index+1)).append(dateIbFormate.format(startTime)).append(".log"); int res = readLogFile(stringBuilder.toString()); if(res == 0) { logger.info("read yesterday success"); anotherDay = false; } else if(res == 1) { logger.info("yesterday file not found"); } else { logger.info("yestoday file read fail"); } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { countDownLatch.countDown(); } countDownLatch.await(); readLogFile(logUrl); } catch (Exception e) { logger.error(e.getMessage(), e); }
在未使用CountDownLatch前,有出现最后一行
readLogFile
的数据先于前面的代码数据执行插入操作了,故为了确保数据有序性,加入CountDownLatch
性质有点像:https://www.cnblogs.com/silyvin/p/9106641.html
原文:https://www.cnblogs.com/silyvin/p/9448012.html