1. Въведение
Едно от основните предимства на Java е автоматизираното управление на паметта с помощта на вградения Garbage Collector (или GC за кратко). GC имплицитно се грижи за разпределянето и освобождаването на паметта и по този начин е в състояние да се справи с повечето проблеми с изтичането на памет.
Въпреки че GC ефективно обработва добра част от паметта, това не гарантира надеждно решение за изтичане на памет. GC е доста умен, но не и безупречен. Течовете на паметта все още могат да се промъкнат дори в приложения на съвестен разработчик.
Все още може да има ситуации, при които приложението генерира значителен брой излишни обекти, като по този начин изчерпва важни ресурси на паметта, понякога води до отказ на цялото приложение.
Изтичането на памет е истински проблем в Java. В този урок ще видим какви са потенциалните причини за изтичане на памет, как да ги разпознаем по време на изпълнение и как да се справим с тях в нашето приложение .
2. Какво е изтичане на памет
Изтичане на памет е ситуация, когато в купчината има обекти, които вече не се използват, но събирачът на боклук не е в състояние да ги премахне от паметта и по този начин те ненужно се поддържат.
Изтичането на памет е лошо, защото блокира ресурсите на паметта и влошава производителността на системата с течение на времето . И ако не се реши, приложението в крайна сметка ще изчерпи ресурсите си, като накрая ще завърши с фатален java.lang.OutOfMemoryError .
Има два различни типа обекти, които се намират в паметта на купчината - препратени и без препратки. Препратени обекти са тези, които все още имат активни препратки в приложението, докато обектите без препратки нямат активни препратки.
Събирачът на боклук периодично премахва обекти без препратки, но никога не събира обектите, към които все още има препратки. Тук могат да възникнат изтичания на памет:

Симптоми на изтичане на памет
- Силно влошаване на производителността, когато приложението работи непрекъснато за дълго време
- OutOfMemoryError грешка в купчината в приложението
- Спонтанни и странни сривове на приложението
- Приложението понякога изчерпва обектите за свързване
Нека разгледаме по-отблизо някои от тези сценарии и как да се справим с тях.
3. Видове изтичане на памет в Java
Във всяко приложение може да възникне изтичане на памет по много причини. В този раздел ще обсъдим най-често срещаните.
3.1. Изтичане на памет през статични полета
Първият сценарий, който може да причини потенциално изтичане на памет, е интензивното използване на статични променливи.
В Java статичните полета имат живот, който обикновено съвпада с целия живот на работещото приложение (освен ако ClassLoader не отговаря на условията за събиране на боклука).
Нека създадем проста Java програма, която попълва статичен списък:
public class StaticTest { public static List list = new ArrayList(); public void populateList() { for (int i = 0; i < 10000000; i++) { list.add(Math.random()); } Log.info("Debug Point 2"); } public static void main(String[] args) { Log.info("Debug Point 1"); new StaticTest().populateList(); Log.info("Debug Point 3"); } }
Сега, ако анализираме Heap паметта по време на изпълнението на тази програма, ще видим, че между точките за отстраняване на грешки 1 и 2, както се очакваше, паметта на купчината се увеличи.
Но когато оставим метода populateList () в точка за отстраняване на грешки 3, паметта на купчина все още не е събрана боклук, както можем да видим в този отговор на VisualVM:

Въпреки това, в горната програма, в ред номер 2, ако просто изпуснем ключовата дума static , тогава това ще доведе до драстична промяна в използването на паметта, този Visual VM отговор показва:

Първата част до точката за отстраняване на грешки е почти същата като тази, която получихме в случай на статично. Но този път, след като напуснем метода populateList () , цялата памет на списъка е събран боклук, защото нямаме никаква препратка към него .
Следователно трябва да обърнем много голямо внимание на използването на статични променливи. Ако колекции или големи обекти са декларирани като статични , те остават в паметта през целия живот на приложението, като по този начин блокират жизненоважната памет, която иначе би могла да се използва другаде.
Как да го предотвратим?
- Намалете до минимум използването на статични променливи
- Когато използвате единични, разчитайте на изпълнение, което лениво зарежда обекта, вместо да се зарежда с нетърпение
3.2. Чрез незатворени ресурси
Винаги, когато правим нова връзка или отваряме поток, JVM разпределя памет за тези ресурси. Няколко примера включват връзки с база данни, входни потоци и обекти на сесия.
Забравянето да затвори тези ресурси може да блокира паметта, като по този начин ги държи извън обсега на GC. Това може дори да се случи в случай на изключение, което пречи на изпълнението на програмата да достигне изявлението, което обработва кода, за да затвори тези ресурси.
И в двата случая отворената връзка, останала от ресурси, консумира памет и ако не се справим с тях, те могат да влошат производителността и дори да доведат до OutOfMemoryError .
Как да го предотвратим?
- Винаги използвайте block накрая, за да затворите ресурси
- Кодът (дори в блока окончателно ), който затваря ресурсите, не би трябвало да има изключения
- Когато използваме Java 7+, можем да използваме блока try -with-resources
3.3. Improper equals() and hashCode() Implementations
When defining new classes, a very common oversight is not writing proper overridden methods for equals() and hashCode() methods.
HashSet and HashMap use these methods in many operations, and if they're not overridden correctly, then they can become a source for potential memory leak problems.
Let's take an example of a trivial Person class and use it as a key in a HashMap:
public class Person { public String name; public Person(String name) { this.name = name; } }
Now we'll insert duplicate Person objects into a Map that uses this key.
Remember that a Map cannot contain duplicate keys:
@Test public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() { Map map = new HashMap(); for(int i=0; i<100; i++) { map.put(new Person("jon"), 1); } Assert.assertFalse(map.size() == 1); }
Here we're using Person as a key. Since Map doesn't allow duplicate keys, the numerous duplicate Person objects that we've inserted as a key shouldn't increase the memory.
But since we haven't defined proper equals() method, the duplicate objects pile up and increase the memory, that's why we see more than one object in the memory. The Heap Memory in VisualVM for this looks like:

