Java Training
Java Training
Technologies continuously change, tech stacks evolve, the mindset shifts, and the best practices constantly align, so…
⚠️ Find the most up-to-date version of this file at: [Link]
Training Topics
The topics can be tailored to fit your needs: sub-items removed, added, or combined.
Target Audience:
- Developer looking to upgrade the quality of the code you write.
- Senior/Tech Lead/Coach/Chapter Lead concerned with helping your colleagues develop their skills.
What to expect: A mix of short refactoring exercises with debates about design options, attitude, teamwork,
and more, in an entertaining style spiced with real-life stories and analogies (preview). Concepts will be applied
via code review of selected prep-assignments, live-refactoring of code samples from the audience (for private
sessions), and hands-on refactoring by the participants working in mini-groups.
Option: Half-days with more hands-on: Split the online training in 4 hours / day, and allow the participants to
work independently during the 2nd half of the day on refactoring exercises/self-study that I can provide.
Prep work:
1. Practice refactoring ideally in pair/trio programming
a) Trivia Kata (est: 3-5 hours)
Java: [Link] (.zip)
Non-Java: [Link]
b) Stream API Kata (est: 3 hours, optional): [Link]
⚠️ MANDATORY: upload your solution before the training here: TODO
3. Read
- You can find the slides (eg. to preview them and explore hyperlinks) in this Google Drive: TODO
- Chapters 2-3 (est: 30 minutes) from Refactoring book by Martin Fowler
- Chapters 1-11 (est: 2 hours) from Clean Code book by Uncle Bob (Robert C. Martin)
- Overview of Code Smells: [Link]
6. Send me a list with the GitHub ID for all participants the evening before the training. I will invite them to
collaborate to a public Git (needed for the independent exercise during the second day).
Page 2 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Agenda
The agenda should be adjusted for your team’s needs in a prep-call.
- Fundamentals
o Refactoring Opportunities: boy-scout, pre-done, pre-change, post-frustration, post-rush
o Refactoring Stoppers: time, fear, branching, focus
o Teamwork: code review, conventional commit, pair programming
o Split large refactoring in safe baby-steps using full IDE support
o Refactoring Legacy Code: Mikado Method, Golden Master Testing (optional)
- Code Smells – overview of the most damaging micro-design issues today & fixing tactics:
- Expressive Code
o Good names: explanatory variables, methods, and constants
o Function signature: numbers of parameters, flags, defaults, extract parameter object
o Function depth and cognitive complexity; guards
o Single Responsibility (SRP) and Single-Level of Abstraction (SLAb) principles
o The 3 rules of a clean switch
o Error handling best practices
- Clean Object-Oriented Programming (OOP)
o Missing Abstraction – identifying and extracting Value Objects
o Encapsulation: move behavior next to state, enforce domain constraints
o Primitive obsession, micro-types
- Clean Functional Programming (FP)
o Pure Functions in practice
o Immutable Objects: benefits and tradeoffs
o Replacing loops with FP pipelines
o Mastering pipelines operators: .map, .filter, .flatMap, …
o FP anti-patterns and abuse: side-effects, tuples, FP chain wreck, complex .reduce, Try monad
- Language-specific Best Practices (spread throughout the content)
o Java: Optional<>, checked exceptions, switch, mutability
o PHP: type hints, collections, ?, default params
o Kotlin/Scala: tuples, extension functions, ?
o Python: type hints, named tuples, comprehensions, **, @dataclass
o TypeScript/JavaScript: type vs interface vs class, config object, async,
- IDE Refactoring Moves: extract/inline variables, methods, parameters, constants & interfaces, etc…
- Live-Refactoring (1-2 hours): Victor on production code snippets from the audience
- Code review of selected prep-assignments (1 hour)
- Hands-on (2-2.5 hours): Participants refactoring in mini-groups
- Other Debates, triggered by the audience questions
Page 3 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Main Goals:
- Empower developers to thoroughly unit-test their code
- Understand the design feedback provided by unit-tests
- Review today’s state-of-the-art unit/integration testing techniques
Prep-work:
- Read about different levels of testing - Practical Test Pyramid
- Coding Exercises to practice writing unit tests and mocks BEFORE the training, (mandatory for those
with less working experience) [Link] - (Java)
- [optional] Watch a Test-Driven Development Coding Kata: [Link]
live-coding-kata
- Send me samples of Unit Tests (for dedicated sessions only)
o 1-3 typical test classes of ≤ 100-200 lines + production code under test
o If making the extracted sample compile is too difficult, don’t send me any code code around
it - I will create the missing code to make it compile
o At least one participant should be familiar with the code.
Code: [Link]
Agenda
( a prep-call is mandatory to select from this agenda the techniques used in company )
- Fundamentals
o Why we write tests, why test-first, why test around bugs; tests cost/value
o Key Concepts: Line/Branch Coverage, Mutation Testing, Test Isolation, Flaky Test
o Strategies: Test Pyramid vs Honeycomb Testing
o Test anatomy (Given/When/Then), test names, Single Assert Rule
- Test-Driven Development (TDD) – 2 hours
o Red-Green-Refactor flow, TDD rules
o TDD Styles: Chicago(“triangulation”) vs. London(“outside-in”)
o TDD Pros / Cons
o Exercise: Classic TDD Coding Kata
o Exercise: Outside-in TDD Coding Kata [optional]
- Testing Techniques
o Creating test data
o Expressive asserts with Assert4J (assertThat)
o Parameterized Tests: uses/abusesTODO
o Behavior-Driven Development (BDD/ATDD) with Gherkin .feature files
o Testing Legacy Code: Characterization tests and Golden-Master technique
o Approval Testing
o Subcutaneous tests, @VisibleForTesting
o Hierarchical test classes: @Nested
- Mocks Best Practices – 2 hours
o Mocks: 3 reasons to love, 3 reasons to hate them
o Basic Features (recap): stubbing, verification, argument matchers, captors, static mocks
o Advanced/Dangerous Features: lenient, any, doReturn, spy, times, noMoreInteractions
o Exercise: Testing Legacy Code
- Test-Driven Design Insights - 4 hours (preview, video)
o Social Unit Tests (vs testing boilerplate code)
o Precise method signatures
o Specialized data structures
o Object Mother Pattern (vs mocking getters)
o Agnostic Domain (vs logic mixed with infrastructure)
Page 4 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
o Split by Layers of Abstraction (vs partial mocking)
o Split unrelated complexity (vs fixture creep)
o Contract-Driven Testing (Mock Roles, not Objects)
o Extract complexity in Pure Functions
- Testing with Spring Framework – 4-6 hours
o Testing with DI: @Import, @MockBean, @Primary, profiles, test properties, @DirtiesContext
o Testing with Persistence: in-memory/Testcontainers DB, cleanup strategies
o Testing with External APIs: intro to Wire Mock (+recording proxy); vs MockServer
o Testing your API: MockMvc, gray- vs black-box, custom testing DSLs, testing authorization
o Testing with MQ / Multi-threaded code: blocking, polling
o Exercise: refactoring from a mock-based test to an end-to-end system test
o Speeding up integration tests: context cache, Spring slice tests (@DataJpa..),
o Contract freeze test
o [optional] Consumer-Driven Contract Tests with Pact or Spring Cloud Contract (1h)
- Code review of unit tests from participants [optional]
Page 5 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Preparation:
● CLONE & IMPORT in IDE the code (optionally try to solve in advance some TODOs in the [Link]):
1) [Link] and
2) [Link]
● READ a compilation of architectural styles: [Link]
● READ an influential article [Link]
● WATCH introduction to Modular Monolith: [Link]
● STUDY a diagram: [Link]
BF5uU9h6o
● THINK: compile and send me before the training a bullet list of topics you’d like to debate .
● READ: the links in the agenda below
Page 6 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Agenda:
● Fundamentals
o Principles: SOLID, DRY, KISS & CUPID
o Complexity vs Coupling vs Data
o Constraints, NFRs, tradeoffs, and “it depends”
o Documenting Design: UML, ADR, C4
o Role of an Architect. How to become one?
● The Domain Model
o Ubiquitous Language and Bounded Context (Domain-Driven Design)
o Value Objects for a Supple Domain Model
o Rich Domain Model with behavior and constraints
o Debate: is ORM a friend or a foe?
o Exercise: refactoring Domain Model from ‘anemic’ to ‘rich’
● Exposing your API
o Contract- vs Code-first API development
o The Dark side of Automatic Mappers
o Command-Query Responsibility Segregation (CQRS)
o Task-Based UI
o API Versioning Strategies, SemVer
● Consuming their API
o Adapter Pattern and Dependency Inversion
o Enforce boundaries with Architecture Unit Tests
o Exercise: extract infrastructure concerns out of core logic
● Evolutionary Architecture
o Over-engineer vs Under-design
o Application Service (in DDD) and Separation by Layers of Abstraction
o Vertical-Slice Architecture (VSA)
o Exercise: push complexity in Domain Services
● Concentric Architectures
o Hexagonal Architecture (aka Ports-and-Adapters)
o Onion Architecture
o The 5 Rules of a Clean Architecture
o Criticisms and Pragmatic Simplifications
o Quiz
● Finding Service Boundaries - Heuristics
o Screaming Architecture – partition code first by business capability, not by layers
o Bounded Contexts, Team Size, Code Volatility, Conway’s Law
o Platform Team (as in Team Topologies)
● Modular Monolith Architecture (Modulith)
o What is a “Module”
o Module contract: internal/external, calls/events/plugins, encapsulation
o Data decoupling stages
o Module interaction patterns, breaking cyclic dependencies
o Packages vs Build Units
o Extracting a module as a microservice (for the right! reasons)
o Exercise: Extract a new functional module in an application using Spring Modulith
Page 7 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Prep-work: Participants with no prior contact with Domain-Driven Design philosophy should read
- DDD Terms: read at least pages 1-25 from: [Link]
- Domain-Driven Design Distilled by Vaughn Vernon (on Amazon), or
- DDD Quickly by InfoQ: [Link] (free)
Page 8 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Agenda
- Fundamentals 10m
o Definition and History of Microservices
o Benefits and Drawbacks of Microservices
o CAP Theorem & Eventual Consistency
o Integration Paradigms: RPC, Messaging, Shared DB, Files
- Finding Service Boundaries – A Gallery of Heuristics, including
o Technical vs Functional partitioning (aka Screaming Architecture)
o Business Capability vs Data
o Bounded Contexts for a sharp Domain Model
o Conway’s Law
o Cognitive Load and the Platform Team (Team Topologies)
- Migrating from Monolith to Microservices
o Strangler Pattern
o Modular Monolith Architecture
- API Design and Management
o REST APIs, Swagger/OpenAPI, GraphQL (brief)
o Versioning Strategies ([Link])
o Contract Testing & Automation: [Link] and Spring Cloud Contract
o API Gateway & BFF Pattern
o Service Discovery
- Resilience Patterns
o Catastrophic Failures examples
o Fallback Patterns
o Identifying failure units
o Timeouts, Retry, Idempotency, and Circuit Breaker
o Load Throttling: Concurrency and Rate Limiter
o Load Balancing and Auto-scaling
o Sidecar pattern (Istio)
- Message-Based Integration
o Messaging vs REST (or other RPC) – use-cases
o Messaging Features: persistent q, priority q, DLQ, consumer groups
o Messaging Patterns: fire-and-forget, request-reply, claim check
o Events vs Commands
- Event-Driven Architectures
o Four types of Event-Driven Architectures (talk)
o Kafka fundamentals and common patterns
o Event-Sourcing: patterns and challenges
o Round table: event-streaming war stories
o Distributed Consistency
o Outbox/Inbox Pattern, Change Data Capture (Debezium)
o Choreography vs Orchestration, Smart Endpoints and Dumb Pipes philosphy
o Compensations, Reservations, Saga Pattern
o Exercise: designing a food delivery saga
- Operating & Debugging
o Health Checks & Liveness-Management
o Request tracing & centralized logging
o Metrics: Prometheus/Grafana
o Distributed tracing bottlenecks, eg with Zipkin
- Security
o Authentication / Authorization Strategies
o Top 10 API Vulnerabilities (OWASP) - optional
o Secret Management
- Testing
o Honeycomb Testing Strategy
o End-to-end testing: who owns the service mocks?
Page 9 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
If you want the best of this training, you can prepare in advance by:
- (MUST) READ: 5-10 minutes about each pattern in the agenda below from:
o This website: [Link] or
o This book: Head First Design Patterns
- (RECOMMENDED) CODING: apply as many design patterns as possible you can to this exercise:
o [Link]
- (OPTIONAL) READ (15 minutes): this very influential article about Clean Architecture:
[Link]
IMPORTANT: The patterns listed in the agenda target a backend developer using Java/Kotlin/Scala (±
Spring), C#, or PHP. For developers developing Web Frontends (Angular, React..), Games (eg Unity) or Scripts (eg
python), we can tailor the agenda for their needs during a prep-call. Even if the principles stay the same, their
materialization in patterns is highly dependent of the application challenges, language and frameworks used.
Code: [Link]
Page 10 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Wrap-up – 30 min
- Anti-Patterns + typical workarounds
- Recap & Quiz.
Page 11 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Optional Preparation:
- The participants are assumed to be already fluent with the Java 8 lambda/Stream syntax. To fill any gaps
you can watch this Java 8 Stream API screencast on YouTube, then solve these exercises:
[Link]
Agenda
- Functional Programming
o Advanced Stream use-cases
o Syntax quirks: method references, target typing, effectively final
o Exceptions: wrapping as runtime and the Try monad
- Fighting NULL
o Null Object pattern
o Optional best practices & abuse
o Annotations
- Immutability
o Records (17) and Data-Oriented Programming (DOP); best practices and limitations
o Do we still need Lombok?
o Immutable collections
- Intercepting calls
o Proxy pattern (OOP)
o Aspect-Oriented Programming (AOP) – Spring example
o Execute-Around pattern (FP)
- Forking behavior
o Strategy pattern
o Attaching behavior to enum
o Return-switch-enum pattern (17)
o Filter pattern
- Fill behavior bits
o Template Method pattern (OOP)
o Loan pattern (FP)
- Behavior per subtype
o Visitor pattern (OOP)
o Switch on sealed classes (21)
- Concurrency:
o Parallel stream (8) pitfalls
o CompletableFuture (8)
o Virtual Threads (Project Loom) (21)
o Structured Concurrency (25)
- Strings: formatted, text blocks (17), interpolation (±24)
- [optional] Interfaces with default (8) and private (17) methods – use-cases
- Platform improvements: GraalVM and nativeimage, super-fast Garbage Collectors
- Future of Java Language
Page 12 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Target audience:
a) Entry-level developers with no/little prior contact with Spring
b) Experienced developers with hands-on experience with Spring
⚠️ For the best experience, try to avoid mixing people from both categories in the same group.
Prep work:
- [MUST] Prepare questions, debate topics, and challenging code samples from your project
- [MUST] Clone the project and mvn install it from [Link]
- Juniors can get familiar with the basics via a video course on Udemy/Pluralsight/Coursera …
- More experienced developers can try out samples from [Link] covering topics in the agenda
Agenda
- Spring Container (2h)
o Defining Beans: component-scanning, @Import, and @Bean
o Dependency Injection Styles + Lombok tricks
o Bean Lifecycle @Scope
o Spring Profiles and ConditionalOn…
- Events and Startup (.5h): @EventListener best practices, initializers
- Configuration (.5h): @Value, @ConfigurationProperties, config sources, Cloud Config Server
- Spring Boot (.5h):
o Library version management, starters
o Convention over Configuration: AutoConfiguration, devtools
- Aspects 1h: concepts, proxy implementation, pitfalls, writing an @Aspect
- Transaction Management 2-4h
o Database ACID transaction, anomalies
o @Transactional mechanics: propagation, rollbacks, read-only tx, after-tx hooks
o Best-practices and pitfalls using Transactions, tuning performance [opt]
o JPA integration: write-behind, auto-flushing, lazy-loading, and 1st level cache
- Multi-threading: Spring thread pools, @Async, and non-blocking REST APIs; @Scheduled
- Caching: annotation and programmatic, ⚠Pitfalls (stale cache, distributed cache, hit/miss ratio)
- REST Endpoints 2h
o REST API design best practices, validation, documentation
o @RestControllerAdvice
o [optional] Introduction to WebFlux 1h (see my Reactive Programming training for a deep-dive)
o [optional] WebSockets: concepts, debug, queue/topic, security, common patterns, testing
- Observability 1h
o Spring Actuator features, adding endpoints and health checks
o Exposing metrics with Micrometer
- Spring Security 2-4h
o Spring Security Architecture, Custom Security Filters
o Authentication via: User-Password login form, Basic/api-key, Preauth Headers, JWT Token
o Authorization: URL pattern vs annotations, role vs feature-based authz, data-security, testing
o Spring OAuth2 integration (example using KeyCloak) – prep video: Intro to OAuth
o (For more please see my ‘Secure Coding’ training)
- Messages on Queues 1-2h
o Concepts: durability, topic vs queue, reply queue, consumer group, tracing, DLQ, correlationID
o Spring Cloud Stream (the new Functional-Style)
o [optional] IntegrationFlows DSL
- Testing 4h+
o Testing with DI: @Import, @MockBean, @Primary, profiles, test properties, @DirtiesContext
o Testing with Persistence: in-memory DB, @Transactional tests, cleanup, @Sql, Testcontainers
o Testing with External APIs: essentials of WireMock, recording proxy; vs MockServer
o Testing your API: MockMvc, strategies, building custom testing DSLs, testing authorization
o OpenAPI-freeze approval test
o Exercise: refactoring from a mock-based test to an end-to-end system test
o Optimizing run time of integration tests
o [optional] Consumer-Driven Contract Tests with Pact 1h
- Spring Batch [optional] 2-3h
Page 13 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
o Concepts: Step, Job, Listener, Execution Context, Transaction control, Resume
o Using Listeners to track metadata
o Fine-Tuning Performance: Chunking, Parallel Steps, Multi-Threading processing
- Wrap-up:
o Real-life scenarios - Brainstorming
o Spring Overview: main features, strengths and weaknesses, best learning sources
Page 14 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
This workshop starts by reviewing the essential cryptography and web-security concepts and techniques.
The top web attacks identified by OWASP ([Link] are then explained and fixed with Spring
Framework in several ways comparing the tradeoffs of each option. We’ll then dive into the two main
coordinates of security: authentication and authorization and we’ll explore the mainstream practices as
well as some advanced use-cases that will lead us to discover many details of the Spring Security
framework.
This Training is for you because:
The agenda will be adapted for the technical stack / security techniques in use, ideally guided by the
client pen-testing findings.
Agenda
- Cryptography Fundamentals (2 hour)
o Hashing, Salting, bcrypt, Encryption (symmetric / asymmetric), Digital Signatures
o Certificates, Certificate Authorities, self-signed certificate, keytool overview
o [optional] Java workshop experimenting all the above topics (raw)
o TLS, mTLS; [optional] Exposing https endpoints on a Spring Boot App
o Web Sessions and Cookies
o Security Architecture Overview: DMZ vs Intranet, WAF, Security Proxy
- OWASP Web App Top 10 Vulnerabilities (link)
o Cross-Site Request Forgery (CSRF)
o Cross-Origin Resource Sharing (CORS)
o Injection of SQL/NoSQL/JPQL, javascript (XSS, CSP), OS commands, url parts (SSRF)
o Risks of handling files: upload, zips, XML/YAML attacks, insecure deserialization, viruses
o Vulnerable Dependencies (CVE): fixing strategies; security scanning tools
- OWASP API Security Top 10 Vulnerabilities (link)
o Broken Function- or Object- Level Authorization
o Excessive Data Exposure
o Lack of Resources & Rate Limiting
o Mass Assignment
o Flaws in Configuration, Monitoring, and Deployment
- Securing Applications with Spring
o Authentication: Form Login, Basic, API Token, Pre-Auth headers, JWT token
o Function-Level Authorization: URL-patterns and annotations, Role- vs Authority- based
o Spring Security Architecture, writing a custom filter, debugging
o Object-Level Authorization: data jurisdiction, permission evaluator, data visibility
o Unit-Testing Backend Authorization
- OAuth2 (4-5 hours)
o Tokens, Actors, Front- vs Back- channel, Single-Sign On (SSO)
o Flows: Authorization Code, Client Credentials, Implicit Flow Authorization Code+PKCE
o Social Login (eg “login with Google”), OpenID Connect
o Workshop: Spring OAuth using KeyCloak
o [optional deep-dive] Example attacks on OAuth; dissecting the exchanges (2 hours)
Page 15 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Code: [Link]
Agenda:
- Chapter 1: Efficient Reading & Searching
o Eager vs Lazy Loading
o JPA 1st Level Cache
o Ways to fix N+1 Queries problem
o Paginated Queries: pitfalls & best practices
o Dynamic Queries: JPQL+=, Criteria, metamodel, specifications, conditional JPQL, and QueryDSL
- Chapter 2: Rich & Performant Entity Model
o Deep (@Embedded), Guarded Entities (DDD-style) with Semantic IDs
o Primitive vs Reference Entity vs enum
o Challenging JPA Links: bidirectional, and @ManyToOne
o Entity hashCode/equals fallacy
o Best practices storing files in DB (CLOB/BLOB)
- Chapter 3: Efficient Transactions
o @Transactional mechanics, propagation, rollback, after commit hooks
o Dirty checks, auto-flushing & write-behind
o How to detect and avoid JDBC Connection Pool Starvation
o Transaction control best practices
- Chapter 4: Updating Entities
o Concurrency Control using Optimistic and Pessimistic locks
o Generating Primary Key efficiently
o Demo: High-performance JPA data import using Spring Batch
o [opt] Bulk update JPQL queries – pitfalls
- Chapter 5: Caching (optional)
o Enabling Second-level Cache for Entities and Queries; tuning
o Comparison with Spring @Cacheable
Page 16 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Prerequisites: Solid knowledge of the Java Language. Ideally: prior contact with performance issues.
Prep-work:
- Clone + Import Profiling Project: [Link]
- Install tools: VisualVM, Java Mission Control
- Clone + Import Main Project: [Link]
- Think of performance issues you encountered by now; ask your friends for more ☺
- [optional] Study in advance heap-dumps of some memory leaks, available here
- (optional, if using in project) CompletableFuture Self-study: Intro Video and Workshop Code
Agenda:
- Introduction:
o War stories from participants (round table)
o Key Concepts, Metrics and Questions
o Principles and Strategies to Improve Performance
o Common bottlenecks of backend systems
- Multi-threading
o Thread Pools mechanics, queue size, thread count, usage patterns
o Multi-threading Risks: race bugs, deadlocks, thread pool starvation
o Concurrency Control: synchronized, atomic primitives, synchronized+concurrent collections
o [upon request] Concurrency Primitives: Lock, Semaphore, CyclicBarrier, wait-notify
o Exercise: Designing a thread-safe concurrent workflow
o Non-blocking concurrency with CompletableFutures, Reactive and Virtual Threads (java21)
o Spring Framework support: ThreadPoolTaskExecutor, non-blocking HTTP Endpoints, @Async
o Exercise: parallelizing a non-blocking REST API
o Parallel streams: mechanics, best practices, pitfalls
- [optional] CompletableFuture deep dive workshop (4h – 8h with participants hands-on) - code
o Combining, Chaining
o Exception handling
o Controlling Parallelism
o Best Practices and Common Patterns for Non-blocking Flows
o Testing & Debugging
o Advanced: Tracing (ThreadLocal), Monitoring (Micrometer) & Profiling (JFR)
- Memory Management
o Java Memory Model: Thread Stacks, Metaspace, Heap (old/young/survivor), TLAB
o Garbage Collector: Key concepts, Monitoring, GC Algorithms
o Techniques for using less memory
o Thread Local: best practices, propagation over thread pools, pitfalls
o Heap Dump analysis: retained/shallow heap, GC Roots, profiling allocations
o Exercise: Tracing ten types of Memory Leaks (find some heapdumps here)
- Caching [optional]
o Principles, cost-benefit-risk of caching, core parameters
o What & Where to cache data: comparison
o Maintaining cache consistency: eviction, TTL, distributed cache, best practices
Page 17 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
- Just-In-Time (JIT) Compiler Overview
o JIT mechanics, dynamic optimizations, writing JIT-friendly code
o GraalVM nativeimage
o Exercise: Writing micro-benchmarks with Java Measuring Harness (JMH)
- Tuning JPA Performance 1-2 days (not included⚠️) -- see the JPA topic in my agenda.
o In many Java applications, DB and JPA usage becomes a bottleneck.
Page 18 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Overview:
The first challenge when approaching reactive programming is understanding WHY and WHEN NOT to
use it. Starting from ‘classic’ blocking web endpoints, we’ll benchmark the bottleneck that occurs under
heavy load and then explore the different historical alternatives to Reactor. Besides exploring dozens of
operators, the focus will remain on understanding the signals that drive all reactive flows, as this is the
key to unlocking the mysteries of backpressure, hot publishers and avoiding common pitfalls when
starting to work with Reactor. We will then use this knowledge to approach several typical reactive flows,
drawing conclusions about the best way to write the code to be maintainable and safe. After a roundtrip
of Spring WebFlux features and quirks, we’ll then talk about 2 tough tasks: testing reactive flows and
progressive migration of blocking code to reactive flows, and if there’s time left, about performance
tuning.
Prerequisites:
- Fluency with Functional Programming concepts: .filter() .map(), lambda syntax, immutable
objects
- Prior contact with multi-threaded code
Preparation:
⚠ This is a very challenging workshop ⚠
It’s imperative to allocate 2-8 hours to go through the prep work, alone or in pair programming (ask your
manager)
- The Main Workshop:
During the workshop, we will spend a lot of time solving some prepared problems (eg
C1_Creation.java) for which we’ll try to pass some pre-written unit tests (eg C1_CreationTest.java).
Please🙏 spend several hours on that code in advance to get more familiar with the concepts we’ll
be juggling with for long hard hours.
- Alternatively, check out the ProjectReactor’s official lite workshop with more explained theory is this
(est work time ≥ 3-4 hours): [Link]
- If you get stuck, you can find the solutions on our project’s Git ( eg: ‘[Link]’ )
Code: [Link]
Agenda
- Introduction
o [optional, basics] Recap: functional pipelines with Java8 Streams
o Blocking REST Endpoints: trace a thread pool starvation issue
o Alternatives to Reactive: CompletableFuture, coroutines(kt), Virtual Threads (Project Loom)
o Reactive Streams Spec
o Mono, Flux
o Understanding Marble Diagrams
o Signals: next, complete, error, request, subscribe, cancel
- Core Operators
o Immediate: just, empty, error, never, range, fromIterable
o Delayed: delay, interval, delayElements
o Immediate Operators: distinct, filter, map, first, take, contains, all
Page 19 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
- Enriching Data
o flatMap vs concatMap vs flatMapSequential
o Batching requests: buffer, bufferWindow
o Handling Empty: defaultIfEmpty, switchIfEmpty
o Async filtering [Link]
o Parallelizing work: Tuples, zip, zipWith, zipWhen
o Use-case Context design pattern
- Performing Side Effects
o Fire-and-forget using doOnNext
o Parallelization, cancellation
- [Hands-on] Migrating a blocking codebase to Reactive Programming
o Schedulers: CPU vs IO, best practices, ParallelFlux
o Calling blocking code in a safe way on boundedElastic scheduler
o CompletableFuture integration
o Bridging to a callback-based model: Sinks
o Reactive REST: Endpoints, and WebClient
o Reactive NoSQL: Mongo, Cassandra, Redis
o Reactive SQL: R2DBC
o Reactive Messages: send/receive
o Kafka Streams [optional]: KStream, KTable, Spring Cloud Stream Functions
- Infinite Fluxes
o Preventing cancellation with onErrorContinue
o GroupedFlux
o Time series operators: scan, reduce, window, buffer, sample, merge, concat, combineLatest
o Hot vs Cold Publisher
o In-memory broadcast using Sinks
o Caching Hot Publishers: replay, cache, connect, autoConnect
- Resilience
o Error handling patterns
o Timeout and Retry
o Back-pressure
o Throttling: rate-limiting, resilience4j integration
o Challenges of distributed systems under heavy load - brainstorming
- Testing
o StepVerifier vs .block()
o TestPublisher
o PublisherProbe + custom extension
o Detecting blocking code with BlockHound
o Controlling Virtual Time [optional]
- Debugging, Monitoring and Tuning
o Propagating metadata via Reactor Context
o Checkpoints and [Link]
o Monitoring using .metrics, .elapsed, .timed
- Common Pitfalls and Workarounds
o Not subscribing / Resubscribing to Cold Publisher
o Loosing Data Signals (empty)
o .subscribe()
o Blocking in non-blocking threads
o Unexpected Cancelation
- Review of Code Sample from the audience
Page 20 / 21 Get the most up-to-date version of this document at: [Link]
Training Catalog – Victor Rentea Consulting SRL [Link]
Important: The hourly fee is considerably lower (≅1/3) than the training fee.
The timeslots are booked 1-2 weeks in advance, during lunch time.
Page 21 / 21 Get the most up-to-date version of this document at: [Link]