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?
Join Stack Overflow to learn, share knowledge, and build your career.
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?
there are many different situations memory will leak. One i encountered, which expose a map that should not be exposed and used in other place.
public class ServiceFactory {
private Map<String, Service> services;
private static ServiceFactory singleton;
private ServiceFactory() {
services = new HashMap<String, Service>();
}
public static synchronized ServiceFactory getDefault() {
if (singleton == null) {
singleton = new ServiceFactory();
}
return singleton;
}
public void addService(String name, Service serv) {
services.put(name, serv);
}
public void removeService(String name) {
services.remove(name);
}
public Service getService(String name, Service serv) {
return services.get(name);
}
// the problematic api, which expose the map.
//and user can do quite a lot of thing from this api.
//for example, create service reference and forget to dispose or set it null
//in all this is a dangerous api, and should not expose
public Map<String, Service> getAllServices() {
return services;
}
}
// resource class is a heavy class
class Service {
}
An example I recently fixed is creating new GC and Image objects, but forgetting to call dispose() method.
GC javadoc snippet:
Application code must explicitly invoke the GC.dispose() method to release the operating system resources managed by each instance when those instances are no longer required. This is particularly important on Windows95 and Windows98 where the operating system has a limited number of device contexts available.
Image javadoc snippet:
Application code must explicitly invoke the Image.dispose() method to release the operating system resources managed by each instance when those instances are no longer required.
Theoretically you can't. Java memory model prevents it. However, because Java has to be implemented, there are some caveats you can use. Depends on what you can use:
If you can use native, you can allocate memory that you don not relinquish later.
If that is not available, there is a dirty little secret about java that not much people know. You can ask for a direct access array that is not managed by GC, and therefor can be easily used to make a memory leak. This is provided by DirectByteBuffer (http://download.oracle.com/javase/1.5.0/docs/api/java/nio/ByteBuffer.html#allocateDirect(int)).
If you can't use any of those, you still can make a memory leak by tricking the GC. The JVM is implemented using a Generational garbage collection. What this means is that the heap is divided into areas: young, adults and elders. An object when its created starts at the young area. As he is used more and more, he progresses into adults up to elders. An object that reaches the eldery area most likely will not be garbaged collected. You cannot be sure that an object is leaked and if you ask for a stop and clean GC it may clean it but for a long period of time he will be leaked. More info at (http://java.sun.com/docs/hotspot/gc1.4.2/faq.html)
Also, class objects are not required to be GC'ed. Might me a way to do it.
A thread that does not terminate (say sleeps indefinitely in its run method). It will not be garbage collected even if we loose a reference to it. You can add fields to make the thread object is a big as you want.
The currently top answer lists more tricks around this but these seem redundant.
I want to give an advice on how to monitor application for the memory leaks with the tools that are available in JVM. It doesn't show how to generate the memory leak but explains how to detect it with minimum tools available.
You need to monitor Java memory consumption first.
The simplest way to do this is to use jstat utility that comes with JVM.
jstat -gcutil <process_id> <timeout>
It will report memory consumption for each generation (Young, Eldery and Old) and garbage collection times (Young and Full).
As soon as you spot that Full Garbage Collection is executed too often and takes too much time, you can assume that application is leaking memory.
Then you need to create a memory dump using jmap utility:
jmap -dump:live,format=b,file=heap.bin <process_id>
Then you need to analyse heap.bin file with Memory Analyser, Eclipse Memory Analyzer (MAT) for example.
MAT will analyze the memory and provide you suspect information about memory leaks.
Most of the memory leaks I've seen in java concern processes getting out of sync.
Process A talks to B via TCP, and tells process B to create something. B issues the resource an ID, say 432423, which A stores in an object and uses while talking to B. At some point the object in A is reclaimed by garbage collection (maybe due to a bug), but A never tells B that (maybe another bug).
Now A doesn't have the ID of the object it's created in B's RAM any more, and B doesn't know that A has no more reference to the object. In effect, the object is leaked.
A few suggestions:
The above effects could be 'improved' by redeploying the application ;)
Recently stumbled upon this:
Read http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5072161 and linked issues for an in-depth-discussion.
If Max heap size is X. Y1....Yn no of instances So,total memory= number of instances X Bytes per instance.If X1......Xn is bytes per instances.Then total memory(M)=Y1 * X1+.....+Yn *Xn. So,if M>X it exceeds heap space . following can be the problems in code 1.Use of more instances variable then local one. 2.Creating instances every time instead of pooling object. 3.Not Creating the object on demand. 4.Making the object reference null after the completion of operation.Again ,recreating when it is demanded in program.
There are many answers on how to create a memory leak in Java, but please note the point asked during the interview.
"how to create a memory leak with Java?" is an open-ended question, whose purpose is to evaluate the degree of experience a developer has.
If I ask you "Do you have experience troubleshooting memory leaks in Java?", your answer would be a simple "Yes". I would have then to follow up with "Could you give me examples where you hat to troubleshoot memory leaks?", to which you would give me one or two examples.
However, when the interviewer asks "how to create a memory leak with Java?" the expected answer should follow alongs these lines:
When the developer fails to follow this line of thought I try to guide him/her asking "Could you give me an example of how could Java leak memory?", followed by "Did you ever have to fix any memory leak in Java?"
Note that I am not asking for an example on how to leak memory in Java. That would be silly. Who would be interested in a developer who can effectively write code that leaks memory?
String.substring method in java 1.6 create a memory leak. This blog post explains it.
http://javarevisited.blogspot.com/2011/10/how-substring-in-java-works.html
One possibility is to create a wrapper for an ArrayList that only provides one method: one that adds things to the ArrayList. Make the ArrayList itself private. Now, construct one of these wrapper objects in global scope (as a static object in a class) and qualify it with the final keyword (e.g. public static final ArrayListWrapper wrapperClass = new ArrayListWrapper()
). So now the reference cannot be altered. That is, wrapperClass = null
won't work and can't be used to free the memory. But there's also no way to do anything with wrapperClass
other than add objects to it. Therefore, any objects you do add to wrapperClass
are impossible to recycle.
A memory leak in java is not your typical C/C++ memory leak.
To understand how the JVM works, read the Understanding Memory Management.
Basically, the important part is:
The Mark and Sweep Model
The JRockit JVM uses the mark and sweep garbage collection model for performing garbage collections of the whole heap. A mark and sweep garbage collection consists of two phases, the mark phase and the sweep phase.
During the mark phase all objects that are reachable from Java threads, native handles and other root sources are marked as alive, as well as the objects that are reachable from these objects and so forth. This process identifies and marks all objects that are still used, and the rest can be considered garbage.
During the sweep phase the heap is traversed to find the gaps between the live objects. These gaps are recorded in a free list and are made available for new object allocation.
The JRockit JVM uses two improved versions of the mark and sweep model. One is mostly concurrent mark and sweep and the other is parallel mark and sweep. You can also mix the two strategies, running for example mostly concurrent mark and parallel sweep.
So, to create a memory leak in Java; the easiest way to do that is to create a database connection, do some work, and simply not Close()
it; then generate a new database connection while staying in scope. This isn't hard to do in a loop for example. If you have a worker that pulls from a queue and pushes to a database you can easily create a memory leak by forgetting to Close()
connections or opening them when not necessary, and so forth.
Eventually, you'll consume the heap that has been allocated to the JVM by forgetting to Close()
the connection. This will result in the JVM garbage collecting like crazy; eventually resulting in java.lang.OutOfMemoryError: Java heap space
errors. It should be noted that the error may not mean there is a memory leak; it could just mean you don't have enough memory; databases like Cassandra and ElasticSearch for example can throw that error because they don't have enough heap space.
Its worth noting that this is true for all GC languages. Below, are some examples I've seen working as an SRE:
json.Unmarshal
and then passing the results by reference and keeping them open. Eventually, this resulted in the entire heap being consumed by accidental refs I kept open to decode json.In Java a "memory leak" is primarily just you using too much memory which is different than in C where you are no longer using the memory but forget to return (free) it. When an interviewer asks about Java memory leaks they are asking about JVM memory usage just appearing to keep going up and they determined that restarting the JVM on a regular basis is the best fix. (unless the interviewer is extremely technically savvy)
So answer this question as if they asked what makes JVM memory usage grow over time. Good answers would be storing too much data in a HttpSessions with overly long timeout or a poorly implemented in-memory cache (Singleton) that never flushes old entries. Another potential answer is having lots of JSPs or dynamically generated classes. Classes are loaded into an area of memory called PermGen that is usually small and most JVMs don't implement class unloading.
Swing has it very easy with dialogs. Create a JDialog, show it, the user closes it, leak!
You have to call dispose()
or configure setDefaultCloseOperation(DISPOSE_ON_CLOSE)
If you don't use a compacting garbage collector, you can have some sort of a memory leak due to heap fragmentation.
Lapsed Listerners is a good example of memory leaks: Object is added as a Listener. All references to the object are nulled when the object is not needed anymore. However, forgetting to remove the object from the Listener list keeps the object alive and even responding to events, thereby wasting both memory and CPU. See http://www.drdobbs.com/jvm/java-qa/184404011
Carelessly Using a non-static inner Class inside a class who has its own life cycle.
In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.
Here is a common example to have memory leak in Android,which is not obvious though:
public class SampleActivity extends Activity {
private final Handler mLeakyHandler = new Handler() { //non-static inner class, holds the reference to the SampleActivity outter class
@Override
public void handleMessage(Message msg) {
// ...
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Post a message and delay its execution for a long time.
mLeakyHandler.postDelayed(new Runnable() {//here, the anonymous inner class holds the reference to the SampleActivity class too
@Override
public void run() {
//....
}
}, SOME_TOME_TIME);
// Go back to the previous Activity.
finish();
}}
This will prevent the activity context from being garbage collected.
mLeakyHandler
static prevent it from leaking memory? And are there any (other) ways to prevent mLeakyHandler
from leaking the activity? Also, how would you go about solving the same problem for the anonymous Runnable
inner class?
– ban-geoengineering
Jun 24 '15 at 13:08
import sun.misc.Unsafe;
import java.lang.reflect.Field;
class Main {
public static void main(String args[]) {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
((Unsafe) f.get(null)).allocateMemory(2000000000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
There are many good examples of memory leaks in Java, and I will mention two of them in this answer.
Example 1:
Here is a good example of a memory leak from the book Effective Java, Third Edition (item 7: Eliminate obsolete object references):
// Can you spot the "memory leak"?
public class Stack {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private Object[] elements;
private int size = 0;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0) throw new EmptyStackException();
return elements[--size];
}
/*** Ensure space for at least one more element, roughly* doubling the capacity each time the array needs to grow.*/
private void ensureCapacity() {
if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
This is the paragraph of the book that describe why this implementation will cause a memory leak:
If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is simply a reference that will never be dereferenced again. In this case, any references outside of the “active portion” of the element array are obsolete. The active portion consists of the elements whose index is less than size
Here is the solution of the book to tackle this memory leak:
The fix for this sort of problem is simple: null out references once they become obsolete. In the case of our Stack class, the reference to an item becomes obsolete as soon as it’s popped off the stack. The corrected version of the pop method looks like this:
public Object pop() {
if (size == 0) throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
But how can we prevent a memory leak from happening? This is a good caveat from the book:
Generally speaking, whenever a class manages its own memory, the programmer should be alert for memory leaks. Whenever an element is freed, any object references contained in the element should be nulled out.
Example 2:
The observer pattern also can cause a memory leak. You can read about this pattern in the following link: Observer pattern.
This is one implementation of Observer
pattern:
class EventSource {
public interface Observer {
void update(String event);
}
private final List<Observer> observers = new ArrayList<>();
private void notifyObservers(String event) {
observers.forEach(observer -> observer.update(event)); //alternative lambda expression: observers.forEach(Observer::update);
}
public void addObserver(Observer observer) {
observers.add(observer);
}
public void scanSystemIn() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
notifyObservers(line);
}
}
}
In this implementation, EventSource
, which is Observable in Observer
design pattern, can hold link to Obeserver
objects, but this link is never removed from the observers
field in EventSource
. So they will never be collected by the garbage collector. One solution to tackle this problem is providing another method to client for removing the aforementioned observers from observers
field when they don't need those observers any more:
public void removeObserver(Observer observer) {
observers.remove(observer);
}
a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released => wiki definition
It's kind of relatively context-based topic, you can just create one based on your taste as long as the unused references will never be used by clients but still stay alive.
The first example should be a custom stack without nulling the obsolete references in effective java item 6.
Of course there are many more as long as you want, but if we just take look at the java built-in classes, it could be some as
Let's check some super silly code to produce the leak.
public class MemoryLeak {
private static final int HUGE_SIZE = 10_000;
public static void main(String... args) {
letsLeakNow();
}
private static void letsLeakNow() {
Map<Integer, Object> leakMap = new HashMap<>();
for (int i = 0; i < HUGE_SIZE; ++i) {
leakMap.put(i * 2, getListWithRandomNumber());
}
}
private static List<Integer> getListWithRandomNumber() {
List<Integer> originalHugeIntList = new ArrayList<>();
for (int i = 0; i < HUGE_SIZE; ++i) {
originalHugeIntList.add(new Random().nextInt());
}
return originalHugeIntList.subList(0, 1);
}
}
Actually there is another trick we can cause memory leak using HashMap by taking advantage of its looking process. There are actually two types:
hashCode()
is always the same but equals()
are different;hashCode()
and equals()
always true;Why?
hashCode()
-> bucket => equals()
to locate the pair
I was about to mention substring()
first and then subList()
but it seems this issue is already fixed as its source presents in JDK 8.
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
A real time example of memory leak before JDK 1.7
suppose you read a file of 1000 lines of text and keep in String object
String fileText = 1000 characters from file
fileText = fileText.subString(900, fileText.length());
In above code I initially read 1000 char and then did substring to get only 100 last characters. Now fileText should only refer to 100 chars and all other characters should get garbage collected as I lost the reference but before JDK 1.7 substring function indirectly refer to original string of last 100 chars and prevents whole string from garbage collection and whole 1000 chars will be there in memory until you loose reference of substring.
you can create memory leak example like the above
One of the java memory leakings examples is MySQLs memory leaking bug resulting when ResultSets close method is forgotten to be called. For example:
while(true) {
ResultSet rs = database.select(query);
...
// going to next step of loop and leaving resultset without calling rs.close();
}
Create a JNI function containing just a while-true loop and call it with a large object from another thread. The GC doesn't like JNI very much and is going to keep the object in memory forever.
One of the easiest way to implement memory leak sample is to use static method.
For example
static List<int> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
list.add(i);
}
system.sleep();
In this case, jvm can't release the memory of list, cuz it's a static class and it always remains memory on heap.
From effective java book
.
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
return elements[--size];
}
/**
* Ensure space for at least one more element, roughly doubling the capacity
* each time the array needs to grow.
*/
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
Can you spot the memory leak? So where is the memory leak? If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is simply a reference that will never be dereferenced again. In this case, any references outside of the “active portion” of the element array are obsolete. The active portion consists of the elements whose index is less than size.
size
changes every time pop
is called, it is still possible to iterate over the complete array using its length
property. Therefore there are no obsolete references. I must say that it is usual that a collection releases ownership in a function such as pop
though, but this example will not create a memory leak which is the original question
– 0xDEADC0DE
Dec 27 '18 at 13:52
Here is a very simple Java program that will run out of space
public class OutOfMemory {
public static void main(String[] arg) {
List<Long> mem = new LinkedList<Long>();
while (true) {
mem.add(new Long(Long.MAX_VALUE));
}
}
}
There's no such thing as a memory leak in Java. Memory leak is a phrase borrowed from C et al. Java deals with memory allocation internally with the help of the GC. There's memory wastefulness (ie. leaving stranded objects), but not memory leak.
Just like this!
public static void main(String[] args) {
List<Object> objects = new ArrayList<>();
while(true) {
objects.add(new Object());
}
}