65

Click here to load reader

Garbage Collection en el JVM

Embed Size (px)

Citation preview

Page 1: Garbage Collection en el JVM

Garbage CollectorConociendo el manejo de memoria en el JVM

@SuperSerch

Page 2: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 3: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 4: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 5: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 6: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 7: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 8: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 9: Garbage Collection en el JVM

¿Qué ocurre en la memoria?

Page 10: Garbage Collection en el JVM

Retos al administrar la memoria

Velocidad de asignación ( velocidad de creación de objetos )

Seguimiento de objetos y valores vivos

Seguimiento del espacio vacío

Fragmentación de la memoria

Page 11: Garbage Collection en el JVM

JVMS: 2.5.3 HeapThe heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java Virtual Machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.

Page 12: Garbage Collection en el JVM

JVMS: 2.5.3 HeapThe heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java Virtual Machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.If a computation requires more heap than can be made available by the automatic storage management system, the Java Virtual Machine throws an OutOfMemoryError.

Page 13: Garbage Collection en el JVM

Hipótesis GeneracionalHipótesis generacional debil

La mayoría de los objetos mueren jovenes

80% - 95% de los objetos en 1MB mueren antes de que se llene el siguiente MB

95% de los objetos Java son de corta vida

Page 14: Garbage Collection en el JVM

Memoria generacional

Perm

Gen

(jdk8

- na

tivo)

Old Gen

Young Gen

Page 15: Garbage Collection en el JVM

Young Gen

Page 16: Garbage Collection en el JVM

Young GenEden

Survivor SpacesFrom To⇄

Page 17: Garbage Collection en el JVM

Allocation

Page 18: Garbage Collection en el JVM

Allocation

Page 19: Garbage Collection en el JVM

Allocation

From To

Page 20: Garbage Collection en el JVM

Allocation

From To

Page 21: Garbage Collection en el JVM

Allocation

To From

Page 22: Garbage Collection en el JVM

Allocation

To From

Page 23: Garbage Collection en el JVM

Allocation

From To

Page 24: Garbage Collection en el JVM

Promotion

From To

No hay espacio suficiente

Page 25: Garbage Collection en el JVM

Promotion

From To

Old Generation

Page 26: Garbage Collection en el JVM

Colectores en Oracle JVM

Serial Garbage Collector

Parallel Garbage Collector

Concurrent Mark-Sweep Garbage Collector

G1 Garbage Collector (Garbage 1srt)

Page 27: Garbage Collection en el JVM

Serial Garbage CollectorCompactación por deslizamiento, con una pausa stop-the-world

Util para ambientes con 1 virtual core o en ambientes donde varias JVMs comparten el mismo hardware

Para Heaps en el orden de MBs

Pausas posiblemente largasApp App AppGC GC

Page 28: Garbage Collection en el JVM

Parallel Garbage Collector

Compactación por deslizamiento, con una pausa stop-the-world

utiliza todos los núcleos disponibles

Alto throughput

Para Heaps en el orden de GBs App App AppGC GC

Page 29: Garbage Collection en el JVM

Concurrent Mark-Sweep Garbage Collector

Diseñado para tener un tiempo de respuesta consistente

Hace gran parte del trabajo de limpiar Old Gen concurrente a la aplicación

Si se acaba el espacio antes de que CMS pueda limpiar, ocurre una SWP y limpia en paralelo

Require un Heap mas grande

App App AppIM RM

SW

Page 30: Garbage Collection en el JVM

G1 Garbage Collector (Garbage 1srt)

Page 31: Garbage Collection en el JVM

G1 Garbage Collector (Garbage 1srt)

Page 32: Garbage Collection en el JVM

G1 Garbage Collector (Garbage 1srt)

Page 33: Garbage Collection en el JVM

G1 Garbage Collector (Garbage 1srt)

Page 34: Garbage Collection en el JVM

G1 Garbage Collector (Garbage 1srt)

Page 35: Garbage Collection en el JVM

G1 Garbage Collector (Garbage 1srt)

Paralelo, concurrente e incremental

Pausas cortas y alto throughput

Divide el heap en regiones

Cada región puede cambiar de rol según se requiera al momento

Remplazo a largo tiempo del CMS, en JDK9 es el GC por defecto

App App AppGC GC

Page 36: Garbage Collection en el JVM

¿Cuándo un Objeto es basura?

Un objeto es elegible para ser colectado cuando desde ningún GC Root de la jvm se puede alcanzar con una referencia fuerte al objeto

Referencia fuerte (Variable en alcance)

GC Root de la jvm

Page 37: Garbage Collection en el JVM

GC Roots de la JVM

Variables locales (stack)

Threads activos

Variables estáticas

Referencias JNIGC Roots

Objetos Alcanzables

Objetos NO Alcanzables

Page 38: Garbage Collection en el JVM

Tipos de Referencias

Fuerte

Suave ( SoftReference )

Debil ( WeakReference )

Fantasma ( PhantomReference )

Page 39: Garbage Collection en el JVM

Ejemplo WeakReferenceWagTask.run Kennel.dogCache

WeakReference

Dog

Tail

Stack Heap

Page 40: Garbage Collection en el JVM

Ejemplo WeakReferenceWagTask.run Kennel.dogCache

WeakReference

Dog

Tail

Stack Heap

El Thread se muere

Page 41: Garbage Collection en el JVM

Ejemplo WeakReferenceKennel.dogCache

WeakReference

Dog

Tail

Heap

Durante un GC

Page 42: Garbage Collection en el JVM

Ejemplo WeakReferenceKennel.dogCache

WeakReference

null

Heap

Después del GC

Page 43: Garbage Collection en el JVM

