2 * Copyright (c) 2017 Brocade Communications Systems, Inc. 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.annotations.VisibleForTesting;
11 import com.google.common.base.FinalizablePhantomReference;
12 import com.google.common.base.FinalizableReferenceQueue;
13 import com.google.common.collect.Sets;
14 import com.google.common.io.ByteSource;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.io.ByteArrayInputStream;
17 import java.io.ByteArrayOutputStream;
19 import java.io.FileInputStream;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.util.Iterator;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import javax.annotation.concurrent.GuardedBy;
29 import javax.annotation.concurrent.ThreadSafe;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * An {@link OutputStream} that starts buffering to a byte array, but switches to file buffering once the data
35 * reaches a configurable size. This class is thread-safe.
37 * @author Thomas Pantelis
40 public class FileBackedOutputStream extends OutputStream {
41 private static final Logger LOG = LoggerFactory.getLogger(FileBackedOutputStream.class);
44 * This stores the Cleanup PhantomReference instances statically. This is necessary because PhantomReferences
45 * need a hard reference so they're not garbage collected. Once finalized, the Cleanup PhantomReference removes
46 * itself from this map and thus becomes eligible for garbage collection.
49 static final Set<Cleanup> REFERENCE_CACHE = Sets.newConcurrentHashSet();
52 * Used as the ReferenceQueue for the Cleanup PhantomReferences.
54 private static final FinalizableReferenceQueue REFERENCE_QUEUE = new FinalizableReferenceQueue();
56 private final int fileThreshold;
57 private final String fileDirectory;
60 private MemoryOutputStream memory = new MemoryOutputStream();
63 private OutputStream out = memory;
69 private ByteSource source;
71 private volatile long count;
74 * Creates a new instance that uses the given file threshold, and does not reset the data when the
75 * {@link ByteSource} returned by {@link #asByteSource} is finalized.
77 * @param fileThreshold the number of bytes before the stream should switch to buffering to a file
78 * @param fileDirectory the directory in which to create the file if needed. If null, the default temp file
81 public FileBackedOutputStream(int fileThreshold, @Nullable String fileDirectory) {
82 this.fileThreshold = fileThreshold;
83 this.fileDirectory = fileDirectory;
87 * Returns a readable {@link ByteSource} view of the data that has been written to this stream. This stream is
88 * closed and further attempts to write to it will result in an IOException.
90 * @return a ByteSource instance
91 * @throws IOException if close fails
94 public synchronized ByteSource asByteSource() throws IOException {
98 source = new ByteSource() {
100 public InputStream openStream() throws IOException {
101 synchronized (FileBackedOutputStream.this) {
103 return new FileInputStream(file);
105 return new ByteArrayInputStream(memory.getBuffer(), 0, memory.getCount());
121 @SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT", justification = "Findbugs erroneously complains that the "
122 + "increment of count needs to be atomic even though it is inside a synchronized block.")
123 public synchronized void write(int value) throws IOException {
124 possiblySwitchToFile(1);
130 public synchronized void write(byte[] bytes) throws IOException {
131 write(bytes, 0, bytes.length);
135 public synchronized void write(byte[] bytes, int off, int len) throws IOException {
136 possiblySwitchToFile(len);
137 out.write(bytes, off, len);
142 public synchronized void close() throws IOException {
144 OutputStream closeMe = out;
151 public synchronized void flush() throws IOException {
157 public synchronized long getCount() {
162 * Calls {@link #close} if not already closed and, if data was buffered to a file, deletes the file.
164 public synchronized void cleanup() {
165 LOG.debug("In cleanup");
170 Iterator<Cleanup> iter = REFERENCE_CACHE.iterator();
171 while (iter.hasNext()) {
172 if (file.equals(iter.next().file)) {
178 LOG.debug("cleanup - deleting temp file {}", file);
186 private void closeQuietly() {
189 } catch (IOException e) {
190 LOG.warn("Error closing output stream {}", out, e);
195 * Checks if writing {@code len} bytes would go over threshold, and switches to file buffering if so.
198 private void possiblySwitchToFile(int len) throws IOException {
200 throw new IOException("Stream already closed");
203 if (file == null && memory.getCount() + len > fileThreshold) {
204 File temp = File.createTempFile("FileBackedOutputStream", null, new File(fileDirectory));
207 LOG.debug("Byte count {} has exceeded threshold {} - switching to file: {}", memory.getCount() + len,
208 fileThreshold, temp);
210 FileOutputStream transfer = null;
212 transfer = new FileOutputStream(temp);
213 transfer.write(memory.getBuffer(), 0, memory.getCount());
216 // We've successfully transferred the data; switch to writing to file
221 new Cleanup(this, file);
222 } catch (IOException e) {
223 if (transfer != null) {
226 } catch (IOException ex) {
227 LOG.debug("Error closing temp file {}", temp, ex);
237 private static void deleteFile(File file) {
238 if (!file.delete()) {
239 LOG.warn("Could not delete temp file {}", file);
244 * ByteArrayOutputStream that exposes its internals for efficiency.
246 private static class MemoryOutputStream extends ByteArrayOutputStream {
257 * PhantomReference that deletes the temp file when the FileBackedOutputStream is garbage collected.
259 private static class Cleanup extends FinalizablePhantomReference<FileBackedOutputStream> {
260 private final File file;
262 Cleanup(FileBackedOutputStream referent, File file) {
263 super(referent, REFERENCE_QUEUE);
266 REFERENCE_CACHE.add(this);
268 LOG.debug("Added Cleanup for temp file {}", file);
272 public void finalizeReferent() {
273 LOG.debug("In finalizeReferent");
275 if (REFERENCE_CACHE.remove(this)) {
276 LOG.debug("finalizeReferent - deleting temp file {}", file);