Java, Spring Boot, and Microservices Interview Prep

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What is the primary benefit of using ConcurrentHashMap over a synchronized HashMap in a multithreaded environment?

  • Improved performance due to segment-based locking. (correct)
  • Automatic data consistency without explicit synchronization.
  • Simpler implementation and reduced code complexity.
  • Guaranteed absence of deadlocks and race conditions.

In ConcurrentHashMap, read operations always require acquiring a lock, ensuring data consistency during concurrent modifications.

False (B)

What is the default number of segments, also known as the concurrency level, in a ConcurrentHashMap?

16

In Java 8 and later, if the number of entries in a ConcurrentHashMap's bucket exceeds a certain threshold, the bucket's structure changes from a linked list to a ______.

<p>balanced tree</p>
Signup and view all the answers

Match the garbage collection phase with its description:

<p>Marking = Identifying objects that are still in use. Scanning = Scanning the heap to identify any live objects. Cleanup = Reclaiming the garbage space to use for the next set of objects.</p>
Signup and view all the answers

What happens to objects created within a method scope once the method execution is completed?

<p>They are immediately eligible for garbage collection if no longer referenced. (D)</p>
Signup and view all the answers

Invoking System.gc() guarantees immediate garbage collection in Java.

<p>False (B)</p>
Signup and view all the answers

Name one of the profiling tools used to understand, monitor, and debug memory usage in a Java application.

<p>VisualVM</p>
Signup and view all the answers

In the context of garbage collection, when a new object is initially created, it is placed in the ______.

<p>eden space</p>
Signup and view all the answers

Which SOLID principle states that a class should have only one reason to change?

<p>Single Responsibility Principle (A)</p>
Signup and view all the answers

The Open/Closed Principle suggests that a class should be closed for extension but open for modification.

<p>False (B)</p>
Signup and view all the answers

Which SOLID principle focuses on ensuring that derived classes can substitute for their base classes without altering the correctness of the program?

<p>Liskov Substitution Principle</p>
Signup and view all the answers

The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, but both should depend on ______.

<p>abstractions</p>
Signup and view all the answers

Match the SOLID principle to the description:

<p>Single Responsibility Principle = A class should have only one reason to change. Open/Closed Principle = Software entities should be open for extension, but closed for modification. Liskov Substitution Principle = Subtypes must be substitutable for their base types. Interface Segregation Principle = Clients should not be forced to depend on methods they do not use. Dependency Inversion Principle = Depend upon Abstractions.</p>
Signup and view all the answers

What is a key characteristic of a Marker Interface in Java?

<p>It has no methods or fields. (A)</p>
Signup and view all the answers

A marker interface typically contains method signatures that classes implementing it must implement.

<p>False (B)</p>
Signup and view all the answers

Name one commonly used marker interface in Java's core libraries.

<p>Serializable</p>
Signup and view all the answers

Implementing the Cloneable marker interface enables an object to be ______.

<p>copied</p>
Signup and view all the answers

Match the marker interface with its purpose:

<p>Serializable = Enables object serialization. Cloneable = Enables object cloning. Remote = Indicates a remote object for RMI.</p>
Signup and view all the answers

What is the primary purpose of acquiring a lock in Java multithreading?

<p>To ensure exclusive access to a shared resource by one thread at a time. (D)</p>
Signup and view all the answers

Intrinsic locks in Java are more flexible and provide finer-grained control compared to explicit locks.

<p>False (B)</p>
Signup and view all the answers

Name one type of explicit lock available in Java's java.util.concurrent.locks package.

<p>ReentrantLock</p>
Signup and view all the answers

When using explicit locks, you must manually ______ the lock after you are finished with the shared resource.

<p>unlock</p>
Signup and view all the answers

Match the lock characteristic with its benefit:

<p>Reentrant Lock = Allows a thread to acquire the same lock multiple times. Fair Lock = Favors threads that have been waiting the longest. TryLock = Attempts to acquire a lock without blocking.</p>
Signup and view all the answers

Which of the following is a key difference between the Runnable and Callable interfaces in Java?

