| Feature | Concept | Small Example | Key Point |
|---|---|---|---|
| Lambda Expressions | Concise way to represent a function. | (a, b) -> a + b | Works with functional interfaces. |
| Functional Interfaces | Interface with exactly one abstract method. | Predicate<Integer> p = n -> n > 10; | Common types: Function, BiFunction, Consumer, BiConsumer, Supplier, Predicate, BiPredicate, UnaryOperator, BinaryOperator. |
| Method References | Short form of a lambda that calls an existing method. | names.forEach(System.out::println); | Forms include static, instance and constructor references. |
| Default Methods | Interface can contain an implementation. | default void log(){...} | Allows interfaces to evolve without forcing every implementation to add the method. |
| Static Methods in Interfaces | Utility methods can belong to an interface. | MyUtil.validate() | Called using the interface name. |
| Stream API | Declarative processing of collections. | list.stream().filter(x -> x > 10).toList() | Intermediate operations are lazy; terminal operation triggers processing. |
| Date & Time API | Modern java.time API. | LocalDate.now() | Immutable and generally thread-safe date/time types. |
| Optional | Container representing a value that may be present or absent. | Optional.ofNullable(name).orElse("Unknown") | Useful for expressing absence and reducing accidental null handling. |
| Nashorn JavaScript Engine | Java 8 JavaScript execution engine. | new ScriptEngineManager().getEngineByName("nashorn") | Java 8 feature shown here; later Java releases removed Nashorn. |
| Parallel Streams | Stream processing using parallel execution. | list.parallelStream().map(...) | Useful only when parallel execution actually benefits the workload. |
| CompletableFuture | Asynchronous computation and composition. | CompletableFuture.supplyAsync(() -> load()) | Supports chaining, combining, exception handling and async workflows. |
| Collectors Utility | Collect/reduce stream results. | Collectors.toList(), groupingBy() | Common for converting streams into collections, maps and grouped results. |
| Interface | Input | Output | Example |
|---|---|---|---|
Function<T,R> | 1 | R | x -> x * 2 |
BiFunction<T,U,R> | 2 | R | (a,b) -> a + b |
Consumer<T> | 1 | void | x -> System.out.println(x) |
BiConsumer<T,U> | 2 | void | (k,v) -> System.out.println(k+v) |
Supplier<T> | 0 | T | () -> "Hello" |
Predicate<T> | 1 | boolean | x -> x > 10 |
BiPredicate<T,U> | 2 | boolean | (a,b) -> a.equals(b) |
UnaryOperator<T> | 1 | T | x -> x + 1 |
BinaryOperator<T> | 2 | T | (a,b) -> a + b |
| Category | Operations / API | Example |
|---|---|---|
| Intermediate operations | filter, map, flatMap, distinct, sorted, limit, skip, peek | list.stream().filter(x -> x > 10).map(x -> x * 2).collect(Collectors.toList()) |
| Terminal operations | collect, forEach, count, anyMatch, allMatch, noneMatch, findFirst, findAny, reduce | list.stream().filter(x -> x > 10).count() |
| Method | Source-listed operation | Small Example |
|---|---|---|
forEach | Iterate over Map entries. | map.forEach((k,v) -> System.out.println(k + "=" + v)); |
getOrDefault | Get a value or a default value. | map.getOrDefault("A", 0) |
putIfAbsent | Put a value when absent. | map.putIfAbsent("A", 1) |
computeIfAbsent | Compute a value when absent. | map.computeIfAbsent("A", k -> 100) |
computeIfPresent | Compute a value when present. | map.computeIfPresent("A", (k,v) -> v + 1) |
compute | Compute a new value. | map.compute("A", (k,v) -> v == null ? 1 : v + 1) |
merge | Merge a value with the existing value. | map.merge("A", 1, Integer::sum) |
replace | Replace an existing value. | map.replace("A", 10) |
remove | Remove an entry. | map.remove("A") |
List<String> names =
Arrays.asList("A","B");
names.forEach(n ->
System.out.println(n));List<Integer> result =
numbers.stream()
.filter(n -> n > 10)
.map(n -> n * 2)
.collect(Collectors.toList());String value =
Optional.ofNullable(name)
.orElse("Unknown");names.forEach(
System.out::println);Map<String,List<User>> grouped =
users.stream()
.collect(Collectors.groupingBy(
User::getDepartment));int total =
numbers.stream()
.reduce(0, Integer::sum);| Concept | API | Purpose | Example |
|---|---|---|---|
| Create async task | supplyAsync | Run a task that returns a result. | CompletableFuture.supplyAsync(() -> getUser()) |
| Create async void task | runAsync | Run a task without a result. | CompletableFuture.runAsync(() -> save()) |
| Transform result | thenApply | Transform the previous result. | future.thenApply(User::getName) |
| Chain another async task | thenCompose | Flatten dependent async operations. | user.thenCompose(u -> loadOrders(u.id())) |
| Combine independent tasks | thenCombine | Combine results of two futures. | a.thenCombine(b, (x,y) -> x + y) |
| Run after completion | thenAccept | Consume result without returning a value. | future.thenAccept(System.out::println) |
| Completion action | whenComplete | Observe result or exception. | future.whenComplete((r,e) -> log(r,e)) |
| Exception fallback | exceptionally | Return fallback after failure. | future.exceptionally(e -> "FAILED") |
| Exception handling | handle | Handle success and failure and produce a result. | future.handle((r,e) -> e == null ? r : fallback) |
| Wait for all | allOf | Complete when all futures complete. | CompletableFuture.allOf(a,b,c) |
| Wait for first | anyOf | Complete when any future completes. | CompletableFuture.anyOf(a,b) |
| Get result | join | Wait and return result; wraps failure in CompletionException. | String x = future.join() |
CompletableFuture<User> userFuture =
CompletableFuture.supplyAsync(() -> userService.getUser(10));
CompletableFuture<List<Order>> ordersFuture =
userFuture.thenCompose(user ->
CompletableFuture.supplyAsync(
() -> orderService.getOrders(user.getId())));
ordersFuture
.thenAccept(orders -> System.out.println(orders))
.exceptionally(ex -> {
ex.printStackTrace();
return null;
});
| API | Use When | Simple Meaning |
|---|---|---|
thenApply | Next step is a synchronous transformation. | Future → Future |
thenCompose | Next step itself returns a CompletableFuture and depends on previous result. | Future<Future<T>> → Future<T> |
thenCombine | Two independent futures need to be combined. | Future A + Future B → combined Future |
| Topic | Quick Reference | Example |
|---|---|---|
| Create a virtual thread | Use Thread.startVirtualThread. | Thread.startVirtualThread(() -> service.call()); |
| Builder | Use Thread.ofVirtual(). | Thread.ofVirtual().start(task); |
| Executor | Use a virtual-thread-per-task executor. | Executors.newVirtualThreadPerTaskExecutor() |
| Best fit | Large numbers of mostly blocking I/O tasks. | HTTP calls, database calls, file/network I/O. |
| Not a magic CPU boost | CPU-heavy work is still limited by available CPU resources. | Do not expect unlimited CPU throughput. |
| Thread-local considerations | Thread-local usage should be reviewed when creating very large numbers of threads. | Prefer scoped/context approaches where appropriate. |
try (var executor =
Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> future =
executor.submit(() -> callRemoteService());
System.out.println(future.get());
}
| Aspect | Platform Thread | Virtual Thread |
|---|---|---|
| Managed by | Operating system/JVM platform thread mapping. | Java runtime scheduler. |
| Cost | Relatively heavier. | Much lighter. |
| Scale | Limited by thread/memory overhead. | Can support very large numbers of concurrent tasks. |
| Best for | General tasks and CPU-oriented execution. | High-concurrency blocking I/O workloads. |
| Concept | Purpose | Example | Key Point |
|---|---|---|---|
| Thread | Unit of execution. | new Thread(task).start() | Direct thread management. |
| ExecutorService | Manage a pool of worker threads. | Executors.newFixedThreadPool(10) | Separates task submission from thread management. |
| Callable | Task that returns a value and can throw checked exceptions. | executor.submit(() -> calculate()) | Returns a Future. |
| Future | Represents a pending result. | future.get() | Can block waiting for completion. |
| synchronized | Mutual exclusion and visibility. | synchronized(lock){...} | Only one thread at a time enters the synchronized region for the same monitor. |
| Lock | Explicit locking control. | ReentrantLock | Provides features such as tryLock and interruptible locking. |
| volatile | Visibility of a variable across threads. | volatile boolean running; | Does not make compound operations such as count++ atomic. |
| ConcurrentHashMap | Thread-safe concurrent map. | new ConcurrentHashMap<>() | Designed for concurrent access. |
| BlockingQueue | Thread-safe producer/consumer queue. | new LinkedBlockingQueue<>() | Operations can wait for capacity/items. |
| CountDownLatch | Wait until a count reaches zero. | latch.await() | One-shot synchronization aid. |
| CyclicBarrier | Allow threads to meet at a common barrier. | barrier.await() | Reusable barrier. |
| Semaphore | Limit concurrent access to a resource. | semaphore.acquire() | Useful for controlling concurrency. |
| Feature | synchronized | Lock | volatile |
|---|---|---|---|
| Mutual exclusion | Yes | Yes | No |
| Visibility | Yes | Yes | Yes |
| Flexible lock control | Limited | Yes | No |
| tryLock | No | Yes | No |
| Compound operation atomicity | Can provide it when protected | Can provide it when protected | No |
| Class | Purpose | Example |
|---|---|---|
AtomicInteger | Atomic integer operations. | AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); |
AtomicLong | Atomic long operations. | sequence.incrementAndGet() |
AtomicBoolean | Atomic boolean state. | started.compareAndSet(false, true) |
AtomicReference<T> | Atomic reference updates. | ref.compareAndSet(oldValue, newValue) |
LongAdder | High-throughput counters under contention. | counter.increment() |
| Operation | Meaning | Example |
|---|---|---|
get() | Read current value. | count.get() |
set() | Set value. | count.set(10) |
incrementAndGet() | Increment and return new value. | count.incrementAndGet() |
getAndIncrement() | Return old value, then increment. | count.getAndIncrement() |
compareAndSet() | Update only when current value matches expected value. | count.compareAndSet(10, 20) |
| Aspect | Atomic | synchronized |
|---|---|---|
| Scope | Usually a single variable/state operation. | Can protect a larger critical section. |
| Mechanism | Atomic/compare-and-set style operations. | Monitor locking. |
| Best fit | Counters, flags, simple state transitions. | Multiple related variables/invariants and larger critical sections. |
| Rule | How to Implement |
|---|---|
| Make class final | Prevent subclassing that could introduce mutable behavior. |
| Make fields private and final | State is assigned once. |
| No setters | Do not expose state-changing methods. |
| Initialize through constructor | Validate and establish complete state during construction. |
| Defensive copies | Copy mutable objects on input and output. |
| Return immutable values where possible | Avoid exposing mutable internal state. |
public final class Employee {
private final String name;
private final List<String> skills;
public Employee(String name, List<String> skills) {
this.name = name;
this.skills = List.copyOf(skills);
}
public String getName() {
return name;
}
public List<String> getSkills() {
return skills;
}
}
| Aspect | Mutable | Immutable |
|---|---|---|
| State after construction | Can change. | Cannot change. |
| Thread sharing | Requires careful synchronization when shared. | Generally safer to share because state cannot change. |
| Examples | ArrayList, StringBuilder | String, Integer, LocalDate |
| Design | Setters/mutating methods may exist. | Final state, no setters, defensive copies when needed. |
| Question | Answer |
|---|---|
| What is asynchronous programming? | Executing work without making the caller wait for the operation to finish before continuing. The result can be processed later. |
| What is CompletableFuture? | A Java API for representing and composing asynchronous computations. It supports chaining, combining and exception handling. |
| Future vs CompletableFuture? | Future mainly represents a pending result and commonly requires blocking get(). CompletableFuture supports non-blocking-style composition such as thenApply, thenCompose and thenCombine. |
| thenApply vs thenCompose? | thenApply transforms a result. thenCompose chains a dependent asynchronous operation that itself returns a CompletableFuture. |
| thenCombine vs thenCompose? | thenCompose is for dependent operations. thenCombine combines two independent futures. |
| What is CompletableFuture.allOf()? | It returns a CompletableFuture that completes when all supplied futures complete. |
| How do you handle CompletableFuture exceptions? | Use exceptionally for fallback, handle to process success/failure and produce a result, or whenComplete to observe completion. |
| What is a virtual thread? | A lightweight Java thread managed by the runtime, designed to support very high concurrency, particularly for blocking I/O workloads. |
| Do virtual threads make CPU-intensive applications faster? | Not inherently. CPU-bound work remains constrained by CPU resources. Virtual threads primarily improve scalability for blocking/concurrent workloads. |
| When should you use virtual threads? | When an application has many concurrent tasks that spend significant time waiting on blocking I/O, such as HTTP or database operations. |
| What is concurrency? | The ability to make progress on multiple tasks during overlapping time periods. |
| Concurrency vs parallelism? | Concurrency is about dealing with multiple tasks at once; parallelism is executing multiple tasks simultaneously, typically on multiple CPU cores. |
| What is a race condition? | A bug where the result depends on the timing/interleaving of concurrent operations on shared state. |
| What is thread safety? | The property that shared code/data behaves correctly when accessed concurrently by multiple threads. |
| What does synchronized provide? | Mutual exclusion for the protected critical section and the required memory visibility guarantees around monitor locking/unlocking. |
| What is volatile? | It provides visibility and ordering guarantees for reads/writes of a variable, but does not make compound operations such as count++ atomic. |
| Why is count++ not atomic? | It involves multiple steps: read the value, add one, and write the value. Another thread can interleave between those steps. |
| What are atomic classes? | Classes such as AtomicInteger and AtomicReference provide thread-safe atomic operations without requiring explicit locking for each supported operation. |
| AtomicInteger vs int? | AtomicInteger provides atomic operations suitable for concurrent updates; a normal int does not provide atomic read-modify-write operations across threads. |
| Atomic vs synchronized? | Atomic classes are convenient for simple shared-state operations such as counters. synchronized is more suitable when multiple variables or a larger critical section must be protected as one unit. |
| What is an immutable class? | A class whose observable state cannot change after construction. |
| Why are immutable objects useful in concurrency? | Because their state cannot change, they can generally be shared between threads without synchronization for state mutation. |
| How do you make a class immutable? | Make the class final, fields private/final, initialize through constructors, remove setters, and use defensive copies for mutable fields. |
| Why are defensive copies required? | Returning or storing a mutable object directly can allow external code to change the object's internal state, breaking immutability. |
| What is ExecutorService? | An abstraction for managing task execution using worker threads and lifecycle management rather than creating a new thread manually for every task. |
| CountDownLatch vs CyclicBarrier? | CountDownLatch is generally one-shot and lets threads wait until a count reaches zero. CyclicBarrier lets a group of threads repeatedly wait for each other at a common barrier. |
| What is Semaphore? | A synchronization aid that maintains a set of permits and can limit how many threads access a resource concurrently. |
| What is ConcurrentHashMap? | A thread-safe map designed for concurrent access, allowing multiple threads to operate on the map without requiring one global external lock around every operation. |
| Topic | Remember This |
|---|---|
| CompletableFuture | Async composition: chain, combine and handle failures. |
| Virtual Thread | Lightweight concurrency, especially useful for blocking I/O. |
| synchronized | Mutual exclusion + visibility. |
| volatile | Visibility/order, not compound-operation atomicity. |
| AtomicInteger | Atomic counter/state updates. |
| Immutable | State cannot change after construction. |
| ExecutorService | Manage task execution and worker lifecycle. |
| ConcurrentHashMap | Concurrent access to map data. |
| Java 8 | Java 11 | Java 21 |
|---|---|---|
|
|
|
| Feature | One-Line Interview Answer |
|---|---|
| Lambda | Concise implementation of a functional interface. |
| Functional Interface | Interface with one abstract method. |
| Stream | Declarative pipeline for processing data. |
| Optional | Container for a possibly absent value. |
| Method Reference | Compact syntax for referring to an existing method. |
| Default Method | Interface method with an implementation. |
| CompletableFuture | API for composing asynchronous computations. |
| java.time | Modern immutable date/time API. |
| Collectors | Utility methods for reducing/collecting stream results. |