Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+8 votes
5 views
in Java by (1.5k points)
recategorized by

What is meant by a memory leak in Java, and how to implement it.

2 Answers

+12 votes
by (13.2k points)
edited by

What is meant by Memory Leak?

The memory leak is a condition in which the program continues to hold on to the allocated memory even after the program no longer needs it and it just lies there i.e. inaccessible but still stored in the memory. Now, you can get memory leaks for java by manual memory management via JNI and thus have memory leaks, or by having bugs in JVM may also lead to memory leak.

Now, there can be many ways in which you may achieve memory leak ( from two ways listed above), few of them are :-

  1. Field holding object reference

class Darthvader {

static final ArrayList arraylist = new ArrayList(100);

}

    2. Unclosed connections

try {

Connection connect = ConnectionFactory.getConnection();

} catch (Exception s) {

s.printStacktrace();

}

3.Open streams

try {

    BufferedReader buffer = new BufferedReader(new FileReader(inputFile));

   

} catch (Exception s) {

    s.printStacktrace();

}

0 votes
by (32.3k points)

You can try using a HashSet with an incorrect (or non-existent) hashCode() or equals(), and then keep adding "duplicates". Instead of ignoring duplicates as it should, the set will only ever grow and you won't be able to remove them.

Are you interested in learning Java from scratch! Refer to this video on Java from basics to advance:

 

But, If you want these bad keys/elements to hang around you can use a static field like this:

class BadKey {

   // no hashCode or equals();

   public final String key;

   public BadKey(String key) { this.key = key; }

}

Map map = System.getProperties();

map.put(new BadKey("key"), "value"); // Memory leak even if your threads die.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 2, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 29, 2019 in Java by Nigam (4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...