Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I just had an interview, and I was asked to create a memory leak with Java.
Needless to say, I felt pretty dumb having no clue on how to even start creating one.

What would an example be?

1 Answer

0 votes
by (46k points)

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();

}

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 2, 2019 by Anvi (10.2k points)
+8 votes
2 answers
asked May 23, 2019 in Java by Rohan (1.5k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 29, 2019 in Java by Nigam (4k points)

Browse Categories

...