<p><code>Callable</code> allows a thread to throw a checked exception, while <code>Runnable</code> does not. (C)</p>
Signup and view all the answers

The Runnable interface's run() method can return a value upon completion of the thread's execution.

<p>False (B)</p>
Signup and view all the answers

Which package contains the Callable interface in Java?

<p>java.util.concurrent</p>
Signup and view all the answers

The call() method in the Callable interface can throw a ______ exception, allowing for more robust error handling.

<p>checked</p>
Signup and view all the answers

Match the interface feature with the correct Java interface:

<p>Returns a value = Callable Cannot throw checked exceptions = Runnable Part of java.lang package = Runnable</p>
Signup and view all the answers

What is the first step you should take when you recognize performance degradation in your system?

<p>Diagnose the issue and identify the source of the slowness using monitoring tools. (C)</p>
Signup and view all the answers

If a database query that previously took one second to execute now takes 15 seconds, it always indicates a network issue.

<p>False (B)</p>
Signup and view all the answers

Name one tool that can be used to profile a java application to identify inefficient code or memory leaks.

<p>JProfiler</p>
Signup and view all the answers

To reduce the number of hits to the database, you can implement an ______ cache using tools like Redis or Memcached.

<p>in-memory</p>
Signup and view all the answers

Match the tool to the function:

<p>New Relic = Application Performance Monitoring Eclipse MAT = Memory analysis tool Apache JMeter = Load testing</p>
Signup and view all the answers

Which design pattern is commonly used to manage distributed transactions across microservices, ensuring data consistency even when individual services fail?

<p>Saga Pattern (D)</p>
Signup and view all the answers

When migrating from a monolithic architecture to microservices, it is best to refactor the entire application in one large deployment.

<p>False (B)</p>
Signup and view all the answers

Name a common design pattern used when designing microservices that acts as a single entry point for all client requests.

<p>API Gateway</p>
Signup and view all the answers

In a microservices architecture, [BLANK] helps services locate and communicate with each other dynamically.

<p>service discovery</p>
Signup and view all the answers

Match the microservices concept with description:

<p>Monolith = Single large application where all functionalities as a single unit. Microservice = Small, independent and loosely coupled service. Bounded Context = A specific responsibility that has a well-defined interfaces.</p>
Signup and view all the answers

When estimating the efforts for new feature development, what is the first step?

<p>Breaking down is into tasks. (B)</p>
Signup and view all the answers

When estimating efforts for new feature development, there is no need to include buffer time.

<p>False (B)</p>
Signup and view all the answers

Flashcards

ConcurrentHashMap

A thread-safe implementation of a hash map, allowing multiple threads to read and write concurrently without locking the entire map.

Internal working of ConcurrentHashMap

ConcurrentHashMap is divided into segments (or buckets), each of which can be independently locked, allowing multiple threads to operate on different segments concurrently.

Concurrency level in ConcurrentHashMap

The number of threads that can modify the ConcurrentHashMap simultaneously without hindering each other, determined by the number of segments (default is 16).

Threads running at a time in ConcurrentHashMap

Reads can occur without blocking. Modifications are limited by the number of segments (default 16), requiring a lock on the specific segment being modified.

Signup and view all the flashcards

Garbage Collection

A process in which the JVM automatically reclaims memory occupied by objects that are no longer in use, freeing up resources for new objects.

Signup and view all the flashcards

Object Allocation in Memory

Objects are initially created in the Eden space (Young Generation). Objects that survive garbage collection cycles are moved to the Old Generation.

Signup and view all the flashcards

Minor vs Major Garbage Collection

Minor GC cleans the Young Generation (Eden space), while Major GC cleans the Old Generation, where long-lived objects reside.

Signup and view all the flashcards

G1 Garbage Collector

G1 (Garbage First) is designed for multi-threaded applications with large heaps; aims to meet garbage collection time goals with high throughput.

Signup and view all the flashcards

Making Objects Eligible for Garbage Collection

By setting an object reference to null, reassigning a reference, or when an object goes out of scope within a method.

Signup and view all the flashcards

Nullify Objects

Setting an object to null removes any active references.

