1 /**
2 * Logback: the reliable, generic, fast and flexible logging framework.
3 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4 *
5 * This program and the accompanying materials are dual-licensed under
6 * either the terms of the Eclipse Public License v1.0 as published by
7 * the Eclipse Foundation
8 *
9 * or (per the licensee's choosing)
10 *
11 * under the terms of the GNU Lesser General Public License version 2.1
12 * as published by the Free Software Foundation.
13 */
14 package ch.qos.logback.core.net;
15
16 import java.io.IOException;
17 import java.io.ObjectOutputStream;
18
19 /**
20 * Automatically flushes the underlying {@link java.io.ObjectOutputStream}
21 * immediately after calling it's
22 * {@link java.io.ObjectOutputStream#writeObject(Object)} method.
23 *
24 * @author Sebastian Gröbler
25 */
26 public class AutoFlushingObjectWriter implements ObjectWriter {
27
28 private final ObjectOutputStream objectOutputStream;
29 private final int resetFrequency;
30 private int writeCounter = 0;
31
32 /**
33 * Creates a new instance for the given {@link java.io.ObjectOutputStream}.
34 *
35 * @param objectOutputStream the stream to write to
36 * @param resetFrequency the frequency with which the given stream will be
37 * automatically reset to prevent a memory leak
38 */
39 public AutoFlushingObjectWriter(ObjectOutputStream objectOutputStream, int resetFrequency) {
40 this.objectOutputStream = objectOutputStream;
41 this.resetFrequency = resetFrequency;
42 }
43
44 @Override
45 public void write(Object object) throws IOException {
46 objectOutputStream.writeObject(object);
47 objectOutputStream.flush();
48 preventMemoryLeak();
49 }
50
51 /**
52 * Failing to reset the object output stream every now and then creates a
53 * serious memory leak which is why the underlying stream will be reset
54 * according to the {@code resetFrequency}.
55 */
56 private void preventMemoryLeak() throws IOException {
57 if (++writeCounter >= resetFrequency) {
58 objectOutputStream.reset();
59 writeCounter = 0;
60 }
61 }
62 }