Leanpub Header

Skip to main content

Java Patterns

for experienced programmers

1300+ pages. Modern JAVA

The Language, Libraries and JVM internals

Minimum price

$5.00

$20.00

You pay

$20.00

Author earns

$16.00
$

...Or Buy With Credits!

You can get credits with a paid monthly or annual Reader Membership, or you can buy them here.
PDF
About

About

About the Book

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


Share this book

Categories

Author

About the Author

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $14 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub