Podcast
Questions and Answers
What is the primary benefit of using ConcurrentHashMap over a synchronized HashMap in a multithreaded environment?
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.
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?
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 ______.
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 ______.
Match the garbage collection phase with its description:
Match the garbage collection phase with its description:
What happens to objects created within a method scope once the method execution is completed?
What happens to objects created within a method scope once the method execution is completed?
Invoking System.gc()
guarantees immediate garbage collection in Java.
Invoking System.gc()
guarantees immediate garbage collection in Java.
Name one of the profiling tools used to understand, monitor, and debug memory usage in a Java application.
Name one of the profiling tools used to understand, monitor, and debug memory usage in a Java application.
In the context of garbage collection, when a new object is initially created, it is placed in the ______.
In the context of garbage collection, when a new object is initially created, it is placed in the ______.
Which SOLID principle states that a class should have only one reason to change?
Which SOLID principle states that a class should have only one reason to change?
The Open/Closed Principle suggests that a class should be closed for extension but open for modification.
The Open/Closed Principle suggests that a class should be closed for extension but open for modification.
Which SOLID principle focuses on ensuring that derived classes can substitute for their base classes without altering the correctness of the program?
Which SOLID principle focuses on ensuring that derived classes can substitute for their base classes without altering the correctness of the program?
The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, but both should depend on ______.
The Dependency Inversion Principle states that high-level modules should not depend on low-level modules, but both should depend on ______.
Match the SOLID principle to the description:
Match the SOLID principle to the description:
What is a key characteristic of a Marker Interface in Java?
What is a key characteristic of a Marker Interface in Java?
A marker interface typically contains method signatures that classes implementing it must implement.
A marker interface typically contains method signatures that classes implementing it must implement.
Name one commonly used marker interface in Java's core libraries.
Name one commonly used marker interface in Java's core libraries.
Implementing the Cloneable
marker interface enables an object to be ______.
Implementing the Cloneable
marker interface enables an object to be ______.
Match the marker interface with its purpose:
Match the marker interface with its purpose:
What is the primary purpose of acquiring a lock in Java multithreading?
What is the primary purpose of acquiring a lock in Java multithreading?
Intrinsic locks in Java are more flexible and provide finer-grained control compared to explicit locks.
Intrinsic locks in Java are more flexible and provide finer-grained control compared to explicit locks.
Name one type of explicit lock available in Java's java.util.concurrent.locks
package.
Name one type of explicit lock available in Java's java.util.concurrent.locks
package.
When using explicit locks, you must manually ______ the lock after you are finished with the shared resource.
When using explicit locks, you must manually ______ the lock after you are finished with the shared resource.
Match the lock characteristic with its benefit:
Match the lock characteristic with its benefit:
Which of the following is a key difference between the Runnable
and Callable
interfaces in Java?
Which of the following is a key difference between the Runnable
and Callable
interfaces in Java?
The Runnable
interface's run()
method can return a value upon completion of the thread's execution.
The Runnable
interface's run()
method can return a value upon completion of the thread's execution.
Which package contains the Callable
interface in Java?
Which package contains the Callable
interface in Java?
The call()
method in the Callable
interface can throw a ______ exception, allowing for more robust error handling.
The call()
method in the Callable
interface can throw a ______ exception, allowing for more robust error handling.
Match the interface feature with the correct Java interface:
Match the interface feature with the correct Java interface:
What is the first step you should take when you recognize performance degradation in your system?
What is the first step you should take when you recognize performance degradation in your system?
If a database query that previously took one second to execute now takes 15 seconds, it always indicates a network issue.
If a database query that previously took one second to execute now takes 15 seconds, it always indicates a network issue.
Name one tool that can be used to profile a java application to identify inefficient code or memory leaks.
Name one tool that can be used to profile a java application to identify inefficient code or memory leaks.
To reduce the number of hits to the database, you can implement an ______ cache using tools like Redis or Memcached.
To reduce the number of hits to the database, you can implement an ______ cache using tools like Redis or Memcached.
Match the tool to the function:
Match the tool to the function:
Which design pattern is commonly used to manage distributed transactions across microservices, ensuring data consistency even when individual services fail?
Which design pattern is commonly used to manage distributed transactions across microservices, ensuring data consistency even when individual services fail?
When migrating from a monolithic architecture to microservices, it is best to refactor the entire application in one large deployment.
When migrating from a monolithic architecture to microservices, it is best to refactor the entire application in one large deployment.
Name a common design pattern used when designing microservices that acts as a single entry point for all client requests.
Name a common design pattern used when designing microservices that acts as a single entry point for all client requests.
In a microservices architecture, [BLANK] helps services locate and communicate with each other dynamically.
In a microservices architecture, [BLANK] helps services locate and communicate with each other dynamically.
Match the microservices concept with description:
Match the microservices concept with description:
When estimating the efforts for new feature development, what is the first step?
When estimating the efforts for new feature development, what is the first step?
When estimating efforts for new feature development, there is no need to include buffer time.
When estimating efforts for new feature development, there is no need to include buffer time.
Flashcards
ConcurrentHashMap
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
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
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
Threads running at a time in ConcurrentHashMap
Signup and view all the flashcards
Garbage Collection
Garbage Collection
Signup and view all the flashcards
Object Allocation in Memory
Object Allocation in Memory
Signup and view all the flashcards
Minor vs Major Garbage Collection
Minor vs Major Garbage Collection
Signup and view all the flashcards
G1 Garbage Collector
G1 Garbage Collector
Signup and view all the flashcards
Making Objects Eligible for Garbage Collection
Making Objects Eligible for Garbage Collection
Signup and view all the flashcards
Nullify Objects
Nullify Objects
Signup and view all the flashcards
Reassign Reference
Reassign Reference
Signup and view all the flashcards
Objects inside the method scope
Objects inside the method scope
Signup and view all the flashcards
Dereferencing Cyclic Dependency
Dereferencing Cyclic Dependency
Signup and view all the flashcards
SOLID Principles
SOLID Principles
Signup and view all the flashcards
Single Responsibility Principle
Single Responsibility Principle
Signup and view all the flashcards
Open/Closed Principle
Open/Closed Principle
Signup and view all the flashcards
Liskov Substitution Principle
Liskov Substitution Principle
Signup and view all the flashcards
Interface Segregation Principle
Interface Segregation Principle
Signup and view all the flashcards
Dependency Inversion Principle
Dependency Inversion Principle
Signup and view all the flashcards
Marker Interface
Marker Interface
Signup and view all the flashcards
Examples of Marker Interface
Examples of Marker Interface
Signup and view all the flashcards
Why use a Marker Interface
Why use a Marker Interface
Signup and view all the flashcards
Lock
Lock
Signup and view all the flashcards
Types of Locks in Java
Types of Locks in Java
Signup and view all the flashcards
Locking Mechanism
Locking Mechanism
Signup and view all the flashcards
Runnable vs. Callable
Runnable vs. Callable
Signup and view all the flashcards
Return and Exceptions
Return and Exceptions
Signup and view all the flashcards
When to Use Runnable vs. Callable
When to Use Runnable vs. Callable
Signup and view all the flashcards
Diagnose Performance Issues
Diagnose Performance Issues
Signup and view all the flashcards
Common Performance Bottlenecks
Common Performance Bottlenecks
Signup and view all the flashcards
Optimization Techniques
Optimization Techniques
Signup and view all the flashcards
When to use Monolith
When to use Monolith
Signup and view all the flashcards
When to Use Microservices
When to Use Microservices
Signup and view all the flashcards
Saga Design Pattern
Saga Design Pattern
Signup and view all the flashcards
Orchestration vs. Choreography
Orchestration vs. Choreography
Signup and view all the flashcards
Top Down vs. Bottom Up Approach
Top Down vs. Bottom Up Approach
Signup and view all the flashcards
Bottom to Up Approach
Bottom to Up Approach
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
- Marking: Identifies live objects in the old generation.
- Stopping: The program is shortly interrupted during the marking process.
- Concurrent Scanning: The heap is scanned for live objects.
- Final Marking: Completes the marking process.
- 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()
andnotify()
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
andCallable
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 thejava.lang
package.Callable
is from thejava.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 importantCalable
: 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
Optimize Database Related Things
- 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.