Java Architect Interview Questions and Answers (2024)
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.
Take a look at our Suggested Posts :
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 Answers
Q: 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