From 9ff69f265dae8f0647fb9c204fda070eafe25613 Mon Sep 17 00:00:00 2001
From: Matthew Swift <matthew.swift@forgerock.com>
Date: Wed, 13 Jun 2012 21:05:11 +0000
Subject: [PATCH] Fix OPENDJ-520: Worker threads are too greedy when caching memory used for encoding/decoding entries and protocol messages

---
 opends/src/server/org/opends/server/protocols/asn1/ByteSequenceOutputStream.java |   26 +++++++++++++++++++++-----
 1 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/opends/src/server/org/opends/server/protocols/asn1/ByteSequenceOutputStream.java b/opends/src/server/org/opends/server/protocols/asn1/ByteSequenceOutputStream.java
index ae04d5b..d5f86d9 100644
--- a/opends/src/server/org/opends/server/protocols/asn1/ByteSequenceOutputStream.java
+++ b/opends/src/server/org/opends/server/protocols/asn1/ByteSequenceOutputStream.java
@@ -23,6 +23,7 @@
  *
  *
  *      Copyright 2006-2008 Sun Microsystems, Inc.
+ *      Portions copyright 2012 ForgeRock AS.
  */
 package org.opends.server.protocols.asn1;
 
@@ -36,18 +37,26 @@
  * with the outputstream interface.
  */
 final class ByteSequenceOutputStream extends OutputStream {
+  private static final int BUFFER_INIT_SIZE = 32;
 
   private final ByteStringBuilder buffer;
+  private final int maxInternalBufferSize;
 
   /**
    * Creates a new byte string builder output stream.
    *
    * @param buffer
    *          The underlying byte string builder.
+   * @param maxInternalBufferSize
+   *          The threshold capacity beyond which internal cached buffers used
+   *          for encoding and decoding protocol messages will be trimmed after
+   *          use.
    */
-  ByteSequenceOutputStream(ByteStringBuilder buffer)
+  ByteSequenceOutputStream(ByteStringBuilder buffer, int maxInternalBufferSize)
   {
     this.buffer = buffer;
+    this.maxInternalBufferSize = Math.max(maxInternalBufferSize,
+        BUFFER_INIT_SIZE);
   }
 
   /**
@@ -98,18 +107,25 @@
   }
 
   /**
-   * Resets this output stream such that the underlying byte string
-   * builder is empty.
+   * Resets this output stream such that the underlying byte string builder is
+   * empty, and also has a capacity which is not too big.
    */
   void reset()
   {
-    buffer.clear();
+    if (buffer.capacity() > maxInternalBufferSize)
+    {
+      buffer.clear(BUFFER_INIT_SIZE);
+    }
+    else
+    {
+      buffer.clear();
+    }
   }
 
   /**
    * {@inheritDoc}
    */
   public void close() throws IOException {
-    buffer.clear();
+    reset();
   }
 }

--
Gitblit v1.10.0