Todas las especialidadesTecnología · Entrevista de trabajo

JVM

Las preguntas sobre la JVM muestran si sabes qué se ejecuta bajo tu código Java. Explicar la recolección de basura y la memoria en un inglés sencillo es una habilidad que se puede entrenar.

Palabras → expresiones → frases → conversación

Probar SpeakRole ↗
Entrevista de trabajoJVM
V

What happens when the JVM runs out of heap memory?

0:18
Pregunta del entrevistador

JVM

Los entrevistadores de puestos de Java suelen pasar del lenguaje al entorno de ejecución: cómo se organiza la memoria, cómo se limpian los objetos y qué haces cuando un servicio en producción se queda sin memoria. Incluso a un candidato de nivel medio se le exige conocer las ideas principales y las herramientas adecuadas.

Da las respuestas en este orden: qué hace cada pieza, cómo funciona en términos sencillos y cómo la verías en un sistema real, por ejemplo en un log de GC o en un volcado del heap (heap dump). Ten cuidado con los detalles que dependen de la versión y di "in modern Java" o "it depends on the version" cuando no estés seguro.

  • ✓Palabras → expresiones → frases → conversación
  • ✓Sentido de la respuesta
  • ✓Idioma

Preguntas habituales y respuestas de ejemplo

How does garbage collection work in the JVM?

¿Cómo funciona la recolección de basura (garbage collection) en la JVM?

Qué quiere oír el entrevistador. La alcanzabilidad desde las raíces, la idea de las generaciones, la diferencia entre pausas cortas y largas y al menos un recolector con nombre.

Respuesta de ejemplo en inglés para practicar en voz alta

The JVM frees the memory of objects that can no longer be reached from the roots, such as thread stacks and static fields. Most objects die young, so the heap is usually divided into a young generation and an old generation. New objects go to the young area, and a small, fast collection cleans it. Objects that survive move to the old area, which is collected less often. Some phases stop the application, and we call that a stop-the-world pause. In modern Java, G1 is usually the default collector, and it tries to keep pauses short. ZGC and Shenandoah aim for even shorter pauses. I choose by the pause and throughput requirements, and I check the GC logs.

What are the main memory areas of the JVM?

¿Cuáles son las principales áreas de memoria de la JVM?

Qué quiere oír el entrevistador. El heap, las pilas de los hilos, el metaspace y la memoria nativa, y qué se guarda en cada una. Extra: qué error apunta a qué área.

Respuesta de ejemplo en inglés para practicar en voz alta

The biggest area is the heap, where objects are created and where the garbage collector works. Each thread has its own stack, which holds method frames with local variables and references. When the stack gets too deep, for example with endless recursion, we get a StackOverflowError. Class metadata is stored in metaspace, which uses native memory and replaced the old permanent generation in Java 8. There is also memory outside the heap: thread stacks, direct buffers and the code cache with compiled code. This is important in containers, because the process uses more memory than the heap size alone.

How does class loading work in the JVM?

¿Cómo funciona la carga de clases en la JVM?

Qué quiere oír el entrevistador. Carga, enlace e inicialización, el modelo de delegación al padre y la diferencia entre ClassNotFoundException y NoClassDefFoundError.

Respuesta de ejemplo en inglés para practicar en voz alta

The JVM loads classes lazily, when they are first needed. A class loader finds the bytecode and creates the class. Then the class is linked, which means it is verified and prepared, and finally it is initialised: static fields are set and static blocks run. Class loaders form a hierarchy with parent delegation. A loader first asks its parent to load the class, and only then tries by itself. This protects core classes like String from being replaced. ClassNotFoundException happens when code asks for a class by name and it is not found. NoClassDefFoundError usually means that the class existed at compile time but is missing at runtime, or that its static initialisation failed.

How do you investigate a memory leak or an OutOfMemoryError?

¿Cómo investigas una fuga de memoria o un OutOfMemoryError?

Qué quiere oír el entrevistador. Una secuencia práctica: confirmar con logs de GC y métricas, tomar un volcado del heap, analizarlo, encontrar la cadena de referencias y corregir la causa.

Respuesta de ejemplo en inglés para practicar en voz alta