Signup and view all the flashcards

Reassign Reference

Creating a new object and assigning it to a reference that previously pointed to another object makes the original object eligible.

Signup and view all the flashcards

Objects inside the method scope

Objects created inside a method exist only within that method's scope; once the method completes, the objects are eligible for garbage collection.

Signup and view all the flashcards

Dereferencing Cyclic Dependency

The garbage collector automatically handles cyclic dependencies, so explicit action is not needed.

Signup and view all the flashcards

SOLID Principles

A set of principles for object-oriented programming that promote maintainable, extensible, and robust software design.

Signup and view all the flashcards

Single Responsibility Principle

A class should have only one reason to change.

Signup and view all the flashcards

Open/Closed Principle

Software entities should be open for extension but closed for modification.

Signup and view all the flashcards

Liskov Substitution Principle

Objects of a superclass should be replaceable with objects of its subclasses without altering the correctness of the program.

Signup and view all the flashcards

Interface Segregation Principle

Clients should not be forced to depend on methods they do not use.

Signup and view all the flashcards

Dependency Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Signup and view all the flashcards

Marker Interface

A special type of interface with no methods or fields, used to mark a class as having a specific property or behavior.

Signup and view all the flashcards

Examples of Marker Interface

serializable, clonable, and remote

Signup and view all the flashcards

Why use a Marker Interface

To tag a class as eligible for certain features or behavior without requiring any specific method implementations.

Signup and view all the flashcards

Lock

A section of code where access is controlled to ensure that only one thread can execute it at a time, preventing race conditions.

Signup and view all the flashcards

Types of Locks in Java

Intrinsic locks are provided by Java and are associated with every object, used with the synchronized keyword. Explicit locks are part of the java.util.concurrent.locks package.

Signup and view all the flashcards

Locking Mechanism

Automatic when entering a synchronized block; must be manually locked and unlocked with explicit locks.

Signup and view all the flashcards

Runnable vs. Callable

Runnable is an interface with a run() method to execute tasks. Callable is an interface with a call() method that returns a value and can throw exceptions.

Signup and view all the flashcards

Return and Exceptions

Runnable cannot return a value or throw checked exceptions; Callable can return a value and throw checked exceptions.

Signup and view all the flashcards

When to Use Runnable vs. Callable

Use Runnable when you only need to execute a task without needing a result or handling exceptions. Use Callable when you need a result and/or to handle exceptions.

Signup and view all the flashcards

Diagnose Performance Issues

Diagnose with monitoring tools, identify slowness (API, memory, DB), check JVM metrics, and analyze DB execution time.

Signup and view all the flashcards

Common Performance Bottlenecks

High-memory objects, slow DB queries, thread contention, and deadlocks.

Signup and view all the flashcards

Optimization Techniques

Tools for profiling code, adjusting JVM parameters, optimizing thread usage, and implementing caching.

Signup and view all the flashcards

When to use Monolith

Small to medium size is simple. Easy to develop and deploy. Strict deadline means focus on functionality.

Signup and view all the flashcards

When to Use Microservices

Independent team can work on it. Autonomous system to be deployed. Quickly iterated for customer feedback.

Signup and view all the flashcards

Saga Design Pattern

Breaks a long process into a series of smaller, individual transactions executed by different microservices, with compensating rollbacks for failures.

Signup and view all the flashcards

Orchestration vs. Choreography

A centralized service manages and coordinates transactions; decentralized where services communicate directly

Signup and view all the flashcards

Top Down vs. Bottom Up Approach

Design starts from the highest level components broken to smaller modules while from the granular level, build to high level module

Signup and view all the flashcards

Bottom to Up Approach

The development starts with granular to integrate for a higher level system that suits requirement changes.

Signup and view all the flashcards

Study Notes

Interview Preparation: Java, Spring Boot, and Microservices

  • These notes are based on a real L1 interview experience at Cognizant.
  • Questions are relevant for software engineers and Java developers at various experience levels.
  • Focus on understanding the questions and formulating the ideal answers.

Tell Me About Yourself

  • Highlight education, experience, current role, and contributions.
  • Mention technology stacks and project overviews.
  • Project architecture details are covered later, if requested.

