@@ -177,13 +177,12 @@ private static void performStateDirectoriesFsync(List<Tuple<Path, Directory>> st
177177 }
178178
179179 /**
180- * Writes the given state to the given directories and performs cleanup.
180+ * Writes the given state to the given directories and performs cleanup of old state files if the write succeeds or
181+ * newly created state file if write fails.
181182 * See also {@link #write(Object, Path...)} and {@link #cleanupOldFiles(long, Path[])}.
182183 */
183184 public final long writeAndCleanup (final T state , final Path ... locations ) throws WriteStateException {
184- long currentGeneration = write (state , locations );
185- cleanupOldFiles (currentGeneration ,locations );
186- return currentGeneration ;
185+ return write (state , true , locations );
187186 }
188187
189188 /**
@@ -207,6 +206,10 @@ public final long writeAndCleanup(final T state, final Path... locations) throws
207206 * @return generation of newly written state.
208207 */
209208 public final long write (final T state , final Path ... locations ) throws WriteStateException {
209+ return write (state , false , locations );
210+ }
211+
212+ private final long write (final T state , boolean cleanup , final Path ... locations ) throws WriteStateException {
210213 if (locations == null ) {
211214 throw new IllegalArgumentException ("Locations must not be null" );
212215 }
@@ -242,7 +245,9 @@ public final long write(final T state, final Path... locations) throws WriteStat
242245 performRenames (tmpFileName , fileName , directories );
243246 performStateDirectoriesFsync (directories );
244247 } catch (WriteStateException e ) {
245- cleanupOldFiles (oldGenerationId , locations );
248+ if (cleanup ) {
249+ cleanupOldFiles (oldGenerationId , locations );
250+ }
246251 throw e ;
247252 } finally {
248253 for (Tuple <Path , Directory > pathAndDirectory : directories ) {
@@ -251,6 +256,10 @@ public final long write(final T state, final Path... locations) throws WriteStat
251256 }
252257 }
253258
259+ if (cleanup ) {
260+ cleanupOldFiles (newGenerationId , locations );
261+ }
262+
254263 return newGenerationId ;
255264 }
256265
0 commit comments