Is it possible to create a memory leak with Java

0 votes
If possible, what would be a good example for it?
May 31, 2018 in Java by Daisy
• 8,110 points

1 answer to this question.

0 votes

Here's a good way to create a memory leak in pure Java:

  1.  a long-running thread  is created by the application
  2. The thread loads a class via an (optionally custom) ClassLoader
  3. The class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal
  4. Allocating the extra memory is optional, but it will make the leak work that much faster
  5. All references are cleared to the custom class or the ClassLoader  from which it was loaded
  6. Repeat

This works because the ThreadLocal keeps a reference to the object, which keeps a reference to its Class, which in turn keeps a reference to its ClassLoader. The ClassLoader, in turn, keeps a reference to all the Classes it has loaded

answered May 31, 2018 by Parth
• 4,630 points

Related Questions In Java

0 votes
1 answer

Is it possible to run a java program from command line on windows?How?

  Let's say your file is in C:\myprogram\ Run ...READ MORE

answered Apr 18, 2018 in Java by sophia
• 1,400 points
0 votes
2 answers

Why it is not possible to define a static method in a Java interface?

Interfaces are concerned with polymorphism which is ...READ MORE

answered Aug 27, 2019 in Java by Sirajul
• 59,090 points
0 votes
1 answer

How to create a memory leak in Java?

Hello @kartik, A simple thing to do is ...READ MORE

answered Jul 28, 2020 in Java by Niroj
• 82,880 points
0 votes
1 answer

Is it possible to upload a file from desktop to web using Selenide?

Hi, @Nikhil, Yes it's possible to drop a ...READ MORE

answered Dec 16, 2020 in Java by Gitika
• 65,970 points
0 votes
1 answer

java.lang.OutOfMemoryError: GC overhead limit exceeded Error

This simply means that for some reason ...READ MORE

answered May 31, 2018 in Java by misc.edu04
• 1,440 points
+10 votes
13 answers

Default parameters of XMS and XMX in JVM

Run this code to see all the ...READ MORE

answered Nov 13, 2018 in Java by anonymous
0 votes
1 answer

Increasing the JVM memory using command line

You can adjust your JVM memory needs by ...READ MORE

answered Sep 25, 2018 in Java by geek.erkami
• 2,680 points
+1 vote
1 answer

Maximum memory usage for JVM

I guess, you can try using the ...READ MORE

answered Nov 14, 2018 in Java by 93.lynn
• 1,600 points
0 votes
3 answers

How to read a Text File in Java?

You can use readAllLines and the join method to ...READ MORE

answered Jul 28, 2018 in Java by samarth295
• 2,220 points
0 votes
2 answers

How to read a text file in Java?

You can use Scanner class to read ...READ MORE

answered Aug 9, 2018 in Java by Parth
• 4,630 points