2 * Copyright (c) 2017 Inocybe Technologies and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.io;
10 import com.google.common.base.Preconditions;
11 import java.util.concurrent.atomic.AtomicInteger;
12 import java.util.function.Consumer;
15 * A FileBackedOutputStream that allows for sharing in that it maintains a usage count and the backing file isn't
16 * deleted until the usage count reaches 0. The usage count is initialized to 1 on construction. Subsequent users of
17 * the instance must call {@link #incrementUsageCount()}. The {@link #cleanup()} method decrements the usage count and,
18 * when it reaches 0, the {@link FileBackedOutputStream#cleanup()} is called to delete the backing file.
20 * @author Thomas Pantelis
22 public class SharedFileBackedOutputStream extends FileBackedOutputStream {
23 private final AtomicInteger usageCount = new AtomicInteger(1);
24 @SuppressWarnings("rawtypes")
25 private Consumer onCleanupCallback;
26 private Object onCleanupContext;
28 public SharedFileBackedOutputStream(int fileThreshold, String fileDirectory) {
29 super(fileThreshold, fileDirectory);
33 * Increments the usage count. This must be followed by a corresponding call to {@link #cleanup()} when this
34 * instance is no longer needed.
36 public void incrementUsageCount() {
37 usageCount.getAndIncrement();
41 * Returns the current usage count.
43 * @return the current usage count
45 public int getUsageCount() {
46 return usageCount.get();
50 * Sets the callback to be notified when {@link FileBackedOutputStream#cleanup()} is called to delete the backing
53 public <T> void setOnCleanupCallback(Consumer<T> callback, T context) {
54 onCleanupCallback = callback;
55 onCleanupContext = context;
59 * Overridden to decrement the usage count.
61 @SuppressWarnings("unchecked")
63 public void cleanup() {
64 Preconditions.checkState(usageCount.get() > 0);
66 if (usageCount.decrementAndGet() == 0) {
69 if (onCleanupCallback != null) {
70 onCleanupCallback.accept(onCleanupContext);