However, if we had overridden the equals() and hashCode() methods properly, then there would only exist one Person object in this Map.
Let's take a look at proper implementations of equals() and hashCode() for our Person class:
public class Person { public String name; public Person(String name) { this.name = name; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Person)) { return false; } Person person = (Person) o; return person.name.equals(name); } @Override public int hashCode() { int result = 17; result = 31 * result + name.hashCode(); return result; } }
And in this case, the following assertions would be true:
@Test public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() { Map map = new HashMap(); for(int i=0; i<2; i++) { map.put(new Person("jon"), 1); } Assert.assertTrue(map.size() == 1); }
After properly overriding equals() and hashCode(), the Heap Memory for the same program looks like:

Another example is of using an ORM tool like Hibernate, which uses equals() and hashCode() methods to analyze the objects and saves them in the cache.
The chances of memory leak are quite high if these methods are not overridden because Hibernate then wouldn't be able to compare objects and would fill its cache with duplicate objects.
How to Prevent It?
- As a rule of thumb, when defining new entities, always override equals() and hashCode() methods
- It's not just enough to override, but these methods must be overridden in an optimal way as well
For more information, visit our tutorials Generate equals() and hashCode() with Eclipse and Guide to hashCode() in Java.
3.4. Inner Classes That Reference Outer Classes
This happens in the case of non-static inner classes (anonymous classes). For initialization, these inner classes always require an instance of the enclosing class.
Every non-static Inner Class has, by default, an implicit reference to its containing class. If we use this inner class' object in our application, then even after our containing class' object goes out of scope, it will not be garbage collected.
Consider a class that holds the reference to lots of bulky objects and has a non-static inner class. Now when we create an object of just the inner class, the memory model looks like:

However, if we just declare the inner class as static, then the same memory model looks like this:

This happens because the inner class object implicitly holds a reference to the outer class object, thereby making it an invalid candidate for garbage collection. The same happens in the case of anonymous classes.
How to Prevent It?
- If the inner class doesn't need access to the containing class members, consider turning it into a static class
3.5. Through finalize() Methods
Use of finalizers is yet another source of potential memory leak issues. Whenever a class' finalize() method is overridden, then objects of that class aren't instantly garbage collected. Instead, the GC queues them for finalization, which occurs at a later point in time.
Additionally, if the code written in finalize() method is not optimal and if the finalizer queue cannot keep up with the Java garbage collector, then sooner or later, our application is destined to meet an OutOfMemoryError.
To demonstrate this, let's consider that we have a class for which we have overridden the finalize() method and that the method takes a little bit of time to execute. When a large number of objects of this class gets garbage collected, then in VisualVM, it looks like:

However, if we just remove the overridden finalize() method, then the same program gives the following response:

How to Prevent It?
- We should always avoid finalizers
For more detail about finalize(), read section 3 (Avoiding Finalizers) in our Guide to the finalize Method in Java.
3.6. Interned Strings
The Java String pool had gone through a major change in Java 7 when it was transferred from PermGen to HeapSpace. But for applications operating on version 6 and below, we should be more attentive when working with large Strings.
If we read a huge massive String object, and call intern() on that object, then it goes to the string pool, which is located in PermGen (permanent memory) and will stay there as long as our application runs. This blocks the memory and creates a major memory leak in our application.
The PermGen for this case in JVM 1.6 looks like this in VisualVM:

In contrast to this, in a method, if we just read a string from a file and do not intern it, then the PermGen looks like:

