Reputation: 7343
well I found this code in a blog, and wanted to understand why it would cause a memory leak, if it is potential of causing a memory leak.
class Test {
public static void main(String[] args) {
Runnable runnable = new EnterpriseBean()
.runnable();
runnable.run(); // Breakpoint here
}
}
@ImportantDeclaration
@NoMoreXML({
@CoolNewValidationStuff("Annotations"),
@CoolNewValidationStuff("Rock")
})
class EnterpriseBean {
Object[] enterpriseStateObject =
new Object[100_000_000];
Runnable runnable() {
return () -> {
System.out.println("Hello from: " + this);
};
}
}
Upvotes: 1
Views: 3207
Reputation: 181008
The provided code does not have a memory leak, and the blog entry from which it is drawn does not say otherwise. What it says is that the object returned by EnterpriseBean.runnable()
has much (much) larger state than you might naively expect, and that that state cannot be garbage collected before the Runnable
itself is.
However, there is nothing in that code that would prevent the Runnable
from eventually being collected, and at that time all the extra state will be eligible for collection, too.
So no, the code is not an example of a memory leak, and does not suggest a means to produce one.
Upvotes: 6