Java 8+ Concurrency & Modern Java – Quick Reference

1. Java 8 Features – Detailed Quick Reference

FeatureConceptSmall ExampleKey Point
Lambda ExpressionsConcise way to represent a function.(a, b) -> a + bWorks with functional interfaces.
Functional InterfacesInterface with exactly one abstract method.Predicate<Integer> p = n -> n > 10;Common types: Function, BiFunction, Consumer, BiConsumer, Supplier, Predicate, BiPredicate, UnaryOperator, BinaryOperator.
Method ReferencesShort form of a lambda that calls an existing method.names.forEach(System.out::println);Forms include static, instance and constructor references.
Default MethodsInterface can contain an implementation.default void log(){...}Allows interfaces to evolve without forcing every implementation to add the method.
Static Methods in InterfacesUtility methods can belong to an interface.MyUtil.validate()Called using the interface name.
Stream APIDeclarative processing of collections.list.stream().filter(x -> x > 10).toList()Intermediate operations are lazy; terminal operation triggers processing.
Date & Time APIModern java.time API.LocalDate.now()Immutable and generally thread-safe date/time types.
OptionalContainer 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 EngineJava 8 JavaScript execution engine.new ScriptEngineManager().getEngineByName("nashorn")Java 8 feature shown here; later Java releases removed Nashorn.
Parallel StreamsStream processing using parallel execution.list.parallelStream().map(...)Useful only when parallel execution actually benefits the workload.
CompletableFutureAsynchronous computation and composition.CompletableFuture.supplyAsync(() -> load())Supports chaining, combining, exception handling and async workflows.
Collectors UtilityCollect/reduce stream results.Collectors.toList(), groupingBy()Common for converting streams into collections, maps and grouped results.

2. Functional Interfaces

InterfaceInputOutputExample
Function<T,R>1Rx -> x * 2
BiFunction<T,U,R>2R(a,b) -> a + b
Consumer<T>1voidx -> System.out.println(x)
BiConsumer<T,U>2void(k,v) -> System.out.println(k+v)
Supplier<T>0T() -> "Hello"
Predicate<T>1booleanx -> x > 10
BiPredicate<T,U>2boolean(a,b) -> a.equals(b)
UnaryOperator<T>1Tx -> x + 1
BinaryOperator<T>2T(a,b) -> a + b

3. Stream Operations

CategoryOperations / APIExample
Intermediate operationsfilter, map, flatMap, distinct, sorted, limit, skip, peeklist.stream().filter(x -> x > 10).map(x -> x * 2).collect(Collectors.toList())
Terminal operationscollect, forEach, count, anyMatch, allMatch, noneMatch, findFirst, findAny, reducelist.stream().filter(x -> x > 10).count()

4. Java 8 Map Enhancements

MethodSource-listed operationSmall Example
forEachIterate over Map entries.map.forEach((k,v) -> System.out.println(k + "=" + v));
getOrDefaultGet a value or a default value.map.getOrDefault("A", 0)
putIfAbsentPut a value when absent.map.putIfAbsent("A", 1)
computeIfAbsentCompute a value when absent.map.computeIfAbsent("A", k -> 100)
computeIfPresentCompute a value when present.map.computeIfPresent("A", (k,v) -> v + 1)
computeCompute a new value.map.compute("A", (k,v) -> v == null ? 1 : v + 1)
mergeMerge a value with the existing value.map.merge("A", 1, Integer::sum)
replaceReplace an existing value.map.replace("A", 10)
removeRemove an entry.map.remove("A")

5. Java 8 Small Examples

Lambda
List<String> names =
    Arrays.asList("A","B");

names.forEach(n ->
    System.out.println(n));
Stream
List<Integer> result =
    numbers.stream()
           .filter(n -> n > 10)
           .map(n -> n * 2)
           .collect(Collectors.toList());
Optional
String value =
    Optional.ofNullable(name)
            .orElse("Unknown");
Method Reference
names.forEach(
    System.out::println);
Grouping
Map<String,List<User>> grouped =
    users.stream()
         .collect(Collectors.groupingBy(
             User::getDepartment));
Reduce
int total =
    numbers.stream()
           .reduce(0, Integer::sum);

6. Asynchronous Programming & CompletableFuture

