10. 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
11. JVMS: 2.5.3 Heap
The 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.
12. JVMS: 2.5.3 Heap
The 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.
13. Hipótesis Generacional
Hipó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
26. Colectores en Oracle JVM
Serial Garbage Collector
Parallel Garbage Collector
Concurrent Mark-Sweep Garbage Collector
G1 Garbage Collector (Garbage 1srt)
27. Serial Garbage Collector
Compactació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 largas
App App AppGC GC
28. 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
29. 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
35. 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
36. ¿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
37. GC Roots de la JVM
Variables locales (stack)
Threads activos
Variables estáticas
Referencias JNI
GC Roots
Objetos
Alcanzables
Objetos NO
Alcanzables
44. Memory leak
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size== 0)
throw new EmptyStackException();
return elements[--size];
}
45. Memory leak
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size== 0)
throw new EmptyStackException();
return elements[--size];
}
46. Memory leak
public Object pop() {
if (size== 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null;
return result;
}
47. Clases miembro
public 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> {
...
}
}
48. Clases miembro
public 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> {
...
}
}
49. Clases miembro
public 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
50. Otro Memory Leak
static Vector vector = new Vector():
...
for (int n = count-1; n > 0; n--) {
vector.removeElementAt(n);
}
...
51. Otro Memory Leak
static Vector vector = new Vector():
...
for (int n = count-1; n > 0; n--) {
vector.removeElementAt(n);
}
...
>=
53. Nonlocal Instance Field
public class Storer {
private Map<Integer, String> hm =
new HashMap<>();
private void doSomething() {
// hm sólo se usa aquí
hm.put(1, "java");
// …
}
}
54. Nonlocal Instance Field
public class Storer {
private Map<Integer, String> hm =
new HashMap<>();
private void doSomething() {
// hm sólo se usa aquí
hm.put(1, "java");
// …
}
}
55. Referencias olvidadas
Reader reader = new Reader();
button.addActionListener(reader);
try {
reader.readSomething();
} catch (IOException e) {
// se maneja la excepción
}
// Ya no se usa reader
56. Referencias olvidadas
Reader 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
57. Referencias olvidadas
Reader 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
58. Referencias olvidadas
Reader 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
59. Referencias fuertes
class 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);
}
}
60. Referencias fuertes
class 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);
}
}
61. Referencias fuertes
class HashMetaData {
private Map<WeakReference<SSLSocket>, InetAddress>
m = Collections.synchronizedMap( new HashMap<>());
ReferenceQueue queue = new ReferenceQueue();
...
65. Bibliografía
Efective 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