Team Structure and Size

  • Explain team hierarchy (junior levels, senior levels, leads, tech leads, project managers).
  • Describe client-facing roles and communication with clients.
  • Mention team size, roles, requirement gathering, sprint cycles, code reviews, and other practical details.

ConcurrentHashMap

  • It's a thread-safe implementation of a hash map, handling multiple concurrent write operations efficiently.
  • It outperforms standard HashMaps in multithreaded environments.
  • Unlike synchronized HashMaps (via Collections.synchronizedMap), ConcurrentHashMap uses segment-based locking.
  • It is part of the java.util.concurrent package.
  • It allows multiple threads to read and modify the map concurrently.
  • It avoids locking the entire map for write operations, improving performance.
  • Data is partitioned into segments, allowing threads to access different segments without blocking.
  • Read operations do not typically require locks.
  • After Java 8, segments use a combination of linked lists and balanced trees for internal structure.
  • High collision rates in a segment trigger the use of balanced trees for better performance.

Internal Working of ConcurrentHashMap

  • It is divided into multiple segments or buckets.
  • Each segment can be independently locked.
  • This allows multiple threads to read, write, and operate concurrently on different segments.
  • Locking occurs at the segment level, reducing contention.
  • Non-blocking reads improve performance.
  • Java 8+ uses linked lists and balanced trees within segments to handle collisions efficiently.
  • Excessive collisions lead to the use of balanced trees to maintain performance.

Concurrency Level in ConcurrentHashMap

  • It represents the number of threads that can simultaneously modify the map without blocking.
  • It is determined by the number of segments in the map.
  • The default concurrency level for ConcurrentHashMap is 16.
  • This enables 16 threads to write concurrently to different segments.

Number of Threads Runnable at a Time

  • Reads can occur without blocking, allowing multiple threads to read concurrently.
  • Modification is limited by the number of segments (default 16).
  • Each write operation requires acquiring a lock on a segment.
  • A maximum of 16 threads can modify 16 different segments simultaneously.
  • Threads attempting to access the same segment must wait.

Summary of ConcurrentHashMap Benefits

  • Suited for multi-threading environments
  • Offers high throughput
  • Prevents bottlenecks by avoiding full map locking
  • Provides non-blocking reads.

Java Garbage Collection of Objects:

  • The garbage collection process automatically recycles unused objects, freeing memory for new objects
  • The JVM automatically reclaims memory by removing objects no longer reachable.
  • G1 (Garbage First) garbage collector has significantly improved object recycling.
  • Objects are initially created in the Eden space of the Young Generation.
  • Objects surviving initial cleanup cycles move to the Old Generation.

Memory Allocation

  • Objects are initially created in the "Eden space."
  • Eden space is part of the Young Generation.
  • Minor GC occurs in the Young Generation.
  • Objects surviving minor GC cycles are moved to the Old Generation.
  • Major GC occurs in the Old Generation.

Garbage Collection types

  • Serial GC
  • Parallel GC
  • Concurrent Mark Sweep (CMS) Collector
  • G1 GC (default)

Steps

  1. Marking: Identifies live objects in the old generation.
  2. Stopping: The program is shortly interrupted during the marking process.
  3. Concurrent Scanning: The heap is scanned for live objects.
  4. Final Marking: Completes the marking process.
  5. Cleanup: Reclaims garbage-collected space, making it available for new objects.

Custom Object Garbage Collection

  • Explains how to make custom objects eligible for garbage collection.
  • Objects can be made eligible by setting them to null or making them unreachable.
  • There is no explicit way to force garbage collection in Java.

Steps for Making an Object Eligible

Marking as Null

  • Setting an object reference to null makes the object eligible for collection.
MyObject obj = new MyObject();
obj = null; // Object is now eligible
System.gc(); // Suggests garbage collection

Reassigning the Reference

  • Assigning a new object to a reference previously pointing to another object.
MyObject obj1 = new MyObject();
obj1 = new MyObject(); // Original object is eligible

Object Scope Inside a Method

  • Objects created within a method have a narrow scope and become eligible once the method completes.
