From 9199f0d66be476789e073ea96571fa4017269896 Mon Sep 17 00:00:00 2001 From: mishako Date: Fri, 15 Jul 2016 22:18:29 +0200 Subject: [PATCH] Clean up threadlocal after usage ThreadLocal is not guaranteed to be garbage collected if the thread keeps running. This can lead to a memory leak in applications with long-living threads. Fixes #303 --- .../rome/feed/impl/ToStringBean.java | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/rome/src/main/java/com/rometools/rome/feed/impl/ToStringBean.java b/rome/src/main/java/com/rometools/rome/feed/impl/ToStringBean.java index d1ec50d..817fd0c 100644 --- a/rome/src/main/java/com/rometools/rome/feed/impl/ToStringBean.java +++ b/rome/src/main/java/com/rometools/rome/feed/impl/ToStringBean.java @@ -41,17 +41,7 @@ public class ToStringBean implements Serializable { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(ToStringBean.class); - private static final ThreadLocal> PREFIX_TL = new ThreadLocal>() { - @Override - public Stack get() { - Stack o = super.get(); - if (o == null) { - o = new Stack(); - set(o); - } - return o; - } - }; + private static final ThreadLocal> PREFIX_TL = new ThreadLocal>(); private static final Object[] NO_PARAMS = new Object[0]; @@ -113,7 +103,15 @@ public class ToStringBean implements Serializable { */ @Override public String toString() { - final Stack stack = PREFIX_TL.get(); + Stack stack = PREFIX_TL.get(); + boolean needStackCleanup = false; + + if (stack == null) { + stack = new Stack(); + PREFIX_TL.set(stack); + needStackCleanup = true; + } + final String[] tsInfo; if (stack.isEmpty()) { tsInfo = null; @@ -128,7 +126,14 @@ public class ToStringBean implements Serializable { prefix = tsInfo[0]; tsInfo[1] = prefix; } - return this.toString(prefix); + + final String result = toString(prefix); + + if (needStackCleanup) { + PREFIX_TL.remove(); + } + + return result; } /**