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
This commit is contained in:
parent
998bf4ac8e
commit
9199f0d66b
1 changed files with 18 additions and 13 deletions
|
@ -41,17 +41,7 @@ public class ToStringBean implements Serializable {
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(ToStringBean.class);
|
private static final Logger LOG = LoggerFactory.getLogger(ToStringBean.class);
|
||||||
|
|
||||||
private static final ThreadLocal<Stack<String[]>> PREFIX_TL = new ThreadLocal<Stack<String[]>>() {
|
private static final ThreadLocal<Stack<String[]>> PREFIX_TL = new ThreadLocal<Stack<String[]>>();
|
||||||
@Override
|
|
||||||
public Stack<String[]> get() {
|
|
||||||
Stack<String[]> o = super.get();
|
|
||||||
if (o == null) {
|
|
||||||
o = new Stack<String[]>();
|
|
||||||
set(o);
|
|
||||||
}
|
|
||||||
return o;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
private static final Object[] NO_PARAMS = new Object[0];
|
private static final Object[] NO_PARAMS = new Object[0];
|
||||||
|
|
||||||
|
@ -113,7 +103,15 @@ public class ToStringBean implements Serializable {
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
final Stack<String[]> stack = PREFIX_TL.get();
|
Stack<String[]> stack = PREFIX_TL.get();
|
||||||
|
boolean needStackCleanup = false;
|
||||||
|
|
||||||
|
if (stack == null) {
|
||||||
|
stack = new Stack<String[]>();
|
||||||
|
PREFIX_TL.set(stack);
|
||||||
|
needStackCleanup = true;
|
||||||
|
}
|
||||||
|
|
||||||
final String[] tsInfo;
|
final String[] tsInfo;
|
||||||
if (stack.isEmpty()) {
|
if (stack.isEmpty()) {
|
||||||
tsInfo = null;
|
tsInfo = null;
|
||||||
|
@ -128,7 +126,14 @@ public class ToStringBean implements Serializable {
|
||||||
prefix = tsInfo[0];
|
prefix = tsInfo[0];
|
||||||
tsInfo[1] = prefix;
|
tsInfo[1] = prefix;
|
||||||
}
|
}
|
||||||
return this.toString(prefix);
|
|
||||||
|
final String result = toString(prefix);
|
||||||
|
|
||||||
|
if (needStackCleanup) {
|
||||||
|
PREFIX_TL.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
Loading…
Reference in a new issue