View Javadoc
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} immediately after calling
21   * it's {@link java.io.ObjectOutputStream#writeObject(Object)} method.
22   *
23   * @author Sebastian Gröbler
24   */
25  public class AutoFlushingObjectWriter implements ObjectWriter {
26  
27      private final ObjectOutputStream objectOutputStream;
28      private final int resetFrequency;
29      private int writeCounter = 0;
30  
31      /**
32       * Creates a new instance for the given {@link java.io.ObjectOutputStream}.
33       *
34       * @param objectOutputStream the stream to write to
35       * @param resetFrequency the frequency with which the given stream will be
36       *                       automatically reset to prevent a memory leak
37       */
38      public AutoFlushingObjectWriter(ObjectOutputStream objectOutputStream, int resetFrequency) {
39          this.objectOutputStream = objectOutputStream;
40          this.resetFrequency = resetFrequency;
41      }
42  
43      @Override
44      public void write(Object object) throws IOException {
45          objectOutputStream.writeObject(object);
46          objectOutputStream.flush();
47          preventMemoryLeak();
48      }
49  
50      /**
51       * Failing to reset the object output stream every now and then creates a serious memory leak which
52       * is why the underlying stream will be reset according to the {@code resetFrequency}.
53       */
54      private void preventMemoryLeak() throws IOException {
55          if (++writeCounter >= resetFrequency) {
56              objectOutputStream.reset();
57              writeCounter = 0;
58          }
59      }
60  }