Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Garbage Collector
Conociendo el manejo de memoria en el JVM
@SuperSerch
¿Qué ocurre en la memoria?
¿Qué ocurre en la memoria?
¿Qué ocurre en la memoria?
¿Qué ocurre en la memoria?
¿Qué ocurre en la memoria?
¿Qué ocurre en la memoria?
¿Qué ocurre en la memoria?
¿Qué ocurre en la memoria?
Retos al administrar la memoria
Velocidad de asignación ( velocidad de creación de objetos )
Seguimiento de objetos y valo...
JVMS: 2.5.3 Heap
The heap is created on virtual machine start-up. Heap storage for objects
is reclaimed by an automatic st...
JVMS: 2.5.3 Heap
The heap is created on virtual machine start-up. Heap storage for objects
is reclaimed by an automatic st...
Hipótesis Generacional
Hipótesis generacional debil
La mayoría de los objetos mueren jovenes
80% - 95% de los objetos en 1...
Memoria generacional
PermGen
(jdk8-nativo)
Old Gen
Young Gen
Young Gen
Young Gen
Eden
Survivor Spaces
From To⇄
Allocation
Allocation
Allocation
From To
Allocation
From To
Allocation
To From
Allocation
To From
Allocation
From To
Promotion
From To
No hay espacio suficiente
Promotion
From To
Old Generation
Colectores en Oracle JVM
Serial Garbage Collector
Parallel Garbage Collector
Concurrent Mark-Sweep Garbage Collector
G1 Ga...
Serial Garbage Collector
Compactación por deslizamiento, con
una pausa stop-the-world
Util para ambientes con 1 virtual
co...
Parallel Garbage Collector
Compactación por deslizamiento, con
una pausa stop-the-world
utiliza todos los núcleos disponib...
Concurrent Mark-Sweep Garbage
Collector
Diseñado para tener un tiempo de
respuesta consistente
Hace gran parte del trabajo...
G1 Garbage Collector
(Garbage 1srt)
G1 Garbage Collector
(Garbage 1srt)
G1 Garbage Collector
(Garbage 1srt)
G1 Garbage Collector
(Garbage 1srt)
G1 Garbage Collector
(Garbage 1srt)
G1 Garbage Collector
(Garbage 1srt)
Paralelo, concurrente e incremental
Pausas cortas y alto throughput
Divide el heap en ...
¿Cuándo un Objeto es basura?
Un objeto es elegible para ser colectado cuando desde
ningún GC Root de la jvm se puede alcan...
GC Roots de la JVM
Variables locales (stack)
Threads activos
Variables estáticas
Referencias JNI
GC Roots
Objetos
Alcanzab...
Tipos de Referencias
Fuerte
Suave ( SoftReference )
Debil ( WeakReference )
Fantasma ( PhantomReference )
Ejemplo WeakReference
WagTask.run Kennel.dogCache
WeakReference
Dog
Tail
Stack Heap
Ejemplo WeakReference
WagTask.run Kennel.dogCache
WeakReference
Dog
Tail
Stack Heap
El Thread se muere
Ejemplo WeakReference
Kennel.dogCache
WeakReference
Dog
Tail
Heap
Durante un GC
Ejemplo WeakReference
Kennel.dogCache
WeakReference
null
Heap
Después del GC
Problemas comunes
(y como evitarlos)
Memory leak
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size== 0)
thr...
Memory leak
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size== 0)
thr...
Memory leak
public Object pop() {
if (size== 0)
throw new EmptyStackException();
Object result = elements[--size];
element...
Clases miembro
public class MySet<E> extends AbstractSet<E> {
... // otros métodos de la clase
public Iterator<E> iterator...
Clases miembro
public class MySet<E> extends AbstractSet<E> {
... // otros métodos de la clase
public Iterator<E> iterator...
Clases miembro
public class MySet<E> extends AbstractSet<E> {
... // otros métodos de la clase
public Iterator<E> iterator...
Otro Memory Leak
static Vector vector = new Vector():
...
for (int n = count-1; n > 0; n--) {
vector.removeElementAt(n);
}...
Otro Memory Leak
static Vector vector = new Vector():
...
for (int n = count-1; n > 0; n--) {
vector.removeElementAt(n);
}...
Otro Memory Leak
static Vector vector = new Vector():
...
vector.clear();
...
Nonlocal Instance Field
public class Storer {
private Map<Integer, String> hm =
new HashMap<>();
private void doSomething(...
Nonlocal Instance Field
public class Storer {
private Map<Integer, String> hm =
new HashMap<>();
private void doSomething(...
Referencias olvidadas
Reader reader = new Reader();
button.addActionListener(reader);
try {
reader.readSomething();
} catc...
Referencias olvidadas
Reader reader = new Reader();
button.addActionListener(reader);
try {
reader.readSomething();
button...
Referencias olvidadas
Reader reader = new Reader();
button.addActionListener(reader);
try {
reader.readSomething();
button...
Referencias olvidadas
Reader reader = new Reader();
button.addActionListener(reader);
try {
reader.readSomething();
} catc...
Referencias fuertes
class HashMetaData {
private Map<SSLSocket, InetAddress> m =
Collections.synchronizedMap( new HashMap<...
Referencias fuertes
class HashMetaData {
private Map<SSLSocket, InetAddress> m =
Collections.synchronizedMap( new WeakHash...
Referencias fuertes
class HashMetaData {
private Map<WeakReference<SSLSocket>, InetAddress>
m = Collections.synchronizedMa...
Referencias fuertes
public void storeTempConn(SSLSocket sock,
InetAddress ip) {
WeakReference<SSLSocket> wr;
while((wr = (...
Referencias fuertes
public void storeTempConn(SSLSocket sock,
InetAddress ip) {
SoftReference<SSLSocket> sr;
while((sr = (...
¿ Preguntas ?
Bibliografía
Efective Java Second Edition - Joshua Bloch
Java Platform Performance - Steve Wilson, Jeff Kesselman
Java Per...
Prochain SlideShare
Chargement dans…5
×

Garbage Collection en el JVM

23 559 vues

Publié le

¿Cómo funciona el Garbage collector? ¿Por que se sigue esta técnica para administrar la memoria en el JVM?¿Qué errores de código pueden afectar al GC?

Publié dans : Logiciels
  • How to get your ex back and save your relationship or marriage! contact: Unityspelltemple@gmail.com , Is certainly the best spell caster online, and his result is 100% guarantee. I'm so excited my boyfriend is back after he left me for another girl. After 4 years of relationship with my boyfriend, he broke up me and brought in another Girl, i did all i could to get him back but all proved abortive, I was really upset and i needed help, so i searched for help online and I came across a website that suggested that Dr Unity can help get ex back fast. So, I felt I should give him a try. I contacted him and he told me what to do and i did it then he did a (Love spell) for me. 28 hours later, my boyfriend really called me and told me that he miss me so much, So Amazing!! So that was how he came back that same day,with lots of love and joy,and he apologized for his mistake, and for the pain he caused me . Then from that day, Our relationship was now stronger than how it were before, All thanks to Dr Unity. he is so powerful and i decided to share my story on the internet that Dr.Unity real and powerful spell caster who i will always pray to live long to help his children in the time of trouble, if you are here and you need your Ex back or your husband moved to another woman, do not cry anymore, contact this powerful spell caster now. Here’s his contact: Email him at: Unityspelltemple@gmail.com , you can also call him or add him on Whats-app: +2348071622464 , you can also visit his website: https://urgentspell.blogspot.com.
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • Hello , Are you looking on how to buy driving license online without taking a test ? or How to buy a passport of any other country without a citizenship ? darkenet-Passport document dealer can help you out with all your issues. You can Buy toefl certificate. Get Graduation certificate without exam. Buy ielts certificate. Purchase new Good driving license online without taking a test. Buy Registered passport online. Order for Resident Permit. Get Working Permit in all countries. Get Social Security Number/Card. Buy Adoption Certificates. Buy Emancipation Document. Buy Birth Certificates. Buy Marriage Certificate Update your College Degrees. And Many More. We guarantee you a New Identity Package (Documents). All our documents are registered into the government data base. We produce documents principally in two formats, that’s Registered and Unregistred Formats. fOR MORE INFORMATION : EMAIL : jackhool111@yahoo.com WHATS-APP # +1 (9109863818)
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • CREDIT D'ARGENT SÉRIEUX ET RAPIDE EN FRANCE . Infos: ( mme.gabrielle.mr.dominique@gmail.com ) Je suis Mme.gabrielle / Mr.dominique. Je vous soumets une offre de prêt entre particuliers, afin de vous permettre de réaliser vos rêves sans soucis.J'écris mon texte sur ce site, afin de vous aider, c'est particuliers à obtenir un financement sérieux, rapide en transparence et traçabilité, mes conditions sont simple, pas protocole. Je fais en effets des prêts entre particuliers aux personnes pouvant respecter mon conditions. Alors si vous avez besoin prêt, crédit, veuillez me répondre pour que je puisse vous faire part de mon offre. Mon taux d'intérêt est de 1,2 % et il s'étend sur l'ensemble du prêt. Ma capacité d'emprunt est de 800.000 euros. Si vous désirez avoir plus d'information n’hésiter par .Mon adresse e-mail: mme.gabrielle.mr.dominique@gmail.com
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • *I knew I was a bad wife and mother for invariably pushing my husband to the point of hating me or seeing me with the kids. But I never let my bad attitude towards him let me feel like I am the worst woman out there. So, I fought inside of me to change the bad attitude and win back my husband’s heart for over six years but could not until he threatened me with a divorce and a restraining order, not only to keep me away from him, but away from our kids. *Because I can’t stand losing them, I threw away my pride and went spiritual on myself with the aid of doctor wakina (dr.wakinalovetemple@gmail.com), I was brought to light and made to understand that “it is of a great significant to make my husband happy and I must start by making myself happy”. *I boldly acknowledge the spiritual power doctor wakina carries that cured me from myself for four days and overturned my husband’s decisions. For over four months I have been having an entertaining moment with myself and family, a lot of things has changed both physical and spiritual. I say thank you Dr. Wakina for saving me from myself and restoring my marriage. *Love… Paris Tyne
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • Nice !! Download 100 % Free Ebooks, PPts, Study Notes, Novels, etc @ https://www.ThesisScientist.com
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici

Garbage Collection en el JVM

  1. 1. Garbage Collector Conociendo el manejo de memoria en el JVM @SuperSerch
  2. 2. ¿Qué ocurre en la memoria?
  3. 3. ¿Qué ocurre en la memoria?
  4. 4. ¿Qué ocurre en la memoria?
  5. 5. ¿Qué ocurre en la memoria?
  6. 6. ¿Qué ocurre en la memoria?
  7. 7. ¿Qué ocurre en la memoria?
  8. 8. ¿Qué ocurre en la memoria?
  9. 9. ¿Qué ocurre en la memoria?
  10. 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. 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. 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. 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
  14. 14. Memoria generacional PermGen (jdk8-nativo) Old Gen Young Gen
  15. 15. Young Gen
  16. 16. Young Gen Eden Survivor Spaces From To⇄
  17. 17. Allocation
  18. 18. Allocation
  19. 19. Allocation From To
  20. 20. Allocation From To
  21. 21. Allocation To From
  22. 22. Allocation To From
  23. 23. Allocation From To
  24. 24. Promotion From To No hay espacio suficiente
  25. 25. Promotion From To Old Generation
  26. 26. Colectores en Oracle JVM Serial Garbage Collector Parallel Garbage Collector Concurrent Mark-Sweep Garbage Collector G1 Garbage Collector (Garbage 1srt)
  27. 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. 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. 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
  30. 30. G1 Garbage Collector (Garbage 1srt)
  31. 31. G1 Garbage Collector (Garbage 1srt)
  32. 32. G1 Garbage Collector (Garbage 1srt)
  33. 33. G1 Garbage Collector (Garbage 1srt)
  34. 34. G1 Garbage Collector (Garbage 1srt)
  35. 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. 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. 37. GC Roots de la JVM Variables locales (stack) Threads activos Variables estáticas Referencias JNI GC Roots Objetos Alcanzables Objetos NO Alcanzables
  38. 38. Tipos de Referencias Fuerte Suave ( SoftReference ) Debil ( WeakReference ) Fantasma ( PhantomReference )
  39. 39. Ejemplo WeakReference WagTask.run Kennel.dogCache WeakReference Dog Tail Stack Heap
  40. 40. Ejemplo WeakReference WagTask.run Kennel.dogCache WeakReference Dog Tail Stack Heap El Thread se muere
  41. 41. Ejemplo WeakReference Kennel.dogCache WeakReference Dog Tail Heap Durante un GC
  42. 42. Ejemplo WeakReference Kennel.dogCache WeakReference null Heap Después del GC
  43. 43. Problemas comunes (y como evitarlos)
  44. 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. 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. 46. Memory leak public Object pop() { if (size== 0) throw new EmptyStackException(); Object result = elements[--size]; elements[size] = null; return result; }
  47. 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. 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. 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. 50. Otro Memory Leak static Vector vector = new Vector(): ... for (int n = count-1; n > 0; n--) { vector.removeElementAt(n); } ...
  51. 51. Otro Memory Leak static Vector vector = new Vector(): ... for (int n = count-1; n > 0; n--) { vector.removeElementAt(n); } ... >=
  52. 52. Otro Memory Leak static Vector vector = new Vector(): ... vector.clear(); ...
  53. 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. 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. 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. 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. 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. 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. 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. 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. 61. Referencias fuertes class HashMetaData { private Map<WeakReference<SSLSocket>, InetAddress> m = Collections.synchronizedMap( new HashMap<>()); ReferenceQueue queue = new ReferenceQueue(); ...
  62. 62. Referencias fuertes public 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); } ...
  63. 63. Referencias fuertes public 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); } ...
  64. 64. ¿ Preguntas ?
  65. 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

×