Restart downed nodes.
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / io / SharedFileBackedOutputStream.java
1 /*
2  * Copyright (c) 2017 Inocybe Technologies and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.io;
9
10 import com.google.common.base.Preconditions;
11 import java.util.concurrent.atomic.AtomicInteger;
12 import java.util.function.Consumer;
13
14 /**
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.
19  *
20  * @author Thomas Pantelis
21  */
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;
27
28     public SharedFileBackedOutputStream(int fileThreshold, String fileDirectory) {
29         super(fileThreshold, fileDirectory);
30     }
31
32     /**
33      * Increments the usage count. This must be followed by a corresponding call to {@link #cleanup()} when this
34      * instance is no longer needed.
35      */
36     public void incrementUsageCount() {
37         usageCount.getAndIncrement();
38     }
39
40     /**
41      * Returns the current usage count.
42      *
43      * @return the current usage count
44      */
45     public int getUsageCount() {
46         return usageCount.get();
47     }
48
49     /**
50      * Sets the callback to be notified when {@link FileBackedOutputStream#cleanup()} is called to delete the backing
51      * file.
52      */
53     public <T> void setOnCleanupCallback(Consumer<T> callback, T context) {
54         onCleanupCallback = callback;
55         onCleanupContext = context;
56     }
57
58     /**
59      * Overridden to decrement the usage count.
60      */
61     @SuppressWarnings("unchecked")
62     @Override
63     public void cleanup() {
64         Preconditions.checkState(usageCount.get() > 0);
65
66         if (usageCount.decrementAndGet() == 0) {
67             super.cleanup();
68
69             if (onCleanupCallback != null) {
70                 onCleanupCallback.accept(onCleanupContext);
71             }
72         }
73     }
74 }