CompressionRatio { void restore() { if (!directory.exists()) { return; } File[] ratioFiles = directory.listFiles((dir, name) -> name.startsWith(FILE_PREFIX)); if (ratioFiles != null && ratioFiles.length > 0) { long maxTimes = 0; double maxCompressionRatioSum = 0; int maxRatioIndex = 0; for (int i = 0; i < ratioFiles.length; i++) { String[] splits = ratioFiles[i].getName().split("-"); long times = Long.parseLong(splits[2]); if (times > maxTimes) { maxTimes = times; maxCompressionRatioSum = Double.parseDouble(splits[1]); maxRatioIndex = i; } } calcTimes = maxTimes; compressionRatioSum = maxCompressionRatioSum; if (calcTimes != 0) { compressionRatio.set(compressionRatioSum / calcTimes); } LOGGER.debug( "After restoring from compression ratio file, compressionRatioSum = {}, calcTimes = {}", compressionRatioSum, calcTimes); for (int i = 0; i < ratioFiles.length; i++) { if (i != maxRatioIndex) { ratioFiles[i].delete(); } } } } private  CompressionRatio(); synchronized void updateRatio(double currentCompressionRatio); double getRatio(); double getCompressionRatioSum(); static CompressionRatio getInstance();  }
@Test public void testRestore() throws IOException { double compressionRatioSum = 0; int calcuTimes = 0; if (new File(directory, String.format(Locale.ENGLISH, CompressionRatio.RATIO_FILE_PATH_FORMAT, compressionRatioSum , calcuTimes)).exists()) { fail(); } int compressionRatio = 10; for(int i = 0; i < 100 ; i+= compressionRatio){ this.compressionRatio.updateRatio(compressionRatio); if (new File(directory, String.format(Locale.ENGLISH, CompressionRatio.RATIO_FILE_PATH_FORMAT, compressionRatioSum , calcuTimes)).exists()) { fail(); } calcuTimes++; compressionRatioSum += compressionRatio; if (!new File(directory, String.format(Locale.ENGLISH, CompressionRatio.RATIO_FILE_PATH_FORMAT, compressionRatioSum , calcuTimes)).exists()) { fail(); } assertEquals(0, Double .compare(compressionRatioSum / calcuTimes, this.compressionRatio.getRatio())); } this.compressionRatio.restore(); assertEquals(10, this.compressionRatio.getCalcTimes()); assertEquals(0, Double .compare(compressionRatioSum / calcuTimes, this.compressionRatio.getRatio())); }