Backend Java and Spring Framework Essentials

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

During a backend engineering screen focused on Java and the Spring ecosystem, address each of the following foundational topics:

  1. Sequential collections: Contrast ArrayList and LinkedList across backing memory layout, asymptotic runtime for indexed reads, insertions, and removals, and suitable workloads.
  2. Object-oriented design rules: Walk through all five SOLID principles and pair each rule with a brief code or domain scenario.
  3. Hashed collections and concurrent maps:
    • Contrast Hashtable with HashSet on element vs. key-value storage, null acceptance, and locking behavior.
    • Describe ConcurrentHashMap, how its internal concurrency model improves upon HashMap and Hashtable, and when backend services rely on it.
  4. Character sequences and immutable types:
    • Contrast String, StringBuilder, and StringBuffer across mutability, multi-threaded safety, and performance trade-offs.
    • Define what makes a Java object immutable, explain its engineering benefits, and list the concrete rules required to build a tamper-proof immutable class.
  5. Thread-safety primitives:
    • Explain Java's volatile modifier, the visibility and ordering guarantees it establishes, and which concurrency bugs it cannot prevent.
    • Explain monitor locking with synchronized, how mutual exclusion and memory flushing work together, and its contention or liveness costs.
    • Explain the java.util.concurrent.atomic toolkit—including AtomicInteger and AtomicReference—and how hardware compare-and-swap enables non-blocking updates.
  6. Exception management: Distinguish checked from unchecked exceptions on the JVM and outline production-ready habits for resource cleanup, cause preservation, and boundary handling.
  7. Spring container and annotations:
    • Define Inversion of Control (IoC) and Dependency Injection (DI) within Spring and illustrate collaborator wiring.
    • Describe Spring's proxy-based Aspect-Oriented Programming (AOP) model along with cross-cutting concerns like declarative transactions and audit logging.
    • Outline how Spring beans are registered (stereotype scanning, Java config classes, or legacy XML), instantiated, lifecycle-managed, and injected.
    • Differentiate @Component, @Service, and @Repository—both their shared container behavior and their layer-specific semantics.
    • Summarize core web, wiring, and configuration annotations including @Controller, @RestController, @Autowired, @Qualifier, @Configuration, @Bean, and @Transactional.
  8. Declarative collection pipelines: Demonstrate functional collection processing with the Java Stream API—covering lazy filtering, projection, grouping, and numeric aggregation—through practical snippets.

Scope & Expectations

  • Ground collection and string comparisons in concrete memory layouts, CPU cache behavior, and asymptotic costs rather than memorized rules alone.
  • Clearly separate memory visibility from compound atomicity when comparing volatile, synchronized, AtomicInteger/AtomicReference, and ConcurrentHashMap operations.
  • Connect Spring container mechanics—constructor injection, singleton lifecycle, proxy interception limits, and transaction rollback defaults—to real production failure modes and clean code examples.