Problemas comunes (y como evitarlos)

Page 44: Garbage Collection en el JVM

Memory leakpublic void push(Object e) { ensureCapacity(); elements[size++] = e; }

public Object pop() { if (size== 0) throw new EmptyStackException(); return elements[--size]; }

Page 45: Garbage Collection en el JVM

Memory leakpublic void push(Object e) { ensureCapacity(); elements[size++] = e; }

public Object pop() { if (size== 0) throw new EmptyStackException(); return elements[--size]; }

Page 46: Garbage Collection en el JVM

Memory leak

public Object pop() { if (size== 0) throw new EmptyStackException(); Object result = elements[--size]; elements[size] = null; return result; }

Page 47: Garbage Collection en el JVM

Clases miembropublic class MySet<E> extends AbstractSet<E> { ... // otros métodos de la clase public Iterator<E> iterator() { return new MyIterator(); }

private class MyIterator implements Iterator<E> { ... } }

Page 48: Garbage Collection en el JVM

Clases miembropublic class MySet<E> extends AbstractSet<E> { ... // otros métodos de la clase public Iterator<E> iterator() { return new MyIterator(); }

private class MyIterator implements Iterator<E> { ... } }

Page 49: Garbage Collection en el JVM

Clases miembropublic class MySet<E> extends AbstractSet<E> { ... // otros métodos de la clase public Iterator<E> iterator() { return new MyIterator(); }

private class MyIterator implements Iterator<E> { ... } }

static

Page 50: Garbage Collection en el JVM

Otro Memory Leak static Vector vector = new Vector(): ...

for (int n = count-1; n > 0; n--) { vector.removeElementAt(n); } ...

Page 51: Garbage Collection en el JVM

Otro Memory Leak static Vector vector = new Vector(): ...

for (int n = count-1; n > 0; n--) { vector.removeElementAt(n); } ...

>=

Page 52: Garbage Collection en el JVM

Otro Memory Leak

static Vector vector = new Vector(): ...

vector.clear(); ...

Page 53: Garbage Collection en el JVM

Nonlocal Instance Fieldpublic class Storer { private Map<Integer, String> hm = new HashMap<>();

private void doSomething() { // hm sólo se usa aquí hm.put(1, "java"); // … } }

Page 54: Garbage Collection en el JVM

Nonlocal Instance Fieldpublic class Storer { private Map<Integer, String> hm = new HashMap<>();

private void doSomething() { // hm sólo se usa aquí hm.put(1, "java"); // … } }

Page 55: Garbage Collection en el JVM

Referencias olvidadasReader reader = new Reader(); button.addActionListener(reader); try { reader.readSomething(); } catch (IOException e) { // se maneja la excepción } // Ya no se usa reader

Page 56: Garbage Collection en el JVM

Referencias olvidadasReader reader = new Reader(); button.addActionListener(reader); try { reader.readSomething(); button.removeActionListener(reader); } catch (IOException e) { // se maneja la excepción } // Ya no se usa reader

Page 57: Garbage Collection en el JVM

Referencias olvidadasReader reader = new Reader(); button.addActionListener(reader); try { reader.readSomething(); button.removeActionListener(reader); } catch (IOException e) { // se maneja la excepción } // Ya no se usa reader

Page 58: Garbage Collection en el JVM

Referencias olvidadasReader reader = new Reader(); button.addActionListener(reader); try { reader.readSomething(); } catch (IOException e) { // se maneja la excepción } finally { button.removeActionListener(reader); } // Ya no se usa reader

Page 59: Garbage Collection en el JVM

Referencias fuertesclass HashMetaData { private Map<SSLSocket, InetAddress> m = Collections.synchronizedMap( new HashMap<>());

public void storeTempConn(SSLSocket sock, InetAddress ip) { m.put(sock, ip); } pubic void removeTempConn(SSLSocket sock) { m.remove(sock); } }

Page 60: Garbage Collection en el JVM

Referencias fuertesclass HashMetaData { private Map<SSLSocket, InetAddress> m = Collections.synchronizedMap( new WeakHashMap<>());

public void storeTempConn(SSLSocket sock, InetAddress ip) { m.put(sock, ip); } pubic void removeTempConn(SSLSocket sock) { m.remove(sock); } }

Page 61: Garbage Collection en el JVM

Referencias fuertes

class HashMetaData { private Map<WeakReference<SSLSocket>, InetAddress> m = Collections.synchronizedMap( new HashMap<>()); ReferenceQueue queue = new ReferenceQueue();

...

Page 62: Garbage Collection en el JVM

Referencias fuertespublic void storeTempConn(SSLSocket sock, InetAddress ip) { WeakReference<SSLSocket> wr; while((wr = (WeakReference) queue.poll) != null){ //... m.remove(wr); } wr = new WeakReference<>(sock, queue); m.put(wr, ip); } ...

Page 63: Garbage Collection en el JVM

Referencias fuertespublic void storeTempConn(SSLSocket sock, InetAddress ip) { SoftReference<SSLSocket> sr; while((sr = (SoftReference) queue.poll) != null){ //... m.remove(sr); } sr = new SoftReference<>(sock, queue); m.put(sr, ip); } ...

Page 64: Garbage Collection en el JVM

¿ Preguntas ?

Page 65: Garbage Collection en el JVM

BibliografíaEfective Java Second Edition - Joshua Bloch

Java Platform Performance - Steve Wilson, Jeff Kesselman

Java Performance - Charlie Hunt, Binu John

The CERT Oracle Secure Coding Standard For Java - Fred Long, Dhruv Mohindra, Robert C. Seacord,

Dean F Sutherland, David Svoboda