Is it possible to create a memory leak with Java

0 votes
If possible, what would be a good example for it?
May 30, 2018 in Java by Daisy
• 8,090 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 30, 2018 by Parth
• 4,640 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
• 48,810 points
+5 votes
3 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,400 points

edited Nov 6, 2018 by Omkar 14,487 views
0 votes
2 answers

How to create a 2-D array in java?

int[][] multi = new int[5][]; multi[0] = new ...READ MORE

answered Jul 16, 2018 in Java by Daisy
• 8,090 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,430 points
+8 votes
11 answers

Default parameters of XMS and XMX in JVM

-xmx and -xms are the parameters used ...READ MORE

answered Jun 1, 2018 in Java by v.liyyah
• 1,320 points
0 votes
1 answer

Increasing the JVM memory using command line

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

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

Maximum memory usage for JVM

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

answered Nov 13, 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 27, 2018 in Java by samarth295
• 2,190 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,640 points