Step-by-step walkthrough

  1. Collections: ArrayList versus LinkedList

    Both ArrayList and LinkedList implement Java's ordered List<E> interface, but their memory layouts could not be more different:

    ArrayList: one contiguous Object[] array on the heap (default initial capacity = 10 on first add)
      [ ref0 | ref1 | ref2 | ref3 | unused | unused ]   <- 4 bytes per slot (compressed OOPs), grows 1.5x when full
    
    LinkedList: scattered doubly linked Node objects (24 bytes per Node wrapper + pointers)
      first -> [prev|item0|next] <-> [prev|item1|next] <-> [prev|item2|next] <- last
    
    • ArrayList stores elements in a resizable Object[] plus a size field. Appending at the end is amortized O(1) (meaning almost every add writes into a free slot in O(1) time, and the occasional 1.5x array copy spreads out to a constant average cost per element). Reading get(i) jumps straight to slot i in O(1), and CPU cache locality (adjacent elements sitting in the same hardware cache line) makes sequential scans very fast.
    • LinkedList stores each element in a heap-allocated Node { item, next, prev } and implements both List and Deque. Adding or removing at the head, tail, or an already-positioned ListIterator updates two pointers in O(1), but get(i) must walk min(i, n - 1 - i) pointers from the nearer end (O(n)), missing CPU caches along the way.
    Operation                         ArrayList                     LinkedList
    --------------------------------  ----------------------------  ------------------------------------
    get(i), set(i, x)                 O(1) direct index             O(n) pointer walk from nearer end
    add(x) at tail                    O(1) amortized                O(1)
    add(0, x), remove(0) at head      O(n) shifts all n elements    O(1) updates head pointers
    add(i, x), remove(i) in middle    O(n - i) array shift          O(min(i, n - i)) walk + O(1) splice
    insert/remove via ListIterator    O(n) array shift              O(1) pointer splice
    contains(x), indexOf(x)           O(n)                          O(n)
    Per-element wrapper overhead      ~4-byte reference slot        24-byte Node object (6x larger)
    

    Worked numeric comparison: Inserting 100,000 items one by one at index 0 of an ArrayList shifts 0 + 1 + 2 + ... + 99,999 = 4,999,950,000 references (O(n^2) total), whereas a LinkedList performs 100,000 constant-time pointer updates. Yet for random reads, iteration, or appending, ArrayList wins decisively.

    Rule of thumb: Default to ArrayList for general lists, use ArrayDeque (a circular resizable array) for queues and stacks, and reserve LinkedList for rare workloads that repeatedly splice elements mid-list through an active ListIterator.

  2. Object-oriented design: the five SOLID principles

    SOLID is a set of five class-design guidelines that keep growing systems modular, testable, and safe to extend without breaking existing callers:

    • S — Single Responsibility Principle (SRP): A class should have only one reason to change. An Invoice class that calculates taxes, formats PDFs, and runs SQL queries couples accounting rules, UI layout, and database schemas; split it into InvoiceCalculator, InvoicePdfRenderer, and InvoiceRepository.
    • O — Open/Closed Principle (OCP): Modules should be open for extension (new behavior) but closed for modification (no surgery on working code). Replace a growing switch (customerTier) inside checkout() with a DiscountPolicy interface so adding a "VIP" rule is one new class, not an edit to checkout().
    • L — Liskov Substitution Principle (LSP): Any subtype must honor the behavioral contract promised by its base type so callers never get surprises. Square extends Rectangle violates LSP when calling rect.setWidth(5); rect.setHeight(2); silently overwrites width to 2 and yields area 4 instead of 10.
    • I — Interface Segregation Principle (ISP): Callers should not be forced to depend on methods they never use. Split a bloated Machine { print(); scan(); fax(); } interface into Printer, Scanner, and Fax so a basic printer never stubs fax() with UnsupportedOperationException.
    • D — Dependency Inversion Principle (DIP): High-level business policy should depend on interfaces (abstractions), not low-level vendor classes. OrderService talks to PaymentGateway, and the concrete StripeGateway is supplied from outside.
    interface DiscountPolicy {                          // O: add new discount rules as new classes
        BigDecimal apply(BigDecimal subtotal);
    }
    
    interface PaymentGateway {                          // D: business logic depends on an abstraction
        Receipt charge(String customerId, BigDecimal total);
    }
    
    class OrderService {
        private final PaymentGateway gateway;
        private final DiscountPolicy discount;
    
        OrderService(PaymentGateway gateway, DiscountPolicy discount) {
            this.gateway = gateway;
            this.discount = discount;
        }
    
        Receipt checkout(String customerId, BigDecimal subtotal) {
            BigDecimal finalAmount = discount.apply(subtotal);
            return gateway.charge(customerId, finalAmount);
        }
    }
    
  3. Hash-based collections and ConcurrentHashMap

    Java's hash collections map keys into array slots (buckets) using key.hashCode() and resolve hash collisions (two distinct keys landing in the same bucket) using key.equals(), achieving O(1) average lookup, insertion, and deletion:

    Collection          What it stores        Null support                  Thread safety
    ------------------  --------------------  ----------------------------  -----------------------------------------
    Hashtable           key -> value pairs    No null key, no null value    Coarse: locks entire table on every call
    HashSet             unique elements       One null element allowed      Not thread-safe
    HashMap             key -> value pairs    One null key, any null values Not thread-safe
    ConcurrentHashMap   key -> value pairs    No null key, no null value    Fine-grained: lock-free reads, bucket locks
    

    Internal mechanics:

    • HashSet<E> does not have its own hashing engine: internally it wraps a HashMap<E, Object> where your elements are the keys and every key points to the same static dummy PRESENT object.
    • Hashtable is a legacy Java 1.0 class whose methods are all synchronized on this, turning the entire map into a single-file bottleneck under multi-threaded traffic.
    • HashMap (default capacity 16, load factor 0.75, resizing past 16 * 0.75 = 12 entries) stores colliding entries in a linked list per bucket, and once a bucket exceeds 8 nodes (provided table capacity is at least 64; smaller tables simply double in size), it converts that bucket into a balanced red-black tree to bound worst-case collision lookups to O(log n).
    • ConcurrentHashMap is built for high-throughput concurrent access:
      1. Reads (get) are lock-free and rely on volatile reads.
      2. Writes into an empty bucket use an atomic CAS (Compare-And-Swap, a single CPU instruction that updates a memory slot only if it still holds the expected value), and writes into a populated bucket lock only that bucket's head node (Java 8+), letting threads on other buckets run in parallel.
      3. Iterators are weakly consistent: they never throw ConcurrentModificationException and reflect updates on a best-effort basis.
      4. null keys and values are forbidden because in concurrent code map.get(k) == null would be ambiguous (you cannot safely call containsKey(k) afterward without another thread changing the entry in between).

    Even with ConcurrentHashMap, combining separate get and put calls creates a check-then-act race—always use single-call atomic methods like merge, compute, or computeIfAbsent:

    ConcurrentHashMap<String, Integer> wordCounts = new ConcurrentHashMap<>();
    
    // BROKEN under concurrency: two threads read 5 at the same time and both write 6 (one increment lost)
    wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);
    
    // SAFE and atomic: per-key read-modify-write runs atomically inside one bucket lock
    wordCounts.merge(word, 1, Integer::sum);
    
  4. Strings, builders, and designing immutable classes

    Type            Mutable?   Thread-safe?                 When to choose it
    --------------  ---------  ---------------------------  ------------------------------------------------
    String          No         Yes (state never changes)    Map keys, constants, DTO fields, method args
    StringBuilder   Yes        No                           Building text in loops inside a single thread
    StringBuffer    Yes        Yes (synchronized methods)   Legacy APIs only; synchronization adds overhead
    

    Why loop concatenation with String is O(n^2): Because String is immutable (its contents can never change once constructed), running s += ch inside a 10,000-iteration loop allocates 10,000 separate String objects and performs 1 + 2 + ... + 10,000 = 50,005,000 character writes as all previous characters are re-copied every single step. StringBuilder mutates a resizable backing array in place (O(n) total work).

    Why immutability is valuable across backend code:

    • Automatic thread safety: Multiple threads can read an immutable object concurrently with zero locks and zero risk of torn or half-updated state.
    • Corruption-proof map keys: Because fields never mutate, hashCode() never shifts after insertion into a HashMap or HashSet.
    • Safe sharing and caching: Instances can be cached (like the JVM string pool or Integer cache -128..127) and passed across layers without worrying a callee will mutate them.

    Four rules to implement a truly immutable class in Java:

    1. Declare the class final so subclasses cannot override getters to expose mutable state.
    2. Mark every field private final and assign all of them in the constructor.
    3. Expose no setter methods; return a brand-new instance from "with..." methods when deriving a modified copy.
    4. Make defensive copies (independent copies of mutable inputs like List or Date) on the way into the constructor and never return mutable internal collections directly (List.copyOf makes an unmodifiable copy and rejects null elements):
    public final class Order {
        private final String id;
        private final List<String> items;
        private final Instant createdAt;          // java.time.Instant is itself immutable
    
        public Order(String id, List<String> items, Instant createdAt) {
            this.id = Objects.requireNonNull(id);
            this.items = List.copyOf(items);      // caller mutating their list later cannot affect us
            this.createdAt = Objects.requireNonNull(createdAt);
        }
    
        public String id() { return id; }
        public List<String> items() { return items; }   // unmodifiable view: items().add(...) throws
        public Instant createdAt() { return createdAt; }
    
        public Order withAddedItem(String item) {
            List<String> updated = new ArrayList<>(items);
            updated.add(Objects.requireNonNull(item));
            return new Order(id, updated, createdAt);
        }
    }
    

    Java 16+ record Order(String id, List<String> items, Instant createdAt) generates final fields and accessors automatically, but records are only shallowly immutable—you still add items = List.copyOf(items); in a compact constructor to protect mutable collections.

  5. Concurrency primitives: volatile, synchronized, and atomics

    Thread bugs come from two distinct hazards: visibility (Thread A updates a variable in a CPU register/cache, and Thread B keeps reading a stale value) and atomicity (a multi-step read-modify-write like count++ gets interleaved across threads):

    Why volatile alone CANNOT make count++ thread-safe (initial count = 10):
      Thread 1: reads count (10)  ---> computes 10 + 1 = 11 ---> writes 11
      Thread 2:      reads count (10) ---> computes 10 + 1 = 11 ---> writes 11   (result is 11, not 12!)
    
    • volatile (visibility + ordering, NOT compound atomicity): Establishes a happens-before relationship (a Java Memory Model guarantee that every write before a volatile store becomes visible to any thread that subsequently reads that volatile variable, preventing compiler/CPU caching and instruction reordering). It also guarantees atomic 64-bit reads/writes for long and double. Use volatile for one-writer status flags (volatile boolean running = true;), never for count++ or multi-field invariants.
    • synchronized (mutual exclusion + visibility): Every Java object carries an intrinsic lock (monitor). Entering synchronized (lock) lets only one thread inside at a time, and unlocking flushes all writes to main memory before the next thread acquires the same lock. Locks are reentrant (a thread already holding lock can call another method synchronized on lock without deadlocking itself). Trade-offs: contending threads block (parking OS threads if held long), acquiring two locks in opposite orders causes deadlock, and intrinsic monitors cannot time out—use ReentrantLock when you need tryLock(timeout) or interruptible waits.
    • java.util.concurrent.atomic (lock-free single-variable atomicity): Classes like AtomicInteger and AtomicReference<V> rely on hardware CAS (compareAndSet(expected, next)). To increment, AtomicInteger reads current value v, attempts compareAndSet(v, v + 1), and retries immediately in a tiny loop if another thread beat it (or executes a single hardware lock xadd instruction on x86)—no thread ever suspends. Pair AtomicReference with an immutable state object to swap multiple related fields atomically, use AtomicStampedReference when you must guard against the ABA problem (a value changing A -> B -> A behind a thread's back), and prefer LongAdder over AtomicLong when dozens of threads hammer one counter simultaneously (it stripes increments across cells and sums them on read).
    class SafeMetrics {
        private volatile boolean acceptingTraffic = true;          // single boolean flag: volatile suffices
        private final AtomicInteger activeRequests = new AtomicInteger(0);
        private final Object balanceLock = new Object();
        private long checkingCents = 1_000;
        private long savingsCents = 5_000;
    
        void closeGate() { acceptingTraffic = false; }
    
        void onRequestStart() { activeRequests.incrementAndGet(); } // lock-free exact counter
    
        void transferToSavings(long cents) {                        // 2-variable invariant needs a lock
            synchronized (balanceLock) {
                checkingCents -= cents;
                savingsCents += cents;
            }
        }
    }
    
  6. Exception handling: checked vs. unchecked and production habits

    Throwable
    ├── Error                  JVM-level failures (OutOfMemoryError, StackOverflowError) -> unchecked, never catch
    └── Exception              Checked by compiler (IOException, SQLException) -> must catch or declare `throws`
        └── RuntimeException   Unchecked bugs/violations (NullPointerException, IllegalArgumentException,
                               IllegalStateException) -> no `throws` clause required
    
    • Checked exceptions (Exception subclasses outside RuntimeException) represent anticipated external failures a caller can meaningfully recover from, such as a missing file or network timeout. The compiler requires catching or declaring them.
    • Unchecked exceptions (RuntimeException subclasses) signal programming mistakes (null arguments, index out of bounds, illegal state) or infrastructure failures wrapped at architectural boundaries (for example, Spring's unchecked DataAccessException).

    Production best practices:

    1. Catch only when you can recover or add context—otherwise let exceptions bubble up to a central handler.
    2. Never swallow exceptions silently (catch (Exception ignored) {} hides root causes).
    3. Preserve the causal chain when wrapping (throw new OrderPersistenceException("Order " + id, cause)), keeping the original stack trace intact.
    4. Always close resources with try-with-resources for any AutoCloseable (files, sockets, JDBC connections) so close() runs deterministically even if an exception occurs.
    5. Log once at the handling boundary rather than logging and rethrowing at every layer, and map domain exceptions to clean HTTP status codes centrally via Spring's @RestControllerAdvice.
    6. Remember Spring's @Transactional rollback rule: By default, Spring rolls back database transactions on unchecked RuntimeException and Error, not on checked exceptions unless you specify @Transactional(rollbackFor = Exception.class).
    public AppConfig loadConfig(Path path) {
        try (BufferedReader reader = Files.newBufferedReader(path)) {     // auto-closed on exit
            return AppConfig.parse(reader);
        } catch (NoSuchFileException e) {
            return AppConfig.defaultConfig();                             // genuine local recovery
        } catch (IOException e) {
            throw new UncheckedIOException("Failed reading " + path, e);  // preserve original cause
        }
    }
    
    @RestControllerAdvice
    class GlobalExceptionHandler {
        @ExceptionHandler(OrderNotFoundException.class)
        ResponseEntity<String> handleNotFound(OrderNotFoundException ex) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
        }
    }
    
  7. Spring core: IoC, DI, bean lifecycle, AOP, and annotations

    With Inversion of Control (IoC), your classes stop calling new to assemble their own collaborators; instead, Spring's ApplicationContext container instantiates managed objects called beans, wires them together via Dependency Injection (DI), and manages their lifecycle.

    • Three ways to register beans: Component scanning on stereotype annotations (@Component, @Service, @Repository), explicit @Bean factory methods inside @Configuration classes (ideal for third-party or JDK classes like Clock or HttpClient), and legacy XML definitions.
    • Constructor injection over field/setter injection: A single constructor needs no @Autowired annotation (Spring 4.3+), allows private final fields so beans are never half-initialized, fails fast on circular dependencies, and lets unit tests instantiate new OrderService(fakeGateway) with zero Spring startup cost. Use @Qualifier("stripe") or @Primary when multiple beans implement the same interface.
    Spring Bean Lifecycle (default scope = singleton, one shared instance per ApplicationContext):
      Instantiate -> Inject dependencies -> BeanPostProcessors (before init) -> @PostConstruct init
      -> BeanPostProcessors (after init: wraps bean in AOP proxy if needed) -> Ready to serve requests
      -> On context shutdown: @PreDestroy cleanup (skipped for prototype-scoped beans)
    
    • Aspect-Oriented Programming (AOP): Extracts cross-cutting concerns—transactions (@Transactional), security checks, metrics, caching (@Cacheable)—out of business methods. Spring AOP wraps the target bean inside a runtime proxy (a generated wrapper object using JDK dynamic proxies or CGLIB subclasses) that intercepts external calls:
    External caller ---> [Spring AOP Proxy: opens DB tx] ---> [OrderService target: runs save()]
    Internal call:       OrderService.placeOrder() calls this.save() ---> hits target directly (SKIPS proxy!)
    

    Because this.save() bypasses the proxy wrapper, self-invoking @Transactional or @Cacheable methods inside the same class silently skips the advice, and private or final methods cannot be overridden by CGLIB proxies.

    • Stereotypes and essential annotations:
      • @Component: general-purpose Spring-managed bean.
      • @Service: semantic marker for the business-logic layer (meta-annotated with @Component).
      • @Repository: data-access layer marker; additionally activates persistence exception translation (converting vendor JPA/JDBC exceptions into Spring's unified DataAccessException hierarchy).
      • @Controller vs. @RestController: @Controller resolves view templates; @RestController combines @Controller + @ResponseBody to serialize return values directly to JSON/HTTP bodies.
      • Configuration & web staples: @Configuration (proxied by CGLIB so inter-@Bean calls return the same singleton, unlike @Bean inside a plain @Component), @Value, @ConfigurationProperties, @Profile, @Scope, @GetMapping / @PostMapping, @PathVariable, @RequestParam, @RequestBody, @Valid, and @Transactional.
  8. Functional collection processing with the Stream API

    Java's Stream<T> API expresses declarative data pipelines in three parts: a source (orders.stream()), zero or more lazy intermediate operations (filter, map, flatMap, distinct, sorted), and a single terminal operation (toList(), collect, sum, reduce, anyMatch) that triggers execution:

    orders.stream()  -->  filter(PAID)  -->  mapToDouble(amount)  -->  sum()
       [Source]          [Lazy stage 1]        [Lazy stage 2]        [Terminal: pulls elements 1-by-1]
    

    Key rules: nothing executes until the terminal step runs; stateless stages fuse into a single pass without creating intermediate lists (while stateful stages like sorted must buffer); a stream can be consumed only once; and lambdas inside streams should remain stateless and side-effect-free.

    record Order(String customer, String status, double amount, List<String> items) {}
    
    List<Order> orders = List.of(
        new Order("alice", "PAID", 30.0, List.of("book")),
        new Order("bob",   "PAID", 20.0, List.of("pen", "ink")),
        new Order("alice", "CANCELLED", 50.0, List.of("lamp")),
        new Order("alice", "PAID", 15.0, List.of("pen"))
    );
    
    // 1. Filter + map + deduplicate into an unmodifiable List (Java 16+)
    List<String> paidCustomers = orders.stream()
        .filter(o -> "PAID".equals(o.status()))
        .map(Order::customer)
        .distinct()
        .toList();                                              // ["alice", "bob"]
    
    // 2. Primitive stream avoids Double boxing overhead
    double paidRevenue = orders.stream()
        .filter(o -> "PAID".equals(o.status()))
        .mapToDouble(Order::amount)
        .sum();                                                 // 30.0 + 20.0 + 15.0 = 65.0
    
    // 3. Group and aggregate per key
    Map<String, Double> spendByCustomer = orders.stream()
        .filter(o -> "PAID".equals(o.status()))
        .collect(Collectors.groupingBy(
            Order::customer,
            Collectors.summingDouble(Order::amount)
        ));                                                     // {alice=45.0, bob=20.0}
    
    // 4. Flatten nested collections with flatMap
    Set<String> uniqueItems = orders.stream()
        .flatMap(o -> o.items().stream())
        .collect(Collectors.toSet());                           // {book, pen, ink, lamp}
    
    // 5. Build a Map safely when keys repeat (3rd arg resolves collisions; 2-arg toMap throws!)
    Map<String, Double> maxOrderByCustomer = orders.stream()
        .collect(Collectors.toMap(Order::customer, Order::amount, Math::max));
                                                                // {alice=50.0, bob=20.0}
    

    Avoid sprinkling parallelStream() indiscriminately: it shares the JVM-wide ForkJoinPool.commonPool(), so small collections lose time to thread coordination and any blocking I/O inside a parallel stream can stall unrelated parallel tasks across the entire process.

Intuition & how it works

Think of a backend Java and Spring service as a busy multi-lane fulfillment warehouse. Data structures choose the physical shelf layout (ArrayList packs items side by side on one long shelf for instant index lookup, while ConcurrentHashMap assigns separate bins by key hash so workers in different aisles rarely block each other). Immutability (String and final value objects with defensive copies) seals packages at creation time so dozens of request threads can inspect them simultaneously without locks, while concurrency primitives (volatile, synchronized, AtomicInteger) coordinate the few pieces of state that must change. Above individual classes, SOLID principles keep business logic decoupled behind clean interfaces, and Spring's IoC container (Inversion of Control, where the framework constructs and wires objects instead of your code calling new) acts as the floor manager—creating singleton beans (single shared service instances) at startup, injecting dependencies via constructors, and wrapping entry doors with AOP proxies (runtime wrapper objects that run transactions or logging around business calls).

Relying on surface-level syntax without knowing these mechanics causes classic production failures. Appending characters with s += c in a 10,000-step loop or inserting 100,000 items at index 0 of an ArrayList silently turns linear work into tens of millions or billions of O(n^2) array copies. Under multi-threaded traffic, marking a counter volatile still loses count++ updates because read-add-write is three separate steps, while calling map.get(k) followed by map.put(k, v + 1) on a ConcurrentHashMap still races across the two calls. In Spring, calling a @Transactional helper via this.save() inside the same class skips the proxy wrapper completely, and throwing a checked exception commits half-written database state unless rollbackFor is set.

Walk through how these fundamentals fit together during one POST /orders request for "alice" buying items [30.0, 15.0]: 1. Immutable boundary + DI: @RestController deserializes the payload into an immutable Order (final fields, List.copyOf(items)) and calls constructor-injected OrderService. 2. AOP proxy + Stream pipeline: The call enters Spring's CGLIB proxy, which opens a database transaction before delegating to OrderService; inside, a lazy stream pipeline (items.stream().filter(...).mapToDouble(...).sum()) computes 45.0 in a single pass with zero intermediate list allocations. 3. Lock-free concurrent state: A shared in-memory metric map records the sale via revenueByUser.merge("alice", 45.0, Double::sum)—locking only "alice"'s hash bucket while concurrent readers run lock-free. 4. Centralized exception handling: If inventory fails with an unchecked InsufficientStockException, the proxy rolls back the transaction automatically and @RestControllerAdvice translates the exception into a single logged HTTP 409 Conflict response.

Key points

  • ArrayList vs. LinkedList: ArrayList uses a contiguous resizable Object[] (1.5x growth, O(1) random access, amortized O(1) tail append—meaning occasional resize copies average out to constant cost per add—and strong CPU cache locality); LinkedList uses doubly linked 24-byte Node wrappers (O(1) head/tail/iterator splice, O(n) index traversal). Default to ArrayList, and prefer ArrayDeque for queues and stacks.
  • SOLID principles: Single Responsibility (one reason to change), Open/Closed (extend via new implementations, not switch edits), Liskov Substitution (subtypes preserve base contracts), Interface Segregation (small focused interfaces), and Dependency Inversion (depend on injected abstractions).
  • Hash collections: All bucket entries via hashCode() and verify matches with equals(). HashSet wraps a HashMap using a shared dummy value; Hashtable locks the whole map on every call and forbids null; ConcurrentHashMap offers lock-free reads, per-bucket CAS/synchronized writes, atomic merge/compute methods, weakly consistent iterators (never throwing ConcurrentModificationException), and forbids nulls to keep get(k) == null unambiguous.
  • Strings and immutability: String is immutable and safe as a map key; StringBuilder mutates an internal buffer in O(n) for single-threaded loops; StringBuffer adds legacy method-level synchronization. Build immutable classes with final class, private final fields, no setters, and defensive copies (List.copyOf) on inputs and outputs.
  • Concurrency primitives: volatile guarantees happens-before visibility and ordering (writes before a volatile store are visible to later readers) without compound atomicity; synchronized provides reentrant mutual exclusion plus visibility at the cost of thread blocking; AtomicInteger / AtomicReference use CAS (Compare-And-Swap, a hardware instruction that updates a variable only if its value matches the expected snapshot) for non-blocking single-variable updates.
  • Exceptions: Checked exceptions cover recoverable external conditions (IOException); unchecked RuntimeExceptions cover bugs and unrecoverable faults. Use try-with-resources, never swallow exceptions, pass the original cause when wrapping, log once at the boundary, and note that Spring @Transactional rolls back only on unchecked exceptions by default.
  • Spring IoC, AOP, and stereotypes: Register beans via component scanning (@Component, @Service, @Repository, @RestController) or @Configuration + @Bean; prefer constructor injection; remember default bean scope is singleton (must be stateless/thread-safe); @Repository adds persistence exception translation; and Spring AOP wraps beans in proxies, so internal this.method() calls bypass @Transactional and @Cacheable.
  • Stream API: Pipelines connect a source, lazy stateless/stateful intermediate stages (filter, map, flatMap, sorted), and one single-use terminal operation (toList(), sum(), Collectors.groupingBy, 3-argument Collectors.toMap with merge function).

Common mistakes

  • Saying LinkedList middle insertion is O(1) unqualified: Splicing pointers at an existing ListIterator is O(1), but list.add(i, x) first walks min(i, n - i) nodes in O(n) time.
  • Assuming two calls on ConcurrentHashMap are atomic together: map.put(k, map.getOrDefault(k, 0) + 1) still loses updates under contention; use map.merge(k, 1, Integer::sum).
  • Using volatile for counters or multi-variable invariants: volatile int count; count++ still races between read and write, and two separate volatile fields cannot be updated together atomically.
  • Returning or storing caller-owned List/Date references in an "immutable" class: Without defensive copying (List.copyOf), external callers can mutate the object's state after construction.
  • Self-invoking @Transactional methods or throwing checked exceptions expecting rollback: Calling this.updateOrder() skips the Spring proxy, and throwing a checked IOException commits the transaction unless rollbackFor includes it.
  • Calling Collectors.toMap(keyFn, valFn) when duplicate keys can occur: The two-argument overload throws IllegalStateException on the first duplicate key; pass a merge function as the third argument.

Follow-up questions

  • What rules govern Java's equals and hashCode contract, and what happens if a HashMap key mutates after insertion? Java's contract requires that whenever a.equals(b) is true, a.hashCode() == b.hashCode() must also hold (unequal objects may still share a hash code, causing a collision handled via equals). Overriding equals without overriding hashCode makes logically equal objects hash to different buckets, so map.get(copyOfKey) returns null. Worse, if you mutate a field used by hashCode() after putting a key into a HashMap, the entry sits stranded in its original bucket while future lookups compute the new bucket—making the entry invisible to get and leaking it inside the map, which is why map keys should always be immutable.

  • Why is Spring's @Transactional annotation bypassed when one method calls another inside the same class, and how should you refactor it? Spring implements @Transactional using a runtime proxy wrapper around the bean: external callers invoke the proxy (which starts and commits the transaction), whereas calling this.methodB() inside methodA() invokes the raw Java this reference directly and bypasses the proxy completely. The cleanest fix is either extracting methodB into a separate focused collaborator bean injected via the constructor, or moving @Transactional onto the public entry method methodA if the whole unit of work belongs in one transaction. When fine-grained programmatic boundaries are needed inside a single method (for example, avoiding holding a DB connection during an external HTTP call), inject Spring's TransactionTemplate instead of relying on proxy interception.

  • Under what conditions does parallelStream improve throughput, and why can it degrade a backend web server? parallelStream() helps only when the collection is large (typically tens of thousands of items or more), per-element computation is CPU-heavy and completely independent, the data source splits cleanly in O(1) (ArrayList and arrays split cleanly; LinkedList and Stream.iterate split poorly), and lambdas touch zero shared mutable state. In backend web servers it frequently hurts performance because all parallel streams share ForkJoinPool.commonPool() (sized to CPU cores - 1): running blocking database or HTTP calls inside a parallel stream starves every other parallel task in the JVM, and on small lists thread-splitting and result-merging overhead easily outweighs the parallel speedup.

Follow-up questions

Similar questions

More Antra interview questions

All 4 Antra questions →