public void createObject() {
    MyObject obj = new MyObject();
} // obj is eligible after method execution

Dereferencing Cyclic Dependency

  • Breaking cyclic dependencies between objects makes them eligible for garbage collection.
Node node1 = new Node();
Node node2 = new Node();
node1.next = node2;
node2.next = node1;
node1 = null;
node2 = null; // Both objects are eligible

Garbage Collection Summary

  • Explicitly calling System.gc() is a request, not a command.
  • Objects that are garbage collected are unreachable.
  • Profiling tools like VisualVM aid in monitoring and debugging memory usage.

SOLID Principles

  • These are used for clean code, scalability, and maintainability in software development.
  • A focus on writing structured, scalable, maintainable, and clean code is necessary.
  • These principles are widely adopted.
  • They are used for quality software design.

Single Responsibility Principle (SRP)

  • A class or component should have only one reason to change.
  • Classes should be designed to perform a single, well-defined task.
  • Changes to one part of the code should minimally impact other parts.

Open/Closed Principle (OCP)

  • Entities should be open for extension but closed for modification.
  • One should be able to add new functionality without altering existing code.
  • Keeps existing code well-tested and bug-free.

Liskov Substitution Principle (LSP)

  • Subtypes should be substitutable for their base types without altering the correctness of the program.
  • Subclass objects can replace superclass objects without breaking the code.
  • Focus on inheritance design that avoids breaking functionality.

Interface Segregation Principle (ISP)

  • Clients should not be forced to depend on methods they do not use.
  • Focus on designing specific interfaces, ensuring implementations only extend the required functionalities.
  • Small, specific interfaces should be used instead of large, general-purpose ones.

Dependency Inversion Principle (DIP)

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Interfaces should not depend on implementations; both should depend on abstractions.
  • Focus on abstract code for flexibility.

Benefits of SOLID Principles

  • Improves the reliability of the code
  • Makes code easier to maintain
  • Simplifies debugging
  • Helps with flexibility, which is beneficial when adding new features
  • Makes code reusable via inheritance
  • Abstracts code and promotes code reuse.

Marker Interface

  • It is a special type of interface with no methods or fields.
  • It tags a class for special treatment by the JVM.
  • Examples include Serializable, Clonable, and Remote.
  • Serializable: Marks a class for serialization into a byte stream.
  • Clonable: Enables field-by-field copying of objects.
  • Remote: Used in distributed environments.

Why Marker Interfaces?

  • To tag a class for specific features or behavior.
  • To check the type of a class at runtime, influencing JVM operations.
  • Enables custom behavior within frameworks or libraries.

Marker Interface Use

  • To audit auditable classes
  • If serialization is implemented, it enables serialization
  • If clonable is implemented, it enables cloning
  • This provides easy access to compile-time safety and is handy for the JVM.

Lock mechanism

  • This synchronizes a section of code to control access by multiple threads.
  • Ensures only one thread can execute a synchronized section at a time.
  • A lock prevents multiple threads from simultaneously accessing and modifying shared resources.

Types of Locks in Java

  • Intrinsic Lock: Provided by Java and associated with every object (synchronized keyword).
  • Explicit Lock: Offered by the java.util.concurrent.locks package. Provides more control and features. Lock interface with implementations like ReentrantLock.