How to Prevent It?
- The simplest way to resolve this issue is by upgrading to latest Java version as String pool is moved to HeapSpace from Java version 7 onwards
- If working on large Strings, increase the size of the PermGen space to avoid any potential OutOfMemoryErrors:
-XX:MaxPermSize=512m
3.7. Using ThreadLocals
ThreadLocal (discussed in detail in Introduction to ThreadLocal in Java tutorial) is a construct that gives us the ability to isolate state to a particular thread and thus allows us to achieve thread safety.
When using this construct, each thread will hold an implicit reference to its copy of a ThreadLocal variable and will maintain its own copy, instead of sharing the resource across multiple threads, as long as the thread is alive.
Despite its advantages, the use of ThreadLocal variables is controversial, as they are infamous for introducing memory leaks if not used properly. Joshua Bloch once commented on thread local usage:
“Sloppy use of thread pools in combination with sloppy use of thread locals can cause unintended object retention, as has been noted in many places. But placing the blame on thread locals is unwarranted.”
Memory leaks with ThreadLocals
ThreadLocals are supposed to be garbage collected once the holding thread is no longer alive. But the problem arises when ThreadLocals are used along with modern application servers.
Modern application servers use a pool of threads to process requests instead of creating new ones (for example the Executor in case of Apache Tomcat). Moreover, they also use a separate classloader.
Since Thread Pools in application servers work on the concept of thread reuse, they are never garbage collected — instead, they're reused to serve another request.
Now, if any class creates a ThreadLocal variable but doesn't explicitly remove it, then a copy of that object will remain with the worker Thread even after the web application is stopped, thus preventing the object from being garbage collected.
How to Prevent It?
- It's a good practice to clean-up ThreadLocals when they're no longer used — ThreadLocals provide the remove() method, which removes the current thread's value for this variable
- Do not use ThreadLocal.set(null) to clear the value — it doesn't actually clear the value but will instead look up the Map associated with the current thread and set the key-value pair as the current thread and null respectively
- It's even better to consider ThreadLocal as a resource that needs to be closed in a finally block just to make sure that it is always closed, even in the case of an exception:
try { threadLocal.set(System.nanoTime()); //... further processing } finally { threadLocal.remove(); }
4. Other Strategies for Dealing With Memory Leaks
Although there is no one-size-fits-all solution when dealing with memory leaks, there are some ways by which we can minimize these leaks.
4.1. Enable Profiling
Java profilers are tools that monitor and diagnose the memory leaks through the application. They analyze what's going on internally in our application — for example, how memory is allocated.
Using profilers, we can compare different approaches and find areas where we can optimally use our resources.
We have used Java VisualVM throughout section 3 of this tutorial. Please check out our Guide to Java Profilers to learn about different types of profilers, like Mission Control, JProfiler, YourKit, Java VisualVM, and the Netbeans Profiler.
4.2. Verbose Garbage Collection
By enabling verbose garbage collection, we're tracking detailed trace of the GC. To enable this, we need to add the following to our JVM configuration:
-verbose:gc
By adding this parameter, we can see the details of what's happening inside GC:

4.3. Use Reference Objects to Avoid Memory Leaks
We can also resort to reference objects in Java that comes in-built with java.lang.ref package to deal with memory leaks. Using java.lang.ref package, instead of directly referencing objects, we use special references to objects that allow them to be easily garbage collected.
Reference queues are designed for making us aware of actions performed by the Garbage Collector. For more information, read Soft References in Java Baeldung tutorial, specifically section 4.
4.4. Eclipse Memory Leak Warnings
For projects on JDK 1.5 and above, Eclipse shows warnings and errors whenever it encounters obvious cases of memory leaks. So when developing in Eclipse, we can regularly visit the “Problems” tab and be more vigilant about memory leak warnings (if any):

4.5. Benchmarking
We can measure and analyze the Java code's performance by executing benchmarks. This way, we can compare the performance of alternative approaches to do the same task. This can help us choose a better approach and may help us to conserve memory.
For more information about benchmarking, please head over to our Microbenchmarking with Java tutorial.
4.6. Code Reviews
Finally, we always have the classic, old-school way of doing a simple code walk-through.
In some cases, even this trivial looking method can help in eliminating some common memory leak problems.
5. Conclusion
In layman's terms, we can think of memory leak as a disease that degrades our application's performance by blocking vital memory resources. And like all other diseases, if not cured, it can result in fatal application crashes over time.
Течовете на паметта са трудни за решаване и намирането им изисква сложно майсторство и командване над езика Java. Докато се справяме с течовете на памет, няма универсално решение, тъй като течовете могат да възникнат в широк спектър от различни събития.
Ако обаче прибягваме до най-добрите практики и редовно извършваме строги разходки и профилиране на кода, тогава можем да сведем до минимум риска от изтичане на памет в нашето приложение.
Както винаги, кодовите фрагменти, използвани за генериране на отговорите на VisualVM, изобразени в този урок, са налични в GitHub.