C
C
click_f2016-10-18 14:40:23
Java
click_f, 2016-10-18 14:40:23

How to free memory in java?

  • How to force free memory before variable goes out of scope?
  • What are the standard tools for this?

I would be grateful for any advice.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2016-10-18
@click_f

1. The most simple. var = null;If you also need to let the scavenger go - well, let it go, System.gc();
2. If you need the object not to be held - WeakReference. As soon as the object disappears, the weak reference is flipped to null. Sometimes it is necessary: ​​1) if child objects outlive their owners, and at the same time lose the owner - this is not fatal; 2) when we build some temporary list.
3. Do not give out a nameless object to the outside if it outlives the creator. Nameless objects have a reference to the creator. Issue a lambda: if the creator is not needed, there will be no link.
4. Similarly with inner classes - if it outlives the creator, make it static.
5. String.intern if you are working with a bunch of small identical strings. Well, or adjust your cache :)
6. Use object pools and other structures that reduce the load on the scavenger.
7. Breaking strings into small pieces, use the pattern doSomething(String data, int start, int length)without physically pulling out the substring. Use StringBuilder.

M
Mikhail Osher, 2016-10-18
@miraage

offheap, for example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question