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:
- Sequential collections: Contrast
ArrayListandLinkedListacross backing memory layout, asymptotic runtime for indexed reads, insertions, and removals, and suitable workloads. - Object-oriented design rules: Walk through all five SOLID principles and pair each rule with a brief code or domain scenario.
- Hashed collections and concurrent maps:
- Contrast
HashtablewithHashSeton element vs. key-value storage,nullacceptance, and locking behavior. - Describe
ConcurrentHashMap, how its internal concurrency model improves uponHashMapandHashtable, and when backend services rely on it.
- Contrast
- Character sequences and immutable types:
- Contrast
String,StringBuilder, andStringBufferacross 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.
- Contrast
- Thread-safety primitives:
- Explain Java's
volatilemodifier, 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.atomictoolkit—includingAtomicIntegerandAtomicReference—and how hardware compare-and-swap enables non-blocking updates.
- Explain Java's
- Exception management: Distinguish checked from unchecked exceptions on the JVM and outline production-ready habits for resource cleanup, cause preservation, and boundary handling.
- 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.
- 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, andConcurrentHashMapoperations. - 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
Collections: ArrayList versus LinkedList
Both
ArrayListandLinkedListimplement Java's orderedList<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] <- lastArrayListstores elements in a resizableObject[]plus asizefield. Appending at the end is amortized O(1) (meaning almost everyaddwrites into a free slot inO(1)time, and the occasional1.5xarray copy spreads out to a constant average cost per element). Readingget(i)jumps straight to slotiinO(1), and CPU cache locality (adjacent elements sitting in the same hardware cache line) makes sequential scans very fast.LinkedListstores each element in a heap-allocatedNode { item, next, prev }and implements bothListandDeque. Adding or removing at the head, tail, or an already-positionedListIteratorupdates two pointers inO(1), butget(i)must walkmin(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,000items one by one at index0of anArrayListshifts0 + 1 + 2 + ... + 99,999 = 4,999,950,000references (O(n^2)total), whereas aLinkedListperforms100,000constant-time pointer updates. Yet for random reads, iteration, or appending,ArrayListwins decisively.Rule of thumb: Default to
ArrayListfor general lists, useArrayDeque(a circular resizable array) for queues and stacks, and reserveLinkedListfor rare workloads that repeatedly splice elements mid-list through an activeListIterator.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
Invoiceclass that calculates taxes, formats PDFs, and runs SQL queries couples accounting rules, UI layout, and database schemas; split it intoInvoiceCalculator,InvoicePdfRenderer, andInvoiceRepository. - 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)insidecheckout()with aDiscountPolicyinterface so adding a"VIP"rule is one new class, not an edit tocheckout(). - L — Liskov Substitution Principle (LSP): Any subtype must honor the behavioral contract promised by its base type so callers never get surprises.
Square extends Rectangleviolates LSP when callingrect.setWidth(5); rect.setHeight(2);silently overwrites width to2and yields area4instead of10. - 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 intoPrinter,Scanner, andFaxso a basic printer never stubsfax()withUnsupportedOperationException. - D — Dependency Inversion Principle (DIP): High-level business policy should depend on interfaces (abstractions), not low-level vendor classes.
OrderServicetalks toPaymentGateway, and the concreteStripeGatewayis 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); } }- S — Single Responsibility Principle (SRP): A class should have only one reason to change. An
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) usingkey.equals(), achievingO(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 locksInternal mechanics:
HashSet<E>does not have its own hashing engine: internally it wraps aHashMap<E, Object>where your elements are the keys and every key points to the same static dummyPRESENTobject.Hashtableis a legacy Java 1.0 class whose methods are allsynchronizedonthis, turning the entire map into a single-file bottleneck under multi-threaded traffic.HashMap(default capacity16, load factor0.75, resizing past16 * 0.75 = 12entries) stores colliding entries in a linked list per bucket, and once a bucket exceeds8nodes (provided table capacity is at least64; smaller tables simply double in size), it converts that bucket into a balanced red-black tree to bound worst-case collision lookups toO(log n).ConcurrentHashMapis built for high-throughput concurrent access:- Reads (
get) are lock-free and rely onvolatilereads. - 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.
- Iterators are weakly consistent: they never throw
ConcurrentModificationExceptionand reflect updates on a best-effort basis. nullkeys and values are forbidden because in concurrent codemap.get(k) == nullwould be ambiguous (you cannot safely callcontainsKey(k)afterward without another thread changing the entry in between).
- Reads (
Even with
ConcurrentHashMap, combining separategetandputcalls creates a check-then-act race—always use single-call atomic methods likemerge,compute, orcomputeIfAbsent: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);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 overheadWhy loop concatenation with
StringisO(n^2): BecauseStringis immutable (its contents can never change once constructed), runnings += chinside a10,000-iteration loop allocates10,000separateStringobjects and performs1 + 2 + ... + 10,000 = 50,005,000character writes as all previous characters are re-copied every single step.StringBuildermutates 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 aHashMaporHashSet. - Safe sharing and caching: Instances can be cached (like the JVM string pool or
Integercache-128..127) and passed across layers without worrying a callee will mutate them.
Four rules to implement a truly immutable class in Java:
- Declare the class
finalso subclasses cannot override getters to expose mutable state. - Mark every field
private finaland assign all of them in the constructor. - Expose no setter methods; return a brand-new instance from
"with..."methods when deriving a modified copy. - Make defensive copies (independent copies of mutable inputs like
ListorDate) on the way into the constructor and never return mutable internal collections directly (List.copyOfmakes an unmodifiable copy and rejectsnullelements):
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)generatesfinalfields and accessors automatically, but records are only shallowly immutable—you still additems = List.copyOf(items);in a compact constructor to protect mutable collections.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 avolatilestore becomes visible to any thread that subsequently reads thatvolatilevariable, preventing compiler/CPU caching and instruction reordering). It also guarantees atomic 64-bit reads/writes forlonganddouble. Usevolatilefor one-writer status flags (volatile boolean running = true;), never forcount++or multi-field invariants.synchronized(mutual exclusion + visibility): Every Java object carries an intrinsic lock (monitor). Enteringsynchronized (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 holdinglockcan call another method synchronized onlockwithout 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—useReentrantLockwhen you needtryLock(timeout)or interruptible waits.java.util.concurrent.atomic(lock-free single-variable atomicity): Classes likeAtomicIntegerandAtomicReference<V>rely on hardware CAS (compareAndSet(expected, next)). To increment,AtomicIntegerreads current valuev, attemptscompareAndSet(v, v + 1), and retries immediately in a tiny loop if another thread beat it (or executes a single hardwarelock xaddinstruction on x86)—no thread ever suspends. PairAtomicReferencewith an immutable state object to swap multiple related fields atomically, useAtomicStampedReferencewhen you must guard against the ABA problem (a value changingA -> B -> Abehind a thread's back), and preferLongAdderoverAtomicLongwhen 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; } } }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 (
Exceptionsubclasses outsideRuntimeException) 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 (
RuntimeExceptionsubclasses) signal programming mistakes (null arguments, index out of bounds, illegal state) or infrastructure failures wrapped at architectural boundaries (for example, Spring's uncheckedDataAccessException).
Production best practices:
- Catch only when you can recover or add context—otherwise let exceptions bubble up to a central handler.
- Never swallow exceptions silently (
catch (Exception ignored) {}hides root causes). - Preserve the causal chain when wrapping (
throw new OrderPersistenceException("Order " + id, cause)), keeping the original stack trace intact. - Always close resources with
try-with-resourcesfor anyAutoCloseable(files, sockets, JDBC connections) soclose()runs deterministically even if an exception occurs. - 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. - Remember Spring's
@Transactionalrollback rule: By default, Spring rolls back database transactions on uncheckedRuntimeExceptionandError, 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()); } }- Checked exceptions (
Spring core: IoC, DI, bean lifecycle, AOP, and annotations
With Inversion of Control (IoC), your classes stop calling
newto assemble their own collaborators; instead, Spring'sApplicationContextcontainer 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@Beanfactory methods inside@Configurationclasses (ideal for third-party or JDK classes likeClockorHttpClient), and legacy XML definitions. - Constructor injection over field/setter injection: A single constructor needs no
@Autowiredannotation (Spring 4.3+), allowsprivate finalfields so beans are never half-initialized, fails fast on circular dependencies, and lets unit tests instantiatenew OrderService(fakeGateway)with zero Spring startup cost. Use@Qualifier("stripe")or@Primarywhen 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@Transactionalor@Cacheablemethods inside the same class silently skips the advice, andprivateorfinalmethods 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 unifiedDataAccessExceptionhierarchy).@Controllervs.@RestController:@Controllerresolves view templates;@RestControllercombines@Controller+@ResponseBodyto serialize return values directly to JSON/HTTP bodies.- Configuration & web staples:
@Configuration(proxied by CGLIB so inter-@Beancalls return the same singleton, unlike@Beaninside a plain@Component),@Value,@ConfigurationProperties,@Profile,@Scope,@GetMapping/@PostMapping,@PathVariable,@RequestParam,@RequestBody,@Valid, and@Transactional.
- Three ways to register beans: Component scanning on stereotype annotations (
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
sortedmust 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-wideForkJoinPool.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
ArrayListvs.LinkedList:ArrayListuses a contiguous resizableObject[](1.5xgrowth,O(1)random access, amortizedO(1)tail append—meaning occasional resize copies average out to constant cost per add—and strong CPU cache locality);LinkedListuses doubly linked 24-byteNodewrappers (O(1)head/tail/iterator splice,O(n)index traversal). Default toArrayList, and preferArrayDequefor queues and stacks.- SOLID principles: Single Responsibility (one reason to change), Open/Closed (extend via new implementations, not
switchedits), 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 withequals().HashSetwraps aHashMapusing a shared dummy value;Hashtablelocks the whole map on every call and forbidsnull;ConcurrentHashMapoffers lock-free reads, per-bucket CAS/synchronized writes, atomicmerge/computemethods, weakly consistent iterators (never throwingConcurrentModificationException), and forbidsnulls to keepget(k) == nullunambiguous. - Strings and immutability:
Stringis immutable and safe as a map key;StringBuildermutates an internal buffer inO(n)for single-threaded loops;StringBufferadds legacy method-level synchronization. Build immutable classes withfinal class,private finalfields, no setters, and defensive copies (List.copyOf) on inputs and outputs. - Concurrency primitives:
volatileguarantees happens-before visibility and ordering (writes before avolatilestore are visible to later readers) without compound atomicity;synchronizedprovides reentrant mutual exclusion plus visibility at the cost of thread blocking;AtomicInteger/AtomicReferenceuse 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); uncheckedRuntimeExceptions cover bugs and unrecoverable faults. Usetry-with-resources, never swallow exceptions, pass the originalcausewhen wrapping, log once at the boundary, and note that Spring@Transactionalrolls 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 issingleton(must be stateless/thread-safe);@Repositoryadds persistence exception translation; and Spring AOP wraps beans in proxies, so internalthis.method()calls bypass@Transactionaland@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-argumentCollectors.toMapwith merge function).
Common mistakes
- Saying
LinkedListmiddle insertion isO(1)unqualified: Splicing pointers at an existingListIteratorisO(1), butlist.add(i, x)first walksmin(i, n - i)nodes inO(n)time. - Assuming two calls on
ConcurrentHashMapare atomic together:map.put(k, map.getOrDefault(k, 0) + 1)still loses updates under contention; usemap.merge(k, 1, Integer::sum). - Using
volatilefor counters or multi-variable invariants:volatile int count; count++still races between read and write, and two separatevolatilefields cannot be updated together atomically. - Returning or storing caller-owned
List/Datereferences in an "immutable" class: Without defensive copying (List.copyOf), external callers can mutate the object's state after construction. - Self-invoking
@Transactionalmethods or throwing checked exceptions expecting rollback: Callingthis.updateOrder()skips the Spring proxy, and throwing a checkedIOExceptioncommits the transaction unlessrollbackForincludes it. - Calling
Collectors.toMap(keyFn, valFn)when duplicate keys can occur: The two-argument overload throwsIllegalStateExceptionon 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)istrue,a.hashCode() == b.hashCode()must also hold (unequal objects may still share a hash code, causing a collision handled viaequals). Overridingequalswithout overridinghashCodemakes logically equal objects hash to different buckets, somap.get(copyOfKey)returnsnull. Worse, if you mutate a field used byhashCode()after putting a key into aHashMap, the entry sits stranded in its original bucket while future lookups compute the new bucket—making the entry invisible togetand 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
@Transactionalusing a runtime proxy wrapper around the bean: external callers invoke the proxy (which starts and commits the transaction), whereas callingthis.methodB()insidemethodA()invokes the raw Javathisreference directly and bypasses the proxy completely. The cleanest fix is either extractingmethodBinto a separate focused collaborator bean injected via the constructor, or moving@Transactionalonto the public entry methodmethodAif 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'sTransactionTemplateinstead 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 inO(1)(ArrayListand arrays split cleanly;LinkedListandStream.iteratesplit poorly), and lambdas touch zero shared mutable state. In backend web servers it frequently hurts performance because all parallel streams shareForkJoinPool.commonPool()(sized toCPU 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
- What rules govern Java's equals and hashCode contract, and what happens if a HashMap key mutates after insertion?
- Why is Spring's @Transactional annotation bypassed when one method calls another inside the same class, and how should you refactor it?
- Under what conditions does parallelStream improve throughput, and why can it degrade a backend web server?
Similar questions
- Spring Payment Strategy Service Design
- Count Characters by First Appearance
- Longest Duplicate-Free Substring
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination