Java - Advanced Flashcards
Explain the concept of the Java Memory Model (JMM)
The Java Memory Model (JMM) defines the rules and guarantees for how threads interact with memory in a multi-threaded environment
How does the JMM ensure thread safety?
It ensures thread safety by providing synchronization and visibility guarantees.
Synchronization is achieved through the use of synchronized blocks or methods, which enforce exclusive access to shared resources.
Visibility guarantees are provided by the JMM’s rules for how changes made by one thread become visible to other threads.
This is accomplished through the use of volatile variables, locks, and happens-before relationships.
Concurrency
Concurrency refers to the ability of a system to handle multiple tasks concurrently, where tasks can start, run, and complete in overlapping time periods.
In Java, concurrency is achieved using threads, where multiple threads execute concurrently, sharing the same CPU resources.
An example of concurrency in Java is a web server handling multiple client requests simultaneously.
Parallelism
Parallelism, on the other hand, involves the simultaneous execution of multiple tasks to improve performance by utilizing multiple CPUs or CPU cores.
It is a form of concurrency where tasks are divided into smaller subtasks that can be executed independently.
An example of parallelism in Java is using the Java 8 Stream API to process a large collection of data in parallel using multiple threads.
How does garbage collection work in Java?
Garbage collection in Java automatically reclaims memory occupied by objects that are no longer reachable.
It frees developers from managing memory explicitly.
The Java Virtual Machine (JVM) performs garbage collection by identifying objects that are no longer referenced by any live threads.
The garbage collector identifies these objects and reclaims their memory.
Different types of garbage collectors?
Serial garbage collector
Parallel garbage collector
Concurrent Mark Sweep (CMS) garbage collector
Garbage-First (G1) garbage collector
Serial garbage collector
It uses a single thread for garbage collection and pauses all application threads during the collection process.
It is suitable for small applications with low memory requirements.
Parallel garbage collector
It uses multiple threads for garbage collection, which reduces the pause time. It is suitable for applications with larger heaps and multi-core systems.
Concurrent Mark Sweep (CMS) garbage collector
It minimizes pauses by performing most of the garbage collection work concurrently with the application’s execution. It is suitable for applications that require low pause times.
Garbage-First (G1) garbage collector
It divides the heap into multiple regions and performs concurrent garbage collection with high throughput and low pause times. It is suitable for large heaps and applications with strict pause time requirements.
What are the different ways to achieve inter-thread communication in Java?
Wait and notify
Blocking queues
Condition variables
Wait and notify
The wait() and notify() methods, along with synchronized blocks or methods, allow threads to wait for a condition to be satisfied and notify other threads when the condition changes.
For example, a producer-consumer scenario where a producer thread notifies the consumer thread when new data is available.
Blocking queues
The java.util.concurrent package provides blocking queue implementations like LinkedBlockingQueue and ArrayBlockingQueue.
These queues allow threads to block when trying to retrieve an element from an empty queue or insert an element into a full queue.
They handle the synchronization internally.
Condition variables
The java.util.concurrent.locks.Condition interface provides more flexible inter-thread communication compared to wait and notify.
It allows threads to wait for specific conditions to be met.
For example, a thread waiting for a queue to become non-empty can use a condition variable.
Explain the concept of the Java ClassLoader
The Java ClassLoader is responsible for loading classes into the JVM at runtime. It is a crucial part of the Java runtime environment.
The ClassLoader searches for classes in a specific order, following the delegation model. When a class is requested, the ClassLoader first checks if it has already been loaded. If not, it delegates the request to its parent ClassLoader. If the parent cannot find the class, the ClassLoader attempts to load the class itself.
What are the three main components of the ClassLoader hierarchical structure?
Bootstrap ClassLoader
Extensions ClassLoader
Application ClassLoader
Application ClassLoader
It is a child of the Extensions ClassLoader and loads classes from the application’s classpath.
Extensions ClassLoader
It is a child of the Bootstrap ClassLoader and loads classes from the Java extensions directory.
Bootstrap ClassLoader
It is the parent of all other ClassLoaders and loads core Java classes from the bootstrap classpath.
What are the different ways to handle distributed computing in Java?
Remote Method Invocation (RMI)
Java Messaging Service (JMS)
Web services
Distributed frameworks
Remote Method Invocation (RMI)
RMI allows Java objects to invoke methods on remote objects located on different JVMs.
It provides a simple and transparent way to perform remote method calls by using Java interfaces and stubs.
RMI handles the network communication and object serialization automatically.
Java Messaging Service (JMS)
JMS is a Java API that allows applications to send and receive messages asynchronously.
It enables distributed communication through message-oriented middleware, such as message queues or publish-subscribe systems.
What are the Comparable and Comparator interfaces used for?
The Comparable and Comparator interfaces in Java are used for comparing objects
Comparable interface
It is implemented by a class to define its natural ordering.
The compareTo() method is defined in the Comparable interface, which returns a negative integer, zero, or a positive integer depending on whether the current object is less than, equal to, or greater than the specified object.
For example, the String class implements Comparable, allowing sorting of strings in their natural lexicographical order.
Comparator interface
It is a separate class that defines an external comparison strategy for objects that do not implement Comparable or require a different sorting order.
The compare() method is defined in the Comparator interface, which takes two objects and returns a negative integer, zero, or a positive integer depending on their ordering.
For example, a custom Comparator can be implemented to sort a list of objects based on a specific attribute.
Pagination
Pagination involves dividing the dataset into smaller chunks or pages and retrieving and processing them iteratively.
This approach is useful when the entire dataset cannot fit into memory at once. Typically, you specify the page size and retrieve one page of data at a time.
Pagination can be implemented using techniques like offset and limit queries in databases or using APIs that support paginated responses.
Streaming
Streaming involves processing the dataset as a stream of elements, where elements are processed one at a time without loading the entire dataset into memory.
Java provides the Stream API, introduced in Java 8, which allows you to process large datasets using functional-style operations.
Streams provide operations like filter, map, reduce, and collect, allowing you to perform transformations and computations on the dataset.
java
What are the different ways to achieve immutability in Java?
Final keyword
Immutable classes
What are the different ways to achieve fault tolerance in Java?
Manual retry loop (retry to a set limit)
Libraries and frameworks (Hystrix, resilience4j, etc…)
Circuit breakers
Explain the concept of the Java Native Interface (JNI)
The Java Native Interface (JNI) is a programming framework that enables Java code to interact with code written in other programming languages, particularly native languages like C and C++. JNI provides a way to call native code from Java and vice versa.
JPA
JPA is a Java specification for Object-Relational Mapping (ORM).
It provides a higher-level abstraction over JDBC, allowing developers to work with objects instead of SQL queries.
JPA maps Java objects to relational database tables and provides an API for performing CRUD (Create, Retrieve, Update, Delete) operations.
JPA is implemented by various ORM frameworks, such as Hibernate, EclipseLink, and OpenJPA.
These frameworks handle the mapping of objects to tables, generate SQL queries, and manage the database operations automatically.
What are the different ways to achieve high availability in Java applications?
Clustering
Load Balencing
Clustering
Clustering involves grouping multiple servers or instances together to work as a single logical unit.
In a cluster, each server shares the workload and is aware of the others, allowing them to collaborate and provide high availability.
Load Balencing
Load balancing distributes incoming requests across multiple servers to achieve better resource utilization and prevent any single server from being overwhelmed.
Load balancers act as intermediaries between clients and servers, intelligently routing requests to available server instances.
What are the different ways to handle transactions in Java applications?
Programmatic Transaction Management (put it in the code).
Declarative Transaction Management (using annotations)