Core idea: CompletableFuture represents a result that may become available later. It allows asynchronous tasks to be chained, combined and handled without manually managing threads.
ConceptAPIPurposeExample
Create async tasksupplyAsyncRun a task that returns a result.CompletableFuture.supplyAsync(() -> getUser())
Create async void taskrunAsyncRun a task without a result.CompletableFuture.runAsync(() -> save())
Transform resultthenApplyTransform the previous result.future.thenApply(User::getName)
Chain another async taskthenComposeFlatten dependent async operations.user.thenCompose(u -> loadOrders(u.id()))
Combine independent tasksthenCombineCombine results of two futures.a.thenCombine(b, (x,y) -> x + y)
Run after completionthenAcceptConsume result without returning a value.future.thenAccept(System.out::println)
Completion actionwhenCompleteObserve result or exception.future.whenComplete((r,e) -> log(r,e))
Exception fallbackexceptionallyReturn fallback after failure.future.exceptionally(e -> "FAILED")
Exception handlinghandleHandle success and failure and produce a result.future.handle((r,e) -> e == null ? r : fallback)
Wait for allallOfComplete when all futures complete.CompletableFuture.allOf(a,b,c)
Wait for firstanyOfComplete when any future completes.CompletableFuture.anyOf(a,b)
Get resultjoinWait and return result; wraps failure in CompletionException.String x = future.join()

7. CompletableFuture Example

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;
    });

8. thenApply vs thenCompose vs thenCombine

APIUse WhenSimple Meaning
thenApplyNext step is a synchronous transformation.Future → Future
thenComposeNext step itself returns a CompletableFuture and depends on previous result.Future<Future<T>> → Future<T>
thenCombineTwo independent futures need to be combined.Future A + Future B → combined Future

9. Virtual Threads

Concept: Virtual threads are lightweight threads managed by the Java runtime. They are designed to make thread-per-request style programming practical for applications with many blocking I/O operations.
TopicQuick ReferenceExample
Create a virtual threadUse Thread.startVirtualThread.Thread.startVirtualThread(() -> service.call());
BuilderUse Thread.ofVirtual().Thread.ofVirtual().start(task);
ExecutorUse a virtual-thread-per-task executor.Executors.newVirtualThreadPerTaskExecutor()
Best fitLarge numbers of mostly blocking I/O tasks.HTTP calls, database calls, file/network I/O.
Not a magic CPU boostCPU-heavy work is still limited by available CPU resources.Do not expect unlimited CPU throughput.
Thread-local considerationsThread-local usage should be reviewed when creating very large numbers of threads.Prefer scoped/context approaches where appropriate.

10. Virtual Thread Example

try (var executor =
         Executors.newVirtualThreadPerTaskExecutor()) {

    Future<String> future =
        executor.submit(() -> callRemoteService());

    System.out.println(future.get());
}

11. Platform Thread vs Virtual Thread

AspectPlatform ThreadVirtual Thread
Managed byOperating system/JVM platform thread mapping.Java runtime scheduler.
CostRelatively heavier.Much lighter.
ScaleLimited by thread/memory overhead.Can support very large numbers of concurrent tasks.
Best forGeneral tasks and CPU-oriented execution.High-concurrency blocking I/O workloads.

12. Java Concurrency

ConceptPurposeExampleKey Point
ThreadUnit of execution.new Thread(task).start()Direct thread management.
ExecutorServiceManage a pool of worker threads.Executors.newFixedThreadPool(10)Separates task submission from thread management.
CallableTask that returns a value and can throw checked exceptions.executor.submit(() -> calculate())Returns a Future.
FutureRepresents a pending result.future.get()Can block waiting for completion.
synchronizedMutual exclusion and visibility.synchronized(lock){...}Only one thread at a time enters the synchronized region for the same monitor.
LockExplicit locking control.ReentrantLockProvides features such as tryLock and interruptible locking.
volatileVisibility of a variable across threads.volatile boolean running;Does not make compound operations such as count++ atomic.
ConcurrentHashMapThread-safe concurrent map.new ConcurrentHashMap<>()Designed for concurrent access.
BlockingQueueThread-safe producer/consumer queue.new LinkedBlockingQueue<>()Operations can wait for capacity/items.
CountDownLatchWait until a count reaches zero.latch.await()One-shot synchronization aid.
CyclicBarrierAllow threads to meet at a common barrier.barrier.await()Reusable barrier.
SemaphoreLimit concurrent access to a resource.semaphore.acquire()Useful for controlling concurrency.