First I check whether it is really a leak. In the GC logs or the metrics, I look at whether the memory after a full collection keeps growing. I make sure the JVM writes a heap dump on OutOfMemoryError, or I take one with jcmd. Then I open it in a tool like Eclipse Memory Analyzer and look for the biggest objects and the path from a GC root that keeps them alive. Typical causes are static collections that only grow, caches without a size limit, listeners that are never removed and ThreadLocal values in long-living threads. After the fix, I watch the memory again under similar load.

How do you tune a JVM for a production service?

¿Cómo ajustas una JVM para un servicio en producción?

Qué quiere oír el entrevistador. Medir primero; tamaño del heap, elección del recolector, límites del contenedor y calentamiento; un cambio cada vez y con un objetivo claro.

Respuesta de ejemplo en inglés para practicar en voz alta

I start with a goal: low latency, high throughput or small memory use. Then I measure, and I never tune by guessing. I enable GC logging, set the maximum heap with Xmx, and often set the initial heap to the same size to avoid resizing. In a container, I leave room for non-heap memory, so I set the heap as a percentage of the container limit, for example with MaxRAMPercentage. I change one parameter at a time and test under realistic load. I also remember that the JIT compiler needs warm-up, so the first minutes after a start are slower, and a load test must run long enough to show the real picture.

Cómo pronunciar los términos clave

JVM
dyéi-vi-em (letra a letra)
heap
jiip (la «ii» es larga, no «jip»)
metaspace
mé-ta-speis
bytecode
báit-koud
JIT
dyit (rima con «bit») o dyéi-ai-ti
allocation
a-lo-kéi-shon
generation
dye-ne-réi-shon

Frases útiles para responder

  • Under the hood, the JVM…Internamente, la JVM…
  • The GC logs show that…Los logs de GC muestran que…
  • I would take a heap dump and look at…Haría un volcado del heap y miraría…
  • The trade-off is between pause time and throughput.El trade-off está entre el tiempo de pausa y el throughput.
  • It depends on the JVM version and the collector.Depende de la versión de la JVM y del recolector.
  • The object stays reachable because…El objeto sigue siendo alcanzable porque…
  • I would measure under realistic load first.Primero mediría con una carga realista.

Errores habituales que debes evitar

  • Confundir el modelo de memoria de Java con las áreas de memoria de la JVM. El primero trata de la visibilidad entre hilos; las segundas, del heap, el stack y el metaspace. Di a cuál te refieres.
  • Decir "the garbage collector deletes unused objects" y quedarte ahí. Explica la alcanzabilidad desde las raíces y la idea de las generaciones. Es el punto débil más común.
  • Proponer un heap más grande como solución a una fuga de memoria. Un heap mayor solo retrasa el fallo. Di que encuentras la referencia que mantiene vivos los objetos.
  • Citar de memoria flags de la JVM sin decir la versión. Muchas opciones cambiaron entre versiones de Java, así que di "in recent versions" y consulta la documentación.
  • Pronunciar "heap" como "hip". La vocal es larga, como en "cheap", y el español solo tiene una «i». Practica en voz alta las palabras clave, porque una vocal equivocada puede cambiar la palabra que quieres decir.

Preguntas frecuentes

¿Necesito conocer los algoritmos de GC en detalle?

Necesitas las ideas principales: alcanzabilidad, generaciones, pausas y uno o dos recolectores con sus objetivos. Detalles como el tamaño de las regiones o los flags de ajuste solo se esperan en puestos senior o centrados en el rendimiento.

¿Qué herramientas de la JVM debo mencionar?

Nombra las que usaste: logs de GC, jcmd, jstack para los volcados de hilos, Java Flight Recorder y un analizador de heap como Eclipse Memory Analyzer. Si solo usaste un panel de monitorización, dilo y explica qué mirabas.

¿Debo mencionar la versión de Java?

Sí. Di qué versión usó tu último proyecto y señala que algunos comportamientos difieren entre versiones. Demuestra que sabes que el entorno de ejecución cambia y te protege de afirmar algo que solo es cierto para una versión.

Leer una respuesta no es lo mismo que decirla. Practica cada pregunta en voz alta y después compara el sentido y el idioma de tu propia respuesta.

Probar SpeakRole ↗

Otros temas de esta área