Reputation: 19825
I am looking for a simple program that can demonstrate memory leak in Java.
Thanks.
Upvotes: 5
Views: 8658
Reputation: 15423
Let's first defined what is a memory leak in Java context - it's a situation when a program can mistakenly hold a reference to an object that is never again used during the rest of the program's run.
An example to it, would be forgetting to close an opened stream:
class MemoryLeak {
private void startLeaking() throws IOException {
StringBuilder input = new StringBuilder();
URLConnection conn = new URL("www.example.com/file.txt").openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
while (br.readLine() != null) {
input.append(br.readLine());
}
}
public static void main(String[] args) throws IOException {
MemoryLeak ml = new MemoryLeak();
ml.startLeaking();
}
}
Upvotes: 0
Reputation: 2265
Vector v = new Vector();
while (true)
{
byte b[] = new byte[1048576];
v.add(b);
}
This will continuously add a 1MB byte to a vector until it runs out of memory
Upvotes: 1
Reputation: 43108
http://www.codeproject.com/KB/books/EffectiveJava.aspx
See Item 6.
Upvotes: 3
Reputation:
Memory leak are for example if you have references that are not necessary any more but can't get catched by the garbage collector.
There are simple examples e.g. from IBM that shows the principle:
http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/
Upvotes: 2
Reputation: 16250
A great example from a great book: http://www.informit.com/articles/article.aspx?p=1216151&seqNum=6
Upvotes: 0