CIPHERCODE.AI · JAVA ADVANCED

Java in production

Concurrency, JVM internals and Spring Boot APIs.

  • 3 modules
  • Line-by-line code
  • Quizzes + practice

    Module 1

    Threads, executors and thread safety

    Run work in parallel and avoid race conditions.

    About 2 hours

    A thread is an independent path of execution. Creating threads by hand does not scale, so use an ExecutorService, a managed pool of workers. When two threads change the same variable, a race condition can silently lose updates.

    Counter.java
    import java.util.concurrent.*;
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class Counter {
        public static void main(String[] args) throws Exception {
            ExecutorService pool = Executors.newFixedThreadPool(4);
            AtomicInteger count = new AtomicInteger();
            for (int i = 0; i < 1000; i++)
                pool.submit(() -> count.incrementAndGet());
            pool.shutdown();
            pool.awaitTermination(5, TimeUnit.SECONDS);
            System.out.println(count.get());
        }
    }
    A pool of 4 threads takes 1000 small tasks. AtomicInteger.incrementAndGet() is atomic, so no update is lost. With a plain int count++ the answer would often be below 1000, because ++ is read, add, write and threads interleave. shutdown stops new tasks and awaitTermination waits for the running ones.

    Key takeaways

    • Use executors, not raw Thread objects
    • Shared mutable state needs atomics, locks or concurrent collections
    • count++ is not atomic
    • Always shut pools down

    Practice

    Sum 1..100 using 4 tasks and Future results.

    Submit Callable<Integer> tasks, call future.get() and add.

    Sum.java
    Future<Integer> f = pool.submit(() -> 42);
    System.out.println(f.get());

    Quick quiz

    Why can count++ from many threads give a wrong total?

    Module 2

    JVM memory and garbage collection

    Know where objects live, how GC frees them, and how to spot leaks.

    About 90 minutes

    The JVM splits memory in areas. The stack holds method calls and local variables (one per thread, freed on return). The heap holds all objects and is cleaned by the garbage collector (GC), which frees objects nothing refers to any more.

    AreaHoldsNotes
    StackLocals, call framesStackOverflowError on runaway recursion
    Young genNew objectsFast, frequent minor GC
    Old genLong-lived objectsSlower major GC
    MetaspaceClass metadataGrows with loaded classes
    flags
    java -Xms512m -Xmx512m -XX:+UseG1GC -Xlog:gc MyApp
    -Xms and -Xmx set initial and max heap (equal values avoid resizing). -XX:+UseG1GC picks the G1 collector, the default on modern JDKs. -Xlog:gc prints every collection so you can read pause times.

    Key takeaways

    • Stack = calls, heap = objects
    • GC frees unreachable objects only
    • Leaks are lingering references
    • Measure with GC logs and heap dumps before tuning

    Practice

    Explain why a static HashMap used as a cache can cause OutOfMemoryError and name one fix.

    Entries are never removed, so references keep objects alive. Use a bounded cache (Caffeine) or WeakHashMap.

    Answer: unbounded growth plus live references; fix with an eviction policy.

    Quick quiz

    Which objects does GC free?

    Module 3

    Spring Boot REST APIs

    Build a JSON web API with controllers, services and configuration.

    About 2 hours

    Spring Boot starts an embedded web server and wires your objects together (dependency injection). Layers keep code clean: the controller handles HTTP, the service holds business rules, the repository talks to the database.

    HelloController.java
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
        private final GreetService service;
    
        public HelloController(GreetService service) {
            this.service = service;
        }
    
        @GetMapping("/hello/{name}")
        public String hello(@PathVariable String name) {
            return service.greet(name);
        }
    }
    @RestController returns data (JSON or text) instead of web pages. @RequestMapping("/api") sets a base path. The constructor receives GreetService; Spring creates and injects it, so you never call new. @GetMapping maps GET /api/hello/Asha and @PathVariable extracts Asha.
    application.properties
    server.port=8080
    spring.datasource.url=jdbc:postgresql://localhost:5432/shop
    spring.jpa.hibernate.ddl-auto=validate
    Configuration lives outside code. Never commit real passwords; read them from environment variables.

    Key takeaways

    • Controller -> Service -> Repository layering
    • Constructor injection is the preferred style
    • @GetMapping/@PostMapping map HTTP to methods
    • Externalise configuration and secrets

    Practice

    Add @GetMapping("/health") returning "OK".

    One method in the controller returning a String.

    Health.java
    @GetMapping("/health")
    public String health() { return "OK"; }

    Quick quiz

    What does dependency injection remove?

    EXAM READINESS EXTENSION · ADVANCED

    Advanced Core Java, backend and production topics

    The current advanced path covers concurrency, JVM memory and Spring REST. For broader university, certification-style and interview exams, add the following areas. Some are Core Java language/API topics; framework and tooling questions depend on the syllabus.

    Definition bank: Advanced Java definitions

    Learn these concise definitions for theory questions. In written exams, define the term first, then add a short example when asked.

    Thread
    A path of execution within a process; Java programs can run multiple threads concurrently.
    Concurrency and parallelism
    Concurrency is managing overlapping tasks; parallelism is executing tasks at the same time on multiple processing resources.
    Race condition
    A bug in which the result depends on unpredictable timing or interleaving of concurrent operations.
    Thread safety
    A property whereby code behaves correctly when accessed by multiple threads under its documented usage conditions.
    Synchronization
    A mechanism, such as synchronized, that coordinates thread access to shared state and establishes memory-visibility guarantees.
    volatile
    A field modifier that provides visibility and ordering guarantees for reads and writes, but does not make compound actions atomic.
    Atomic class
    A class such as AtomicInteger that provides thread-safe atomic operations on a value.
    ExecutorService
    An API for managing task execution using a pool or other executor, rather than manually creating a thread for each task.
    Future
    An object representing a result or completion of an asynchronous computation that may be checked or awaited.
    Java Memory Model (JMM)
    The rules that define how threads interact through memory, including visibility and ordering of reads and writes.
    Heap and stack
    The heap stores objects and arrays; each thread has a stack containing method frames, local variables and call information.
    Garbage collection
    Automatic reclamation of heap memory for objects that are no longer reachable.
    Class loading
    The JVM process of locating class definitions, loading them, linking them and initializing classes when required.
    JIT compiler
    The Just-In-Time compiler converts frequently executed bytecode into native machine code at runtime to improve performance.
    JVM profiling
    Collecting runtime measurements such as CPU use, allocation, garbage collection and thread activity to locate bottlenecks.
    SOLID
    Five object-oriented design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion.
    Design pattern
    A reusable, named approach to a recurring software design problem, such as Strategy, Factory or Observer.
    Dependency injection
    A design technique in which an object receives its dependencies from outside rather than creating all of them itself.
    Spring Boot
    A framework built on Spring that simplifies application setup and configuration, often used for stand-alone services and APIs.
    REST API
    An HTTP-based interface organized around resources and standard methods, commonly returning representations such as JSON.
    HTTP status code
    A numeric response code indicating the outcome of an HTTP request, such as 200, 201, 400, 404 or 500.
    DTO (Data Transfer Object)
    An object used to carry data between application layers or across an API boundary.
    ACID properties
    Database transaction properties: Atomicity, Consistency, Isolation and Durability.
    Build tool
    Software such as Maven or Gradle that automates compiling, testing, dependency management and packaging.
    Integration test
    A test that checks whether multiple components work together, for example a service interacting with a database.
    Complexity analysis
    Evaluation of an algorithm’s growth in time or memory usage as the input size changes.

    1. Java Memory Model and thread safety

    A race condition occurs when the result depends on timing between threads. Synchronization provides mutual exclusion and visibility. volatile provides visibility/order guarantees for a variable but does not make compound actions atomic. Use atomic classes, locks or concurrent collections as appropriate.

    private final AtomicInteger count = new AtomicInteger();
    void increment() { count.incrementAndGet(); }
    int current() { return count.get(); }

    Know happens-before relationships, safe publication, immutable shared state, deadlock conditions, interruption, executor shutdown, Future/CompletableFuture, and the distinction between CPU-bound and I/O-bound workloads.

    2. Generics, collections and complexity

    Advanced exams may ask about type erasure, bounded wildcards, generic invariance, comparator contracts and hash-based collection internals. Average complexity depends on hash distribution and implementation; state assumptions instead of presenting O(1) as an unconditional guarantee.

    static double sum(List xs) {
        double total = 0;
        for (Number x : xs) total += x.doubleValue();
        return total;
    }

    Be able to justify a data structure choice and estimate time/space costs. Review arrays, linked lists, stacks, queues, hash tables, trees, heaps, binary search, sorting and graph traversal if algorithms are in scope.

    3. JVM internals and performance

    Understand class loading (loading, linking and initialization), runtime data areas, stack frames, heap objects, garbage collection, JIT compilation and class metadata. A memory leak can occur when objects remain reachable even though the application no longer needs them.

    Use evidence rather than guesswork: inspect CPU and heap profiles, thread dumps, GC logs and allocation rates. Avoid relying on finalization or calling System.gc() as a deterministic cleanup mechanism. Close external resources explicitly.

    Common distinction: stack overflow often results from deep recursion or excessive stack use; out of memory means the JVM cannot satisfy an allocation or a relevant memory area is exhausted.

    4. Modern Java language features

    Know the version boundaries specified by your course. Modern Java may include local-variable type inference (var), switch expressions, text blocks, records, sealed classes, pattern matching and modules. These features do not remove the need to understand classes, interfaces, exceptions and type safety.

    record Point(int x, int y) { }
    
    static String describe(Object value) {
        return switch (value) {
            case String s -> "text: " + s;
            case Integer i -> "number: " + i;
            case null -> "null";
            default -> "other";
        };
    }

    Use the exact supported syntax for the configured Java release; some features were preview features before becoming permanent.

    5. JDBC transactions and data safety

    A transaction groups operations into a unit. Review ACID: atomicity, consistency, isolation and durability. Understand auto-commit, commit/rollback, isolation levels, lost updates, dirty reads and connection/resource lifecycle.

    try (Connection c = dataSource.getConnection()) {
        c.setAutoCommit(false);
        try {
            // execute related PreparedStatement updates
            c.commit();
        } catch (SQLException ex) {
            c.rollback();
            throw ex;
        }
    }

    Production code should also preserve the original exception if rollback fails and restore connection state when connections are pooled. Parameterize SQL; use least-privilege database credentials.

    6. Spring Boot REST fundamentals

    Know dependency injection, inversion of control, beans, component scanning, configuration, controller/service/repository separation, validation and exception mapping. A REST API should use appropriate HTTP methods and status codes, validate inputs and avoid exposing internal stack traces.

    @RestController
    @RequestMapping("/api/books")
    class BookController {
        @GetMapping("/{id}")
        ResponseEntity get(@PathVariable long id) {
            return service.find(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
        }
    }

    Also review DTOs vs persistence entities, pagination, idempotency, authentication vs authorization, configuration by environment, integration tests and API documentation. Framework annotations vary by Spring version.

    7. Design principles and patterns

    Be able to explain SOLID: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion. Prefer composition where it makes behaviour easier to vary. Common patterns include Strategy, Factory, Builder, Adapter, Decorator, Observer and Repository.

    For an exam answer, give the problem the pattern solves, the participants, a tiny example, and trade-offs. Do not force a pattern where a simple function or class is enough.

    8. Build, testing and diagnostics

    Review Maven/Gradle dependency management, scopes, reproducible builds, unit vs integration tests, test doubles, parameterized tests and CI. Learn to read stack traces from the first relevant application frame, identify the root cause and reproduce a failure with a small test.

    For performance questions, state the workload, measurement method and constraints. Benchmarking needs warm-up and controlled conditions; a single timing run is not reliable evidence.

    High-yield advanced distinctions

    PairExam-ready explanation
    volatile vs synchronizedVolatile provides visibility/order guarantees for reads and writes to one variable; synchronized provides mutual exclusion and visibility around a critical section. Volatile alone does not make read-modify-write operations atomic.
    execute(), submit()ExecutorService execute accepts a Runnable without returning a Future; submit returns a Future and can capture task exceptions for later observation.
    Heap vs stackThe heap holds objects and arrays; each thread has a stack containing frames for active method calls and local execution state. Exact implementation details are JVM-dependent.
    Authentication vs authorizationAuthentication establishes who a caller is; authorization decides what that caller may do.
    Unit vs integration testA unit test isolates a small unit and its collaborators; an integration test verifies interactions across components such as database, framework or network boundaries.
    REST PUT vs PATCHPUT conventionally replaces the target resource representation and is idempotent; PATCH applies partial modifications, with idempotency depending on the patch operation/design.

    Exam-style questions with worked answers

    Q1. Why does volatile int count not make count++ thread-safe?

    Answer: Increment is a read-modify-write sequence: read the old value, add one, write the result. Two threads can read the same old value and overwrite one another's update. Use AtomicInteger.incrementAndGet() or synchronize the operation.

    Q2. What is a memory leak in a garbage-collected language?

    Answer: Objects that are no longer logically needed remain strongly reachable, for example through an unbounded static collection or listener that is never deregistered. The garbage collector cannot reclaim reachable objects merely because the application has stopped using them conceptually.

    Q3. What is the difference between fail-fast iteration and thread safety?

    Answer: Fail-fast iterators may throw ConcurrentModificationException after certain structural modifications; this is a best-effort bug-detection mechanism, not synchronization. It does not make a collection thread-safe.

    Q4. Why use dependency injection in a Spring application?

    Answer: It separates object construction from object use, makes dependencies explicit, supports substitution and testing, and centralizes configuration/lifecycle management. It does not automatically guarantee good architecture; dependency boundaries still matter.

    Q5. How should an API handle invalid request data?

    Answer: Validate at the boundary, return an appropriate client-error status (commonly 400 for invalid input), provide a stable and useful error shape, avoid leaking secrets or stack traces, and test both valid and invalid cases.

    Advanced practical assignments

    1. Build a bounded producer-consumer example and explain how shutdown and interruption work.
    2. Compare HashMap, TreeMap and ConcurrentHashMap for a stated workload.
    3. Write a JDBC service that updates two related rows in one transaction and tests rollback.
    4. Design a Spring REST endpoint with validation, DTOs, status codes and centralized exception handling.
    5. Diagnose a simulated memory leak from object-retention clues and propose a measurement plan.
    6. Explain a design pattern with a minimal Java implementation and its trade-offs.

    You finished

    Keep going when you are ready.

    Continue