Garbage Collection en el JVM

14.798 visualizações

Publicada em

¿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?

Publicada em: Software
4 comentários
91 gostaram
Estatísticas
Notas
  • our neighbor's mom gets 69 an hour at home and she has been laid off for nine months but last month her revenue was 14117 working on the internet for a few hours each week, look at this page... >>>-------- www.profitreview1.com
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui
  • Dear Sir/Madam I ask for your permission to contact you. I would like to discuss an investment and partnership with you. I expect your response so I can send the details. Thank you FJ Fin-Investment fjfininvestment@gmail.com
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui
  • Do you use a paypal account... in case if you have you can make an additional 2000 week after week in your profit just working on the laptop for a couple of hours per day,see this link­ᴵᴵᴵᴵᴵᴵᴵᴵᴵᴵw­w­w­.­8­8­.­j­o­b­s­3­4­.­c­o­m­ᴵᴵᴵᴵᴵᴵᴵᴵᴵᴵ
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui
  • SUPER POWER WONDER RING call now ZUMA ZUK +2349055637784 This is the oldest, mystique and the most powerful magic ring. This power organized by the great powerful magicians (460-800B.C) and greatly improved by the Pharos in Egypt. This SUPER POWER WONDER RING is harmless in any way to the devotee. The results of this ring are so great that this magic has now become well established. This power ring has got the powers of the angels of the seven planets. Now with this ring you will be the most powerful person in this whole world. This ring will effect your stars and will change you, give you success in love, business, make you look very attractive, protect you in your journey, it will prevent you from being fooled from other people, great miracles will come in your life, it will give you good luck and increase your personality, At the same time you will be the richest person in this world. You will dominate other peoples mind; change your bad luck into good luck. With this wonder ring you will even feel a powerful force protecting all around you from evil powers, demons, witch craft, black magic etc and even water and fire will not be able to harm you. All your enemies will become dumb and dare not talk bad about you. You will be the main source of attraction in every field.. And so this powerful ring can do great wonders, some of the few examples that this wonder ring can do is: it will give you promotions in any field you want, always in examinations you will remember difficult answers, it will attract the opposite sex, who ever you want or wish will come to you, in business sky is the limit with this ring, any type of lotteries, pools, lotto’s, bingo’s etc will be won by you, you will be protected from black magic, evil powers, spirits etc so no body will be able to talk bad about you and where ever you go you will be the center of attraction with this wonder power ring. The moment this ring is worn its powers in contact with the fingers produces a gentle current of light electricity which quickly circulates throughout every part of the body, blood, veins, muscles and tissues, recharges the whole system with powers-refills the nerve cells and every organ and destroys diseases, germs and bestows new energy and power to the weak body. Website: https://spiritualherbalist1.wixsite.com/mysite Email : spiritualherbalisthealing@gmail.com or call +2349055637784
       Responder 
    Tem certeza que deseja  Sim  Não
    Insira sua mensagem aqui
Sem downloads
Visualizações
Visualizações totais
14.798
No SlideShare
0
A partir de incorporações
0
Número de incorporações
127
Ações
Compartilhamentos
0
Downloads
58
Comentários
4
Gostaram
91
Incorporações 0
Nenhuma incorporação

Nenhuma nota no slide

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

×