13. synchronized vs Lock vs volatile

FeaturesynchronizedLockvolatile
Mutual exclusionYesYesNo
VisibilityYesYesYes
Flexible lock controlLimitedYesNo
tryLockNoYesNo
Compound operation atomicityCan provide it when protectedCan provide it when protectedNo

14. Atomic Classes

Concept: Atomic classes provide lock-free/thread-safe operations for individual variables using atomic CPU/JVM mechanisms. They are useful when a simple shared-state operation does not require a full lock.
ClassPurposeExample
AtomicIntegerAtomic integer operations.AtomicInteger count = new AtomicInteger(0); count.incrementAndGet();
AtomicLongAtomic long operations.sequence.incrementAndGet()
AtomicBooleanAtomic boolean state.started.compareAndSet(false, true)
AtomicReference<T>Atomic reference updates.ref.compareAndSet(oldValue, newValue)
LongAdderHigh-throughput counters under contention.counter.increment()

15. Atomic Operations

OperationMeaningExample
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)

16. Atomic vs synchronized

AspectAtomicsynchronized
ScopeUsually a single variable/state operation.Can protect a larger critical section.
MechanismAtomic/compare-and-set style operations.Monitor locking.
Best fitCounters, flags, simple state transitions.Multiple related variables/invariants and larger critical sections.

17. Immutable Classes

Concept: An immutable object cannot change after it is created. Its state is fixed for its lifetime.
RuleHow to Implement
Make class finalPrevent subclassing that could introduce mutable behavior.
Make fields private and finalState is assigned once.
No settersDo not expose state-changing methods.
Initialize through constructorValidate and establish complete state during construction.
Defensive copiesCopy mutable objects on input and output.
Return immutable values where possibleAvoid exposing mutable internal state.

18. Immutable Class Example

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;
    }
}

19. Mutable vs Immutable

AspectMutableImmutable
State after constructionCan change.Cannot change.
Thread sharingRequires careful synchronization when shared.Generally safer to share because state cannot change.
ExamplesArrayList, StringBuilderString, Integer, LocalDate
DesignSetters/mutating methods may exist.Final state, no setters, defensive copies when needed.

20. Most Important Interview Questions & Answers

QuestionAnswer
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.

21. Quick Interview Comparison

TopicRemember This
CompletableFutureAsync composition: chain, combine and handle failures.
Virtual ThreadLightweight concurrency, especially useful for blocking I/O.
synchronizedMutual exclusion + visibility.
volatileVisibility/order, not compound-operation atomicity.
AtomicIntegerAtomic counter/state updates.
ImmutableState cannot change after construction.
ExecutorServiceManage task execution and worker lifecycle.
ConcurrentHashMapConcurrent access to map data.

22. Java 8, Java 11 & Java 21 – Feature Snapshot

Java 8Java 11Java 21
  • Lambda Expressions
  • Functional Interfaces
  • Method References
  • Default Methods in Interfaces
  • Static Methods in Interfaces
  • Stream API
  • Date and Time API
  • Optional Class
  • Nashorn JavaScript Engine
  • Parallel Streams
  • CompletableFuture
  • Collectors Utility
  • Local-Variable Syntax for Lambda Parameters
  • New String Methods
  • New File Methods
  • HTTP Client (Standardized)
  • Collection Enhancements
  • Launch Single-File Programs
  • Record Patterns
  • Pattern Matching for switch
  • Virtual Threads
  • Sequenced Collections
  • String Templates
  • Scoped Values
  • Unnamed Patterns and Variables
  • Unnamed Classes and Instance Main Methods
  • Foreign Function & Memory API
  • Structured Concurrency

23. Java 8 Features – Quick Interview Map

FeatureOne-Line Interview Answer
LambdaConcise implementation of a functional interface.
Functional InterfaceInterface with one abstract method.
StreamDeclarative pipeline for processing data.
OptionalContainer for a possibly absent value.
Method ReferenceCompact syntax for referring to an existing method.
Default MethodInterface method with an implementation.
CompletableFutureAPI for composing asynchronous computations.
java.timeModern immutable date/time API.
CollectorsUtility methods for reducing/collecting stream results.