explicit locks

  • Reentrant Lock
  • Fair and Unfair Lock
  • Deadlock (to be avoided_
  • TryLock

Intrinsic vs. Explicit Locks

  • Intrinsic: Built-in, automatic locking/unlocking.
  • Explicit: Manual locking/unlocking with more control.

Comparing Characteristics

  • Intrinsic: Automatic, not fair, not interruptible.
  • Explicit: Needs manual locking/unlocking, can be fair, supports interruption.
  • Intrinsic: Uses wait() and notify() for thread communication.
  • Explicit: Uses conditions via Condition interface for flexible communication.

When to Use Locks

  • Intrinsic: For simplicity, quick critical sections.
  • Explicit: For advanced features (tryLock, fairness, interruptibility), finer control in highly concurrent apps.

Runable and Calable

  • Discusses the differences between Runnable and Callable interfaces in Java concurrency.
  • Both interfaces are used for executing tasks by threads.
  • Questions are aimed to test your experiences with multi-threading
  • Runnable is from the java.lang package.
  • Callable is from the java.util.concurrent package.

Runable

  • To run a task on a thread, a class should implemnet Runable
  • Does not return a value or throw checked exceptions (void run()).
  • Cannot be used with ExecutorService.submit().

Calable

  • A thread can complete a task and return an exception
  • Returns some value and can throw exceptions.
  • Used with ExecutorService to get the result of the task.

Runable vs Calable:

  • Runnable: Cannot return a value or throw checked exceptions.
  • Callable: Returns a value and can throw checked exceptions to handle exceptions.

When to use them:

  • Runable: Useful for tasks when the result is not important
  • Calable: Useful to return a result or handle exceptions

Performance Degradation in System

  • Diagnosing performance issues (slowness)
  • The monitoring applications are New Relic, Dynatrace, AppDynamics; Spring Boot Actuator
  • Error checks for Stack traces, high latencies, etc
  • High memory object creation leads to high memory usage
  • High database response time
  • Garbage collection time and Heap usage can be monitored with the J console, Java Mission Control etc

Pinpointing root causes

  • inefficient code (improper thread pool) can be analyzed with J Profiler, Eclipse Mat etc

How to Optimization

  • Profiler: Profiler is used to analyze code
  • Garbage collection adjustments
  • Fine tune thread pools
  • Reduce database hits with memory caches like Redis, Gawa, EhCache etc
  • Make use of asynchronous process for less critical tasks with completable future as a messageing queue etc
  • Rewriting queries with proper indexes

Monitor and Scale

  • Tools like Prometheus and Grafana monitor the metrics of the system for degradation

General Good Practices

  • Writing effecient code
  • Load testing code with Apache JMeter and Locust to find bottlenecks
  • Set JVM parameters on production
  • Proper coding to implement easy vs eager loading based on application
  • Integrate with memory databases like Redis

Moving from Monolith to Microservices

  • Describes the process of modernizing a monolithic application into microservices
  • Outlines key considerations for architectural shift to a domain driven approach
  • Requires understanding the system
  • Design and develop microservices
  • The following design patterns should be used API gateway, event driven architecture, circuit breaker

Domain Driven Approach and Bounded Context

  • Same terminologies used across all services and implemented by integrated teams

Challenges

  • Complex system, data consistency amongst everything

Important notes

  • Apply design patterns as you migrate
  • Have a clear understanding of what the domain is
  • Step by Step refactor code to microservices

What is the difference

  • monolith is all in one file, micro is seperate amongst different systems
  • Micro can have SQL and non-SQL storage
  • easy additions of features in monolith
  • deployment in single file monolith, multiple in micro

The choice monolith or micro

  • monlith is small application , clear boundaries to develop and deploy, strict deadline
  • micro, it is an important and it should be scalable and flexible with rapid iterations
  • team has text stack
  • continuous delivery is rapid testing and change

New Feature is Added by the Client in the System

  • Estimation involved and effort requires to develop and the test and the deliver
  • First, understand the feature, then break it down into tasks
  • Assign different estimated efforts to each individual
  • Always work with test, developer etc
  • Assign a buffer and estimate accordingly
  • Use a productivity effort of 7 hours a day vs 8 for team members

Microservices

  • Discusses the Saga design pattern to manage distributed transactions across microservices
  • Two common types: orchestration-based and choreography-based

Orchestration Base Saga Pattern

  • Centralized service manages the transaction centrally between all the communications

Choreography Based Saga Pattern

  • Listen to event from other events and communicate with eachother decentralize no central control

Development style

  • What approach should be used for software development
  • Top to bottom or bottom to up
  • Top to bottom design the highest, sub modules and all different types
  • Bottoms integrate components, work and add the modules after
  • Both approaches and combine with the requirements
  • Top suited = crisp
  • Bottom suits agile dynamically changes.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team
Use Quizgecko on...
Browser
Browser