About This Book
This book is a practical guide to writing modern Java. It covers the language, its standard libraries, the JVM, and the patterns that connect them — from everyday idioms to the internals that explain why they work.
What You Will Find
Every chapter pairs explanation with code. Concepts are introduced through short, self-contained examples that compile and run. Where a topic has depth — like garbage collection or concurrency — the chapter walks through the mechanics before showing the pattern.
The book is organized in seven parts:
Java Language starts with object-oriented design, then moves to functional programming with streams and the newer data-oriented style using records, sealed classes, and pattern matching.
Design Patterns covers the classic Gang of Four patterns — creational, structural, and behavioral — alongside functional and concurrency patterns adapted for modern Java.
Core APIs digs into the collections framework, generics, the time API, internationalization, and string processing. Each chapter explains the internal data structures so you can make informed choices.
Concurrency covers threading from basic synchronization through executors, CompletableFuture, virtual threads, and lock-free algorithms.
I/O and Error Handling addresses Optional, exception strategies, file I/O with NIO.2, and non-blocking channels.
Advanced Topics brings together reflection, annotations, testing, security, the Foreign Function and Memory API, networking, and JDBC.
JVM Internals looks under the hood at bytecode, memory management, garbage collectors, the Java Memory Model, performance optimization, and diagnostic tools.
Who This Book Is For
This book is for Java developers who want to go beyond syntax. Whether you are preparing for a senior role, optimizing a production system, or simply want to understand what the JVM does with your code, you will find material here that applies directly to your work.
Familiarity with Java basics is assumed. No framework experience is required — the focus is on the language and platform itself.
How to Read This Book
The parts are self-contained. You can read front to back or jump to the topic you need. Within each chapter, code examples build on each other, so reading a chapter in order works best.
Part I: Java Language
Object-Oriented Analysis and Design
- Classes, interfaces, and abstract classes
- Inheritance vs. composition
- SOLID principles
- GRASP patterns
- UML class diagrams
- Domain modeling
Functional Programming and Streams
- Lambda expressions and functional interfaces
- Method references
- Stream creation, intermediate, and terminal ops
- Collectors and custom reductions
- Parallel streams and performance
- Function composition and higher-order functions
Data-Oriented Programming
- Records as transparent data carriers
- Sealed classes and interfaces
- Pattern matching for instanceof and switch
- Deconstructing records
- Algebraic data types in Java
- Combining OOP and data-oriented styles
Part II: Design Patterns
Creational Patterns
- Singleton (enum, thread-safe, DI alternatives)
- Factory Method and Abstract Factory
- Builder (classic, fluent, Lombok, records)
- Prototype (cloning, deep vs. shallow copy)
- Object Pool (connections, threads, HikariCP)
Structural Patterns
- Adapter (class, object, legacy integration)
- Decorator (dynamic behavior, I/O streams)
- Proxy (virtual, dynamic, Spring AOP)
- Facade (API simplification)
- Composite (tree structures)
- Bridge (abstraction from implementation)
- Flyweight (string interning, integer caching)
Behavioral Patterns
- Strategy (algorithm families, lambdas)
- Observer (event-driven, reactive)
- Command (undo/redo, queues)
- Iterator (collections, streams)
- Template Method (abstract hierarchies, hooks)
- Chain of Responsibility (filters, logging)
- State (state machines, enum-based)
- Visitor (double dispatch, AST traversal)
- Mediator (coordination, message brokers)
- Memento (state restoration, event sourcing)
- Interpreter (expression evaluation)
Functional Patterns
- Function composition
- Higher-order functions
- Currying and partial application
- Monads (Optional, Stream, CompletableFuture)
- Immutability patterns
- Pure functions and side effects
- Lazy evaluation
- Functional error handling
Concurrent Patterns
- Thread-safe Singleton
- Thread pools and Executors
- Producer-Consumer
- Read-Write locks
- Future and CompletableFuture
- Fork/Join framework
- Virtual threads (Java 21+)
- Structured concurrency
Part III: Core APIs
Lists and Arrays
- Array fundamentals and manipulation
- ArrayList internals and growth strategy
- LinkedList and when to use it
- List.of() and immutable lists
- Sorting, searching, and iteration patterns
- Array vs. List trade-offs
HashMap and HashSet
- HashMap internals (buckets, tree bins)
- hashCode/equals contract
- Load factor and capacity tuning
- HashSet as HashMap wrapper
- LinkedHashMap for insertion order
- TreeMap and TreeSet for sorted access
- ConcurrentHashMap for thread safety
Collections
- Queue and Deque implementations
- PriorityQueue and ordering
- Collections utility methods
- Unmodifiable and synchronized wrappers
- Concurrent collections overview
- Choosing the right collection
Generics and Boxing
- Type parameters and bounds
- Wildcards (? extends, ? super, PECS)
- Type erasure and its consequences
- Autoboxing and unboxing costs
- Primitive specializations
- Generic methods and type inference
Java Time API
- LocalDate, LocalTime, LocalDateTime
- ZonedDateTime and timezone handling
- Instant and Duration
- Period and temporal adjusters
- Formatting and parsing (DateTimeFormatter)
- Interop with legacy Date/Calendar
Internationalization
- Locale and resource bundles
- MessageFormat and pluralization
- NumberFormat and currency
- Date/time formatting per locale
- Collation and sorting
- Unicode and character encoding
String Processing
- String immutability and interning
- StringBuilder vs. StringBuffer
- Regular expressions (Pattern, Matcher)
- String formatting and text blocks
- Character encoding (UTF-8, charsets)
- String performance patterns
Part IV: Concurrency
Threading
- Thread lifecycle and states
- synchronized and volatile
- wait/notify and condition variables
- Executor framework and thread pools
- Callable, Future, CompletableFuture
- Virtual threads (Project Loom)
- Structured concurrency
Lock-Free Concurrency
- Atomic classes (AtomicInteger, AtomicReference)
- Compare-and-swap (CAS) operations
- Lock-free queues and stacks
- StampedLock and optimistic reads
- Adders and accumulators
- Memory ordering and happens-before
Part V: I/O and Error Handling
Optional and Error Handling
- Optional creation and chaining
- map, flatMap, filter, orElse variants
- Anti-patterns to avoid
- Checked vs. unchecked exceptions
- Try-with-resources
- Custom exception hierarchies
- Functional error handling (Either, Try, Result)
I/O, Files, and NIO
- Classic streams and readers/writers
- Buffering strategies
- NIO.2 Files and Paths
- Walking file trees and WatchService
- Channels, ByteBuffers, and Selectors
- Asynchronous file I/O
- Memory-mapped files
Part VI: Advanced Topics
Reflection and Annotations
- Class introspection and dynamic invocation
- Dynamic proxy creation
- Custom annotations and retention policies
- Runtime and compile-time annotation processing
- MethodHandles as fast alternative
- Frameworks using annotations (JPA, Spring)
Logging and Debugging
- SLF4J facade and binding architecture
- Logback and Log4j2 configuration
- Log levels and best practices
- Structured logging (JSON)
- MDC and correlation IDs
- Performance considerations
Testing
- JUnit 5 (assertions, parameterized, extensions)
- Mockito (mock, spy, stubbing, verification)
- AssertJ fluent assertions
- Testcontainers for databases and services
- Spring Boot testing (@SpringBootTest, MockMvc)
- Property-based testing (jqwik)
Security
- Authentication vs. authorization
- Spring Security (filters, OAuth2, JWT)
- Java Cryptography Architecture
- Input validation and sanitization
- SQL injection and XSS prevention
- CSRF protection
Foreign Function and Memory
- MemorySegment and MemoryLayout
- Arena-based memory management
- Linker and function descriptors
- Calling C libraries from Java
- Structured access to native memory
- Migration from JNI and Unsafe
Math and Vector API
- Vector species and shapes
- Lane-wise operations
- Masks and reductions
- Math class utilities
- StrictMath and floating-point precision
- Performance benchmarks
Networking and HTTP
- Socket and ServerSocket basics
- HttpClient (Java 11+)
- HTTP/2 and WebSocket support
- Synchronous and asynchronous requests
- Request/response builders
- Connection management and timeouts
SQL and JDBC
- Connection management and DataSource
- PreparedStatement and batch operations
- ResultSet processing patterns
- Transaction handling
- Connection pooling (HikariCP)
- SQL injection prevention
Part VII: JVM Internals
Bytecode and JVM
- Class file structure
- Bytecode instruction set
- Stack-based execution model
- Class loading and delegation
- JIT compilation (C1, C2, tiered)
- Inlining and escape analysis
- Bytecode manipulation (Byte Buddy, ASM)
Memory Management
- JVM memory areas (heap, stack, metaspace)
- Object header and layout
- Allocation and TLAB
- Strong, weak, soft, phantom references
- Memory leaks and detection
- Off-heap memory (DirectByteBuffer)
- Object pooling and flyweight
Garbage Collectors
- Generational hypothesis
- Serial and Parallel GC
- G1 GC (regions, mixed collections)
- ZGC (sub-millisecond pauses)
- Shenandoah GC
- GC tuning (-Xms, -Xmx, flags)
- GC log analysis and monitoring
Concurrency Internals
- Java Memory Model (JMM)
- Happens-before relationships
- volatile, synchronized, and final semantics
- Lock internals (biased, thin, fat locks)
- AQS (AbstractQueuedSynchronizer)
- ForkJoinPool internals
- Virtual thread implementation
Performance Optimization
- Profiling (JFR, async-profiler, VisualVM)
- JMH microbenchmarking
- CPU optimization (algorithms, data locality)
- Memory optimization (pooling, off-heap)
- I/O optimization (buffering, async)
- String and collection performance
- Performance anti-patterns
- Performance testing (JMeter, Gatling)
JVM Tools and Options
- jcmd (unified diagnostic command)
- jstack (thread dumps)
- jmap (heap dumps, histogram)
- jstat (GC and class loading stats)
- Java Flight Recorder (jfr)
- jconsole and JMX
- Essential JVM flags (-XX:+PrintGCDetails, etc.)
- Container-aware JVM settings