Below is quick glance of Java Architecture Interview Questions and Answers.
What does SOLID stand for? What are its principles?
What is the difference between Monolithic, SOA and Microservices Architecture?
What are the differences between continuous integration, continuous delivery, and continuous deployment?
How do you do database migration?
What is the difference between Concurrency and Parallelism?
What was enhanced for Z Garbage Collector (ZGC)?
How do we manage and monitor Spring Boot application in production?
What is Domain Driven Design?
Explain the Single Responsibility Principle (SRP)?
How would you detect and minimise memory leaks?
Are you familiar with The Twelve-Factor App principles?
What is MetaSpace in Java8? How does it differ from PermGen Space?
How Does Volatile Affect Code Optimization By Compiler?
What is message driven design and it's advantages?
Why Kafka is better than other messaging systems?
How to make custom annotation in Spring Boot?
What is CQRS? design pattern?
Q: What is SOLID principles?
Ans:
S.O.L.I.D is an acronym for the first five principles of object-oriented design (OOD) by Robert C. Martin, which stands from
- S - Single-responsibility principle : A class should have one reason to change, which means that a class should only have one job.
- O - Open-closed principle : Objects / entities should be open for extension, but closed for modification.
- L - Liskov substitution principle : Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.
- I - Interface segregation principle : A client should never be forced to implement an interface that it does not use, or clients should not be forced to rely on methods that they do not use.
- D - Dependency Inversion Principle : Entities must depend on abstractions, not concreteness. It states that the high-level module must not depend on the low-level module, but should depend on abstractions.
Q: What is the difference between Monolithic, SOA and Microservices Architecture?
Ans:
The aim of the LTS version is to complete the preview capabilities so that they are stable enough and look good for the next three years.- Monolithic Architecture is analogous to a large container in which all software elements of the application are assembled together and wrapped tightly.
- Service-Oriented Architecture is a set of services that interact with each other. Communication may involve either simple transmission of data or may involve two or more services coordinating such activities.
- Microservice Architecture is an architectural style that constructs an application as a series of small autonomous services, modeled around a business domain.
Q: What is continuous integration, continuous delivery, and continuous deployment?
Ans:
Continuous Integration and continuous Delivery (CI/CD) is a set of software practices and techniques that enable the frequent release of small batches of code changes, with extensive visibility and traceability. It typically involves the creation of a largely automated pipeline that orchestrates the build, test and deployment of software across staged environments, ultimately leading to deployment in production.
- Continuous Integration : Developers merge their changes back to the main branch as much as possible, instead of waiting for the release day to integrate their changes into the release branch.
- Continuous delivery : is an extension of continuous integration to ensure that new improvements can be made easily and sustainably to the customers. This means that, in addition to getting your testing automated, you have also automated your release process and can deploy your application at any time by clicking on a button.
- Continuous delivery is one step beyond continuous delivery, with this any change that passes through all stages of your production pipeline is released to your customers. There is no human interference, and only a failed test can prevent a new improvement from being introduced to production.
Q: What are the most common memory leaks, and how would you deal with them?
Ans:
Memory Leakage via Static Fields
The common case that could result in a memory leak is the high use of static variables. We must tak caution when utilising static variables. When collections or large objects are declared as static, they remain in memory across the application's lifetime, consuming valuable memory that could have been used somewhere else.
As a result, reduce using static variables and, while using singletons, use an implementation that lazily loads the object rather than eagerly loading it.
Unclosed Resources
A memory leak in Java might happen if you neglect to close a resource or if you don't remove a reference to an object. File/Text buffers not closed. (as per reported)
Improper equals() and hashCode() Implementations
When creating new classes, it's typical to forget to provide proper override equals() and hashCode() methods.
These methods are used by HashSet and HashMap in a variety of operations, and if they aren't overridden correctly, they can cause memory leaks.
Map map = new HashMap<>(); for(int i=0; i<10; i++) { map.put(new Employee("Ban"), 1); }
Here, if we don't overrides equals() and hashCode() methods in Employee Class, duplicate objects will collect and take up more memory, which is why several instances will get created in memory.
Therefore, if we would have overridden the equals() and hashCode() methods in Employee class, this Map would only contain one Employee object.
finalize() Methods
When the finalize() method of a class is overridden, objects of that class are not immediately garbage collected. Instead, they are queued for finalisation by the GC, which occurs at a later time.
Furthermore, if the code in the finalize() method is not optimal, and the finalizer queue cannot keep up with the Java garbage collector, our application will eventually encounter an OutOfMemoryError.
Q: Are you familiar with The Twelve-Factor App principles?
Ans:
The 12-factor app approach is a technique for software development as a service. These best practices are intended to allow portability and resilience web applications to be developed.- Codebase : Central one codebase for a deployed service tracked in revision control with the codebase being used for many deployments.
- Dependencies : Explicitly declare and isolate dependencies. All dependencies should be declared, with no implicit reliance on system tools or libraries.
- Config : Store config in the environment. Configuration that varies between deployments should be stored in the environment.
Refer Spring Cloud Config Example for more understanding.
- Backing services : Treat backing services as attached resources. All backing services are treated as attached resources and attached and detached by the execution environment.
- Build, release, run : Strictly separate build and run stages. The delivery pipeline should strictly consist of build, release, run.
- Port binding : Export services as port binding. Self-contained services should make themselves available to other services by specified ports.
- Concurrency : Scale out via the process model. Concurrency is advocated by scaling individual processes.
- Dev/Prod parity : Keep development, staging and production as similar as possible. All environments should be as similar as possible.
- Logs : Treat log as event stream. Applications should produce logs as event streams and leave the execution environment to aggregate.
- Admin Processes : Run admin/management tasks as one-off process. Any needed admin tasks should be kept in source control and packaged with the application.
Q: How do you do database migration?
Ans:
Liquibase and Flyway are two tools that help for database schema changes management, tracking, and deployment. They're both migration-based technologies that aim to fill a gap in many teams workflows by treating database code like app code and automating it.
Refer Spring Boot + Liquibase Example for more understanding.
Q: What is the difference between Concurrency and Parallelism?
Ans:
Concurrency | Parallelism |
Concurrency indicates that an application is working on more than one task at the same time (concurrently). | Parallelism refers to how a program divides its tasks into smaller subtasks that may be handled in parallel, for examples, on several CPUs at the same time. |
Concurrency can be accomplished by utilising a single processing unit. | While this cannot be accomplished with a single processing unit. It requires the use of multiple processing units. |
Concurrency increases the amount of work finished at the same time. | Parallelism increases the system's performance and computing speed. |
Concurrency follow non-deterministic control flow approach. | Parallelism is deterministic control flow approach. |
Q: What was enhanced for Z Garbage Collector (ZGC)?
Ans:
JDK 11 has introduced Z Garbage Collector (ZGC), which had short pause while cleaning up the heap memories and it was not returning unused memory to operating system even though memory was unused for long time. Now Java 13 has extended the feature to return unused heap memory to the operating system.Click on link to know more about Z Garbage Collector
Q: How do we manage and monitor Spring Boot application in production?
Spring Boot Actuator is a Spring Boot sub-project that adds monitoring and management capabilities for your production-ready apps. It offers a number of HTTP or JMX endpoints with which you can communicate.
The Prometheus (a tool for monitoring) endpoint is provided by the Spring Boot Actuator, which regularly pulls this endpoint for metric data and offers graphic representation for data. Grafana, which is rich in graphical representation, could also be used.
Below is Grafana graph, which pulled data from Prometheus.
Refer Spring Boot Actuator + Prometheus + Grafana Example
Q: What is Domain Driven Design?
Ans:
Domain driven design is a methodology and process prescription for developing complex systems which focus on mapping into the technical objects of a solution area activities, tasks, events and data within a problem field. It's all about making your software a real system or process model.
Q: Explain the Single Responsibility Principle (SRP)?
Ans:
Robert C. Martin describes the single responsibility principle as:
"A class should have one, and only one, reason to change."
This principle states that each class should have only one responsibility and one single purpose. This implies that a class will do only one task, meaning that it should have only one reason to change.
It simplifies the implementation of your software and protects against unexpected consequences of future changes.
Q: When should I use a NoSQL database instead of a relational database?
Ans:
Relational databases enforce the ACID. So, you can have schema-based data stores that are transaction-oriented. For 99 percent of real world applications, it is proven and suitable. With relational databases, you can basically do anything.
when it comes to large high-availability data stores, there are speed and scaling limitations. Google and Amazon have terabytes of data stored in large data centers, for example. In these cases, querying and inserting is not successful because of the blocking/schema/transaction nature of the RDBMs.
That is why, for huge performance benefit and scalability, they have introduced their own databases (actually, key-value stores).
- We use NoSQL db usually when:
- Client requires 99.999 percent availability at high traffic sites.
- Your data doesn't make any sense in SQL, you find yourself doing multiple JOIN queries to access some piece of information.
- you split the relational model, have CLOBs that store denormalized data, and create external indexes to search for that data.
Q: What is PermGen (Permanent Generation) ?
Ans:
A memory pool that contains all of the Java Virtual Machine's own reflective data, such as class and method objects. With Java VMs that use data sharing class, this generation is divided into read-only and read-write areas.
Permanent Generation contains the metadata needed by the JVM for the application to define the classes and methods used. At runtime, the permanent generation is populated by the JVM based on classes in the application's use. Moreover, the classes and methods of the Java SE library can be stored here.
Q: What is MetaSpace in Java8? How does it differ from PermGen Space?
Ans:
The Permanent Generation (PermGen) space has been removed completely with JDK8 and is kind of replaced by a new space called Metaspace.
This metadata is now stored as "MetaSpace" in the native memory. This memory is not a Java Heap contiguous memory. It allows for improvements in the collection of garbage space over PermGen space, auto tuning, concurrent metadata de-allocation.
The result of the PermGen elimination is that the PermSize and MaxPermSize JVM arguments are obviously ignored and you will never receive an error with java.lang.OutOfMemoryError: PermGen.
You can refer more question on Garbage Collection Interview Questions and AnswersQ: How Does Volatile Affect Code Optimization By Compiler?
Ans:
Volatile is an instruction that multiple threads will access the variables and should therefore not be cached. Because volatile variables are never cached, their retrieval can therefore not be optimized.
Q: What is message driven design and it's advantages?
Ans:
The goal of message driven architecture is to connect distributed systems by using standardized message oriented middleware to send messages from one module to another module.
- It is non-blocking and asynchronous.
- Without waiting for a response, system resources can be released immediately. It lessens disagreement and raises the possibility of increased scalability.
- When the receiver is available, messages can be delivered.
Refer Spring Cloud Stream with RabbitMQ: Message-Driven Microservices
Q: Why Kafka is better than other messaging systems?
Ans:
There are several messaging systems that are alternate to Kafka. RabbitMQ, ActiveMQ and ZeroMQ are some of the popular ones
- RabbitMQ : RabbitMQ is a powerful messaging broker that was actually designed to implement Advanced Message Queuing Protocol (AMQP). This open-source tool is developed in Erlang and is easy to install and use. RabbitMQ supports both message persistence and replication. RabbitMQ comes with excellent routing capabilities based on rules. The performance is good. RabbitMQ is broker-centric which means it focuses on deliver guarantees between the consumer and the producers. Advanced capabilities such as routing, persistent messaging and load balancing can be performed with a few lines of code. However, RabbitMQ messaging system is not distributed. When you have an infrastructure that scales massively, RabbitMQ won't be able to match that capability
- ActiveMQ : ActiveMQ is another popular messaging system that is easy to implement and use. It enjoys largest number of installations. The deployment supports both P2P and broker topologies. With a few lines of code, you can implement advanced capabilities. It uses Java Message Service specification. ActiveMQ offers numerous options when it comes to clustering and distribution. ActiveMQ enjoys strong documentation and active support. It is highly scalable and handles tens of thousands of messages per second.
ActiveMQ is reliable and delivers high performance. While ActiveMQ offers more features, it is more suited for simple queue service (SQS). When it comes to distributed systems that massively scale up and down, ActiveMQfaces tough competition from newer technologies that deliver better performance and features. ActiveMQ writes messages to a journal before shipping them to consumers. It means the number of messages that it can store depends on the disk capacity. In case of high memory consumption, ActiveMQ pauses producers until the space is freed. In a distributed system wherein producers also act as consumers, the entire system can be locked up.
Refer Spring Boot JMS with ActiveMQ Example - ZeroMQ : ZeroMQ is a light weight messaging system that comes with strong documentation and active support. The tool is especially useful for instances wherein low latency and high throughout are required. It offers all advanced capabilities similar to RabbitMQ. However, the downside is that you have to combine various pieces of frameworks to create those solutions. While ZeroMQ offers strong documentation, there is a bit of learning curve.
Refer Spring Boot Apache Kafka Example
Refer Apache Kafka Interview Questions and Answers
Q: How to make custom annotation in Spring Boot?
Ans:
User can make class, method or field level custom annotation to solve the redundancy or cross cutting concerns. Refer Spring Boot + Custom Annotation Example for class, method or field level custom annotations.
Q: What is CQRS? design pattern?
Ans:
CQRS (Command Query Responsibility Segregation) is a microservices design pattern that divides reading and writing into two models. Every method should be either a Command that performs an action or a Query that returns data. CQRS divides reads and writes into independent models, updating data with commands and reading data with queries.
The name Command Query Responsibility Segregation denotes that Command is used to handle POST, PUT, PATCH, DELETE - (WRITE) operations, whilst Query is used to handle GET - (READ) operation.
Refer Spring Boot CQRS Example
What does it mean by "Memory Is Managed in Java"?
What is Garbage Collection and why is it beneficial?
Are there any Drawbacks of Garbage Collection?
What steps would you take to improve the performance of a Java application?
What is the best way to optimise database calls and which is more important, space or time?
What strategy would you use to refresh your cache?
What Is a Memory Leak?
What are two different types of objects that reside in Heap memory?
What are the Signs of Memory Leaks?
What are the most common memory leaks, and how would you deal with them?
How would you detect and minimise memory leaks?
Q: What does it mean by "Memory Is Managed in Java"?
Ans:
Memory is the most important resource that an application requires to function properly, and it, like any other resource, is limited. As a result, allocating and deallocating memory to and from apps or various sections of an application requires a great deal of thought and care.
In Java, however, a developer does not need to manually allocate and deallocate memory since the JVM, notably the Garbage Collector, handles memory allocation so that the developer does not have to.
Q: What is Garbage Collection and why is it beneficial?
Ans:
Garbage collection is the process of examining heap memory, determining which items are in use and which are not, and then eliminating the objects that aren't.
The most significant benefit of garbage collection is that it saves us of the stress of manual memory allocation and deallocation, allowing us to focus on the problem at hand.
Refer Java 8 - Top Garbage Collection Interview Questions and Answers for more questions on garbage collection.
Q: Are there any Drawbacks of Garbage Collection?
Ans:
Yes, the garbage collector has an effect on the application's performance whenever it runs. This is due to the fact that all other threads in the application must be stopped in order for the garbage collector thread to do its job effectively. This concern, however, can be greatly minimized or eliminated through skilled optimization, garbage collector tuning, and the use of various GC algorithm
Q: What steps would you take to improve the performance of a Java application?
Ans:
Managing pool of threads
- Pool essential system resources such as threads, database connections, socket connections, and so on.
- Focus on thread reuse from a pool of threads. Creating new threads and then discarding them can have a negative impact on performance. Consider using multi-threading in your single-threaded applications to improve performance. Improve pool sizes in accordance with system and application specifications and requirements.
- Too many threads in a pool can also cause performance and scalability issues due to memory stack consumption and CPU context switching.
Reduce network overheads
Reduce network overheads by retrieving multiple related items in a single remote invocation when required. Remote method invocations require a network round-trip, parameter marshalling and unmarshaling, which can cause significant performance issues when the remote interface is poorly designed.
Reduce database calls overheads
- Database calls are network-based remote calls.
- To save memory, data must be loaded lazily from a database, however there are some scenarios in which eagerly loading data and caching can improve performance by reducing network trips to the database.
- Data could be eagerly loaded using SQL scripts with complex joins or stored procedures, and cached using third-party frameworks or even your own framework.
Q: What is the best way to optimise database calls and which is more important, space or time?
Ans:
There is likely some pre-emptive micro-optimization, and therefore I believe we can identify a few general points.
Out of Memory
- Considering the large size of data, it will almost certainly encounter memory errors.
- Avoid reading the entire ResultSet into memory.
- Use pagination.
- Can use cache for static or default data.
Database calls
- Multiple network connections can quickly get to be a bottleneck. A full join can also be costly to the database.
- To save memory, data must be loaded lazily from a database.
Multithreading
- You don't have to run all the code in a single transaction.
- You could even split your process so that each row is not locked by multiple threads. Check that your database will properly adapt row-level locking.
- Focus on thread reuse from a pool of threads. Creating new threads and then discarding them can have a negative impact on performance.
Q: What strategy would you use to refresh your cache?
Ans:
Timed cache strategy
Timed cache strategy in which the cache is refilled on a regular basis (i.e. every 30 minutes, every hour etc). This is a simple strategy that can be used when it is acceptable to present dirty data on event and the data in the database does not frequently change.
Dirty check strategy
Dirty check strategy in which your application is the only one with the ability to evolve (i.e. change) the data in the database. Once data in the database is modified by your application, you could set the
"isDirty" flag
totrue
, and your cache could be refreshed based on the"isDirty" flag
.
Q: What Is a Memory Leak?
Ans:
A Memory Leak occurs whenever objects in the heap are no longer needed but still the garbage collector will be unable to remove them from memory, causing them to be kept in memory unnecessarily.
A memory leak is problematic since it consumes memory resources and slows down the system throughout duration. If this problem is not addressed, the programme will eventually run out of resources, resulting in a fatal java.lang.OutOfMemoryError
.
Q: What are two different types of objects that reside in Heap memory?
Ans:
There are two different types of objects that reside in Heap memory
Referenced
Unreferenced
Referenced objects would be those who still have active references within the application, whereas unreferenced objects do not have any active references.
As we can be seen, we have two types of objects - referenced and unreferenced; the Garbage Collector can remove objects which are unreferenced. Referenced objects will not be collected, although if they are no longer used by the application.
Q: What are the Signs of Memory Leaks?
Ans:
The following are some signs of memory leaks:
- Worked quickly at first, but slowed down over time.
- Works well with small data sets but resulted in serious performance issues with large data sets.
- Your JVM's Old-Generation memory usage is steadily increasing.
- Out-of-Memory Heap errors in your JVM
- Crashing without warning.
Q: What are the most common memory leaks, and how would you deal with them?
Ans:
Memory Leakage via Static Fields
The common case that could result in a memory leak is the high use of static variables. We must tak caution when utilising static variables. When collections or large objects are declared as static, they remain in memory across the application's lifetime, consuming valuable memory that could have been used somewhere else.
As a result, reduce using static variables and, while using singletons, use an implementation that lazily loads the object rather than eagerly loading it.
Unclosed Resources
A memory leak in Java might happen if you neglect to close a resource or if you don't remove a reference to an object. File/Text buffers not closed. (as per reported)
Improper equals() and hashCode() Implementations
When creating new classes, it's typical to forget to provide proper override equals() and hashCode() methods.
These methods are used by HashSet and HashMap in a variety of operations, and if they aren't overridden correctly, they can cause memory leaks.
Map map = new HashMap<>(); for(int i=0; i<10; i++) { map.put(new Employee("Ban"), 1); }
Here, if we don't overrides equals() and hashCode() methods in Employee Class, duplicate objects will collect and take up more memory, which is why several instances will get created in memory.
Therefore, if we would have overridden the equals() and hashCode() methods in Employee class, this Map would only contain one Employee object.
finalize() Methods
When the finalize() method of a class is overridden, objects of that class are not immediately garbage collected. Instead, they are queued for finalisation by the GC, which occurs at a later time.
Furthermore, if the code in the finalize() method is not optimal, and the finalizer queue cannot keep up with the Java garbage collector, our application will eventually encounter an OutOfMemoryError.
Q: How would you detect and minimise memory leaks?
Ans:
There are two options. The first step would be 'quick fix.' If that continues to fail, you'll have had to take the other option.
- quick fix: Eclipse Memory Leak Warnings (catches few of the leaks)
- Using a JVM tool such as VisualVM, manually disable and enable parts of your code and monitor memory usage of your JVM (or Jconsole, or Thermostat).
Top Java Garbage Collection Interview Questions (2023)
What is Java Garbage Collection?
Is there PermGen space in the Java8 onwards version?
What is Metaspace?
What tools are available to monitor Metaspace?
What is the Dangling pointer bug in Garbage Collection?
What is Double free bugs in Garbage Collection?
What is minor or incremental garbage collection?
What does it mean by major or full garbage collection?
What is "stop-the-world" in Garbage Collection?
How did Java tried to resolve the Stop-the-World problem in Garbage Collection?
Which are four types of garbage collectors?
What are the most important Garbage Collection metrics to track?
How do I fine-tune garbage collection?
What is Java Heap Space?
Explain in detail how garbage collection works?
Q: What is Java Garbage Collection?
Ans:
Garbage collection (GC) in the Java virtual machine (JVM) is responsible for automatically determining what memory is no longer in use by a Java application and recycling it for other purposes.
Q: Is there PermGen space in the Java8 onwards version?
Ans:
In JDK 8.0, Permanent Generation (PermGen) memory space has been entirely removed.
If the PermSize and MaxPermSize JVM arguments are available at startup, they have been neglected and a warning is issued.
Q: What is Metaspace?
Ans:
After Java removed PermGen, a new memory space Metaspace was introduced in Java 8.
The JDK 8 HotSpot JVM, like the Oracle JRockit and IBM JVMs, now uses native memory for the representation of class metadata, which is referred to as Metaspace.
Now, you will not encounter or get java.lang.OutOfMemoryError
PermGen exceptions happening due to the limited size of the PermGen space of the heap.
When the class metadata usage exceeds the MaxMetaspaceSize limit, metaspace garbage collection is triggered. Extreme Metaspace garbage collection could be a sign of a class, classloader memory leak, or insufficient sizing for our application.
Q: What tools are available to monitor Metaspace?
Ans:
The HotSpot 1.8 verbose GC log output shows metaspace usage.
Note: Older tools having PermGen space references, like b75, Jstat and JVisualVM have not been updated, so we can't go with these tools for monitoring metspace.
Q: What is the Dangling pointer bug in Garbage Collection?
Ans:
Dangling pointer bugs happen whenever a piece of memory is freed (during object destruction) but there are still pointers to it, and one of those pointers is dereferenced. By then, the memory could have been reassigned to some other use, with unpredictable results.
Q: What is Double free bugs in Garbage Collection?
Ans:
Double free bugs occur when a program attempts to free a region of memory that has already been freed and possibly allocated again.
Q: What is minor or incremental garbage collection?
Ans:
Once unreachable objects in young generation heap memory are removed, it is said that a minor or incremental garbage collection has occurred.
Q: What does it mean by major or full garbage collection?
Ans:
When the objects which survived the minor garbage collection and were copied into the old generation or permanent generation heap memory are removed, a major or full garbage collection has occurred. Garbage collection occurs less frequently in the old generation than in the younger generations.
Q: What is "stop-the-world" in Garbage Collection?
Ans:
The JVM will stop the application for at least a short time and execute GC to free up memory. The procedure is known as "stop-the-world". This means that all threads will stop running except the GC threads until the GC threads have completed and the garbage collector has freed up all objects.
Q: How did Java tried to resolve the Stop-the-World problem in Garbage Collection?
Ans:
Java 11 has some great features, one is Z Garbage Collector (ZGC). The Z Garbage Collector, also known as ZGC, is a low latency scalable garbage collector designed to meet the following objectives.
- Pause times shall not exceed 10 ms
- Handle heaps ranging from a few hundred megabytes to multi terabytes in size
- Pause times do not increase with the size of the heap or live-set.
Refer Z Garbage Collector (ZGC) to understand in detail.
Modern JVMs, such as Azul Zing, use the Continuously Concurrent Compacting Collector (C4), that eliminates the stop-the-world GC pauses which limit scalability in traditional JVMs.
Q: Which are four types of garbage collectors?
Ans:
At its most simple, Garbage Collection includes finding memory that is no longer in use and making it available for reuse.
Java has below four types of garbage collectors:
Serial Garbage Collector
with only one thread executing the GCParallel Garbage Collector
Simultaneous execution of multiple minor threads, each of which executes a part of the GCCMS Garbage Collector
CMS, which is equivalent to parallel, means allowing the execution of some application threads while also reducing the frequency of stop-the-world GC.G1 Garbage Collector
G1, that is also run in parallel and concurrently but it does have a different function than CMS Refer Z Garbage Collector (ZGC) to understand in detail.
Q: Why is it necessary and important to monitor garbage collection?
Ans:
Garbage collection could have an unpredictable impact on the performance of a Java application. Whenever there is a lot of GC activity, it puts a lot of burden on the CPU and slows down application processing. As a result, business transactions are executed slowly, affecting the user experience of end users accessing the Java application.
Q: What are the most important Garbage Collection metrics to track?
Ans:
Below are few important points to keep track in Garbage Collection metrics:
- When the garbage collection took place
- How frequently is garbage collected?
- How much memory is gathered each time?
- How long does garbage collection running?
- JVM garbage collection time as a percentage of total time
- The kind of garbage collection took place - minor or full GC?
- JVM heap and non-heap memory utilisation
- JVM CPU utilisation
Q: How do I fine-tune garbage collection?
Ans:
Here are two common approaches:
- Reduce the number of objects passed to the old generation area as much as possible.
- Set the major (or full) GC time to be short.
-Xms, -Xmx, and -NewRatio are a few crucial JVM parameters to configure for right-sizing the JVM's memory (ratio of new generation and old generation size)
Q: What is Java Heap Space?
Ans:
The Java runtime allocates memory to Objects and JRE classes using heap space. Whenever we make an object, it always makes it in the Heap space.
Garbage Collection runs on heap memory to free memory used by objects that do not have a reference. Any object created in heap space has global access and can be accessed from anywhere in the application.
Q: What is Java Stack Memory?
Ans:
Java Stack memory is used to execute a thread. They contain method-specific, short-lived values as well as references to other objects in the heap that are referred to by the method.
Stack memory is always accessed in the last-in-first-out (LIFO) order.Whenever a method is called, a new block in stack memory is created for the method to keep local primitive values and references to other objects in the method.
Q: Explain in detail how garbage collection works?
Ans:
The heap is subdivided into smaller spaces, known as generations. These areas are known as the Young Generation, the Old or Tenured Generation, and the Permanent Generation.
Young Generation
The Young Generation is where new objects are created.
The Young Generation is further subdivided into the following groups:
Eden space
All new objects begin in Eden space, and initial memory is assigned to them.Survivor spaces (Survivor 1 and Survivor 2)
after surviving one garbage collection cycle, objects are moved here from Eden.
It's said to be a minor garbage collection event, when objects are garbage collected from the Young Generation,
A Minor GC is performed when Eden space is completely filled with objects. All dead objects are removed, and all living objects are relocated to one of the survivor spaces. Minor GC also examines the objects in one survivor space and continues to move them to the other.
Old Generation
Long-lived objects are moved from the Young Generation to the Old Generation. This is also called the Tenured Generation, and it also has objects that have been in survivor spaces for a long period of time.
It's said to be a major garbage collection event, when objects are garbage collected from the Old Generation.
- When a new object is created, it is first placed in the young generation's Eden space.
- When minor garbage collection occur, the live objects from Eden are moved to the Survivor 1 Space .
- When the next minor garbage collection occurs, the live objects from both Eden and Survivor 1 Space are moved to the Survivor 2 Space.
- This cycle is repeated for a specific number of times. If the object is still in use after this step, it will be moved to the old generation space in the next garbage collection cycle.
Permanent Generation (before Java 8 Version)
The Permanent Generation stores metadata such as classes and methods. The JVM populates it at runtime based on the classes in use by the application. Classes which are no longer being used may be collected as garbage by the Permanent Generation.MetaSpace (since from Java 8)
The PermGen memory space has been replaced by the MetaSpace memory space since about Java 8. The implementation differs from PermGen in that this heap space is now automatically resized.
The JDK 8 HotSpot JVM, like the Oracle JRockit and IBM JVMs, now uses native memory for the representation of class metadata, which is referred to as Metaspace.
Now, you will not encounter or get java.lang.OutOfMemoryError: PermGen exceptions happening due to the limited size of the PermGen space of the heap.
No comments:
Post a Comment