Posts Tagged ‘Java’
[MunchenJUG] Reliability in Enterprise Software: A Critical Analysis of Automated Testing in Spring Boot Ecosystems (27/Oct/2025)
Lecturer
Philip Riecks is an independent software consultant and educator specializing in Java, Spring Boot, and cloud-native architectures. With over seven years of professional experience in the software industry, Philip has established himself as a prominent voice in the Java ecosystem through his platform, Testing Java Applications Made Simple. He is a co-author of the influential technical book Stratospheric: From Zero to Production with Spring Boot and AWS, which bridges the gap between local development and production-ready cloud deployments. In addition to his consulting work, he produces extensive educational content via his blog and YouTube channel, focusing on demystifying complex testing patterns for enterprise developers.
Abstract
In the contemporary landscape of rapid software delivery, automated testing serves as the primary safeguard for application reliability and maintainability. This article explores the methodologies for demystifying testing within the Spring Boot framework, moving beyond superficial unit tests toward a comprehensive strategy that encompasses integration and slice testing. By analyzing the “Developer’s Dilemma”—the friction between speed of delivery and the confidence provided by a robust test suite—this analysis identifies key innovations such as the “Testing Pyramid” and specialized Spring Boot test slices. The discussion further examines the technical implications of external dependency management through tools like Testcontainers and WireMock, advocating for a holistic approach that treats test code with the same rigor as production logic.
The Paradigm Shift in Testing Methodology
Traditional software development often relegated testing to a secondary phase, frequently outsourced to separate quality assurance departments. However, the rise of DevOps and continuous integration has necessitated a shift toward “test-driven” or “test-enabled” development. Philip Riecks identifies that the primary challenge for developers is not the lack of tools, but the lack of a clear strategy. Testing is often perceived as a bottleneck rather than an accelerator.
The methodology proposed focuses on the Testing Pyramid, which prioritizes a high volume of fast, isolated unit tests at the base, followed by a smaller number of integration tests, and a minimal set of end-to-end (E2E) tests at the apex. The innovation in Spring Boot testing lies in its ability to provide “Slice Testing,” allowing developers to load only specific parts of the application context (e.g., the web layer or the data access layer) rather than the entire infrastructure. This approach significantly reduces test execution time while maintaining high fidelity.
Architectural Slicing and Context Management
One of the most powerful features of the Spring Boot ecosystem is its refined support for slice testing via annotations. This allows for an analytical approach to testing where the scope of the test is strictly defined by the architectural layer under scrutiny.
- Web Layer Testing: Using
@WebMvcTest, developers can test REST controllers without launching a full HTTP server. This slice provides a mocked environment where the web infrastructure is active, but business services are replaced by mocks (e.g., using@MockBean). - Data Access Testing: The
@DataJpaTestannotation provides a specialized environment for testing JPA repositories. It typically uses an in-memory database by default, ensuring that database interactions are verified without the overhead of a production-grade database. - JSON Serialization:
@JsonTestisolates the serialization and deserialization logic, ensuring that data structures correctly map to their JSON representations.
This granular control prevents “Context Bloat,” where tests become slow and brittle due to the unnecessary loading of the entire application environment.
Code Sample: A Specialized Controller Test Slice
@WebMvcTest(UserRegistrationController.class)
class UserRegistrationControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRegistrationService registrationService;
@Test
void shouldRegisterUserSuccessfully() throws Exception {
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\": \"priecks\", \"email\": \"philip@example.com\"}"))
.andExpect(status().isCreated());
}
}
Managing External Dependencies: Testcontainers and WireMock
A significant hurdle in integration testing is the reliance on external systems such as databases, message brokers, or third-party APIs. Philip emphasizes the move away from “In-Memory” databases (like H2) for testing production-grade applications, citing the risk of “Environment Parity” issues where H2 behaves differently than a production PostgreSQL instance.
The integration of Testcontainers allows developers to spin up actual Docker instances of their production infrastructure during the test lifecycle. This ensures that the code is tested against the exact same database engine used in production. Similarly, WireMock is utilized to simulate external HTTP APIs, allowing for the verification of fault-tolerance mechanisms like retries and circuit breakers without depending on the availability of the actual external service.
Consequences of Testing on Long-term Maintainability
The implications of a robust testing strategy extend far beyond immediate bug detection. A well-tested codebase enables fearless refactoring. When developers have a “safety net” of automated tests, they can update dependencies, optimize algorithms, or redesign components with the confidence that existing functionality remains intact.
Furthermore, Philip argues that the responsibility for quality must lie with the engineer who writes the code. In an “On-Call” culture, the developer who builds the system also runs it. This ownership model, supported by automated testing, transforms software engineering from a process of “handing over” code to one of “carefully crafting” resilient systems.
Conclusion
Demystifying Spring Boot testing requires a transition from viewing tests as a chore to seeing them as a fundamental engineering discipline. By leveraging architectural slices, managing dependencies with Testcontainers, and adhering to the Testing Pyramid, developers can build applications that are not only functional but also sustainable. The ultimate goal is to reach a state where testing provides joy through the confidence it instills, ensuring that the software remains a robust asset for the enterprise rather than a source of technical debt.
Links:
Clojure: A Modern Lisp for Durable, Concurrent Software
Clojure: A Modern Lisp for Durable, Concurrent Software
In the evolving landscape of programming languages, Clojure distinguishes itself not through novelty or aggressive feature growth, but through deliberate restraint. Rather than chasing trends, it revisits enduring principles of computer science—immutability, functional composition, and symbolic computation—and applies them rigorously to contemporary software systems. This approach results in a language that feels both deeply rooted in tradition and sharply attuned to modern challenges.
Clojure appeals to developers and organizations that prioritize long-term correctness, conceptual coherence, and system resilience over short-term convenience.
What Clojure Is and What It Aims to Solve
Clojure is a functional, dynamically typed programming language that runs primarily on the Java Virtual Machine. It is a modern Lisp, and as such it adopts a uniform syntax in which code is represented as structured data. This design choice enables powerful programmatic manipulation of code itself, while also enforcing consistency across the language.
Unlike many earlier Lisp dialects, Clojure was explicitly designed for production systems. It assumes the presence of large codebases, multiple teams, and long-lived services. As a result, its design is deeply influenced by concerns such as concurrency, data integrity, and integration with existing ecosystems.
Historical Context and Design Motivation
Rich Hickey introduced Clojure publicly in 2007 after years of observing recurring failures in large software systems. His critique focused on the way mainstream languages conflate identity, state, and value. In mutable systems, objects change over time, and those changes must be coordinated explicitly when concurrency is involved. The resulting complexity often exceeds human reasoning capacity.
Clojure responds by redefining the problem. Instead of allowing values to change, it treats values as immutable and represents change as a controlled transition between values. This shift in perspective underpins nearly every aspect of the language.
Immutability as a Foundational Principle
In Clojure, immutability is the default. Data structures such as vectors, maps, and sets never change in place. Instead, operations that appear to modify data return new versions that share most of their internal structure with the original.
(def user {:name "Alice" :role "admin"})
(def updated-user (assoc user :role "editor"))
;; user remains unchanged
;; updated-user reflects the new role
Because values never mutate, functions cannot introduce hidden side effects. This dramatically simplifies reasoning, testing, and debugging, especially in concurrent environments.
Functional Composition in Practice
Clojure encourages developers to express computation as the transformation of data through a series of functions. Rather than focusing on control flow and state transitions, programs describe what should happen to data.
(defn even-squares [numbers]
(->> numbers
(filter even?)
(map #(* % %))))
In this example, data flows through a pipeline of transformations. Each function is small, focused, and easily testable, which encourages reuse and composability over time.
Concurrency Through Explicit State Management
Clojure’s concurrency model separates identity from value. State is managed through explicit reference types, while the values themselves remain immutable. This design makes concurrent programming safer and more predictable.
(def counter (atom 0))
(swap! counter inc)
For coordinated updates across multiple pieces of state, Clojure provides software transactional memory, allowing several changes to occur atomically.
(def account-a (ref 100))
(def account-b (ref 50))
(dosync
(alter account-a - 10)
(alter account-b + 10))
Macros and Language Extension
Because Clojure code is represented as data, macros can transform programs before evaluation. This allows developers to introduce new syntactic constructs that feel native to the language rather than external utilities.
(defmacro unless [condition & body]
`(if (not ~condition)
(do ~@body)))
Although macros should be used with care, they play an important role in building expressive and coherent abstractions.
Interoperability with Java
Despite its distinct philosophy, Clojure integrates seamlessly with Java. Java classes can be instantiated and methods invoked directly, allowing developers to reuse existing libraries and infrastructure.
(import java.time.LocalDate)
(LocalDate/now)
Comparison with Java
Although Clojure and Java share the JVM, they differ fundamentally in how they model software. Java emphasizes object-oriented design, mutable state, and explicit control flow. Clojure emphasizes immutable data, functional composition, and explicit state transitions.
While Java has incorporated functional features over time, its underlying model remains object-centric. Clojure offers a more radical rethinking of program structure, often resulting in smaller and more predictable systems.
Comparison with Scala
Scala and Clojure are often compared as functional alternatives on the JVM, yet their philosophies diverge significantly. Scala embraces expressive power through advanced typing and rich abstractions, whereas Clojure seeks to reduce complexity by minimizing the language itself.
Both approaches are valid, but they reflect different beliefs about how developers best manage complexity.
Closing Perspective
Clojure is not designed for universal adoption. It demands a shift in how developers think about state, time, and behavior. However, for teams willing to embrace its principles, it offers a disciplined and coherent approach to building software that remains understandable, correct, and adaptable over time.
Kerberos in the JDK: A Deep Technical Guide for Java Developers and Architects
Kerberos remains one of the most important authentication protocols in enterprise computing. Although it is often perceived as legacy infrastructure, it continues to underpin authentication in corporate networks, distributed data platforms, and Windows domains. For Java developers working in enterprise environments, understanding how Kerberos integrates with the JDK is not optional — it is frequently essential.
This article provides a comprehensive, architectural-level explanation of the Kerberos tooling available directly within the JDK. The objective is not merely to demonstrate configuration snippets, but to clarify how the pieces interact internally so that developers, architects, and staff engineers can reason about authentication flows, diagnose failures, and design secure systems with confidence.
Kerberos Support in the JDK: An Architectural Overview
The JDK provides native support for Kerberos through three primary layers: the internal Kerberos protocol implementation, JAAS (Java Authentication and Authorization Service), and JGSS (Java Generic Security Services API). These layers operate together to allow a Java process to authenticate as a principal, acquire credentials, and establish secure contexts with remote services.
At the lowest level, the JDK contains a complete Kerberos protocol stack implementation located insun.security.krb5. This implementation performs the AS, TGS, and AP exchanges defined by the Kerberos protocol. Although this layer is not intended for direct application use, it is important to understand that the JVM does not require external Kerberos libraries to function as a Kerberos client.
Above the protocol implementation sits JAAS, which is responsible for authentication and credential acquisition. JAAS provides the abstraction layer that allows a Java process to log in as a principal using a password, a keytab, or an existing ticket cache.
Finally, the JDK exposes JGSS through the org.ietf.jgss package. JGSS is the API used to generate and validate Kerberos tokens, negotiate security mechanisms such as SPNEGO, and establish secure contexts between clients and services.
In practice, enterprise Java applications almost always use JAAS to obtain credentials and JGSS to perform service authentication.
JAAS and the Krb5LoginModule
JAAS serves as the authentication entry point for Kerberos within the JVM. The central class isjavax.security.auth.login.LoginContext, which delegates authentication to one or more login modules defined in a JAAS configuration file.
For Kerberos authentication, the relevant module iscom.sun.security.auth.module.Krb5LoginModule, which is bundled with the JDK. This login module supports multiple credential acquisition strategies, including interactive password login, keytab-based login for services, and reuse of an existing operating system ticket cache.
A typical JAAS configuration for a service using a keytab might look as follows:
Client {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=true
keyTab="/etc/security/keytabs/app.keytab"
principal="appuser@COMPANY.COM"
storeKey=true
doNotPrompt=true;
};
Once authentication succeeds, JAAS produces a Subject. This object represents the authenticated identity within the JVM and contains the Kerberos principal along with private credentials such as the Ticket Granting Ticket (TGT).
The Subject becomes the in-memory security identity for the application. Code can be executed under this identity using Subject.doAs, which ensures that downstream security operations use the acquired Kerberos credentials.
JGSS and Security Context Establishment
After credentials are acquired, the next step is to authenticate to a remote service. This is performed through the Java GSS-API implementation provided in theorg.ietf.jgss package.
The central abstraction in JGSS is the GSSContext, which represents a security context between two peers. The GSSManager factory is used to create names, credentials, and contexts. During context establishment, Kerberos tickets are exchanged and validated transparently by the JVM.
On the client side, the application creates a GSSName representing the service principal, then initializes a GSSContext. The resulting token is transmitted to the server, often via an HTTPAuthorization: Negotiate header.
On the server side, the application accepts the token using acceptSecContext, which validates the ticket, verifies authenticity, and establishes a shared session key. Mutual authentication can be requested so that both client and server verify each other’s identities.
Under the hood, JGSS relies on the Kerberos mechanism identified by OID 1.2.840.113554.1.2.2. When SPNEGO is involved, the negotiation mechanism uses OID 1.3.6.1.5.5.2 to determine the appropriate underlying security protocol.
Kerberos Configuration in the JVM
The JVM reads Kerberos configuration from a krb5.conf file, typically located under${java.home}/lib/security or specified via the-Djava.security.krb5.conf system property.
Several JVM system properties significantly influence Kerberos behavior. For example, enabling -Dsun.security.krb5.debug=true produces extremely detailed protocol-level logs, including encryption types, ticket exchanges, and key version numbers. This flag is invaluable when diagnosing authentication failures.
Another important property is -Djavax.security.auth.useSubjectCredsOnly. When set to true (the default), the JVM will only use credentials present in the currentSubject. When set to false, the JVM may fall back to native operating system credentials, which is often necessary in SPNEGO-enabled web applications.
Ticket Cache and Operating System Integration
The JDK can integrate with an operating system’s Kerberos ticket cache. On Unix systems, this typically corresponds to the cache generated by the kinit command. JAAS can be configured with useTicketCache=true to reuse these credentials instead of requiring a password or keytab.
On Windows, the JVM can integrate with the Local Security Authority (LSA), allowing Java applications to authenticate transparently as the currently logged-in domain user.
SASL and GSSAPI Support
Beyond HTTP authentication, the JDK also provides SASL support through thejavax.security.sasl package. The GSSAPI mechanism enables Kerberos authentication for protocols such as LDAP, SMTP, and custom TCP services.
Technologies such as Apache Kafka, enterprise LDAP servers, and distributed data platforms frequently leverage SASL/GSSAPI under the hood. From the JVM’s perspective, the mechanism ultimately delegates to the same JGSS implementation used for HTTP-based SPNEGO authentication.
Encryption Types and Cryptographic Considerations
Modern JDK versions support AES-based encryption types, including AES-128 and AES-256. Older algorithms such as DES have been removed or disabled due to security concerns. Since Java now ships with unlimited cryptographic strength enabled by default, no additional policy configuration is typically required for strong Kerberos encryption.
Encryption type mismatches between the KDC and the JVM are a frequent source of authentication errors, particularly in legacy environments.
Debugging and Operational Realities
Most Kerberos failures in Java applications are not caused by cryptographic defects but by configuration issues. Common causes include DNS misconfiguration, principal mismatches, clock skew between systems, and incorrect keytab versions.
Effective troubleshooting requires correlating JVM debug logs with KDC logs and verifying ticket cache state using operating system tools. Engineers who understand the protocol exchange sequence can usually isolate failures quickly by determining whether the breakdown occurs during AS exchange, TGS exchange, or service ticket validation.
What the JDK Does Not Provide
It is important to clarify that the JDK does not include a Kerberos Key Distribution Center, administrative tools such as kadmin, or command-line utilities for ticket management. Those capabilities are provided by implementations such as MIT Kerberos, Heimdal, or Active Directory.
The JDK functions strictly as a Kerberos client and service runtime.
Conclusion
Kerberos support in the JDK is both mature and deeply integrated. Through JAAS, the JVM can acquire credentials using password, keytab, or ticket cache. Through JGSS, it can establish secure, mutually authenticated contexts with remote services. Through SASL, it can extend this authentication model to non-HTTP protocols.
For architects and staff engineers, understanding these layers is essential when designing secure enterprise systems. For junior developers, gaining familiarity with JAAS, Subject, and GSSContextprovides a strong foundation for working within corporate authentication environments.
Kerberos may not be fashionable, but it remains foundational. In the Java ecosystem, it is not an external add-on — it is part of the platform itself.
Why a Spring Boot Application Often Starts Faster with `java -jar` Than from IntelliJ IDEA
It is not unusual for developers to observe a mildly perplexing phenomenon: a Spring Boot application appears to start faster when executed from the command line using java -jar myapp.jar than when launched directly from IntelliJ IDEA. At first glance, this seems counterintuitive. One might reasonably assume that a so-called “uber-jar” (or fat jar), which packages the application alongside all of its dependencies into a single archive, would incur additional overhead during startup—perhaps due to decompression or archive handling.
In practice, the opposite frequently occurs. The explanation lies not in archive extraction, but in classpath topology, runtime instrumentation, and subtle differences in JVM execution environments. Understanding these mechanisms requires a closer look at how Spring Boot launches applications and how the JVM behaves under different conditions.
The Uber-Jar Is Not Fully Extracted
The most common misconception is that running a Spring Boot fat jar involves unzipping the entire archive before the application can start. This assumption is incorrect.
When executing:
java -jar myapp.jar
Spring Boot delegates startup to its own launcher, typically org.springframework.boot.loader.JarLauncher. This launcher does not extract the archive to disk. Instead, it constructs a specialized classloader capable of resolving nested JAR entries directly from within the archive. Classes and resources are loaded lazily, as they are requested by the JVM. The archive is treated as a structured container rather than a compressed bundle that must be fully expanded.
There is, therefore, no significant “unzipping” phase that would systematically slow down execution. If anything, this consolidated packaging can reduce certain filesystem costs.
Classpath Topology and Filesystem Overhead
The most consequential difference between IDE execution and packaged execution is the structure of the classpath.
When running from IntelliJ IDEA, the classpath typically consists of compiled classes located in target/classes (or build/classes) alongside a large number of individual dependency JARs resolved from the local Maven or Gradle cache. It is not uncommon for a moderately sized Spring Boot application to reference several hundred classpath entries.
Each class resolution performed by the JVM may involve filesystem lookups across these numerous locations. On systems where filesystem metadata operations are relatively expensive—such as Windows environments with active antivirus scanning or network-mounted drives—this fragmented classpath structure can introduce measurable overhead during class loading and Spring’s extensive classpath scanning.
By contrast, a fat jar consolidates application classes and dependencies into a single archive. While internally structured, it presents a smaller number of filesystem entry points to the operating system. The reduction in directory traversal and metadata resolution can, in certain environments, lead to faster class discovery and resource loading.
What appears to be additional packaging complexity may in fact simplify the underlying I/O behavior.
The Impact of Debug Agents and IDE Instrumentation
Another frequently overlooked factor is the presence of debugging agents. When an application is launched from IntelliJ IDEA, even in “Run” mode, the JVM is often started with the Java Debug Wire Protocol (JDWP) agent enabled. This typically appears as a -agentlib:jdwp=... argument in the JVM configuration.
The presence of a debug agent subtly alters JVM behavior. The runtime must preserve additional metadata to support breakpoints and step execution. Certain optimizations may be slightly constrained, and class loading can involve additional bookkeeping. While the performance penalty is not dramatic, it is sufficient to influence startup time in non-trivial applications.
When executing java -jar from the command line, the JVM is usually started without any debugging agent attached. The runtime environment is therefore leaner and more representative of production conditions. The absence of instrumentation alone can account for a noticeable reduction in startup duration.
Spring Boot DevTools and Restart Classloaders
A particularly common source of discrepancy is the presence of spring-boot-devtools on the IDE classpath. DevTools is designed to improve developer productivity by enabling automatic restarts and class reloading. To achieve this, it creates a layered classloader arrangement that separates application classes from dependencies and monitors the filesystem for changes.
This restart mechanism introduces additional classloader complexity and file-watching infrastructure. While extremely useful during development, it is not free from a performance standpoint. If DevTools is present when running inside IntelliJ but excluded from the packaged artifact, then the two execution modes are not equivalent. The IDE run effectively includes additional runtime behavior that the fat jar does not.
In many cases, this single difference explains several seconds of startup variance.
JVM Ergonomics and Configuration Differences
Subtle variations in JVM configuration can also contribute to timing differences. IntelliJ may inject specific JVM options, alter heap sizing defaults, or enable particular runtime flags. The command-line invocation, unless explicitly configured, may rely on different ergonomics chosen by the JVM.
Heap size, garbage collector selection, tiered compilation thresholds, and class verification settings can all influence startup time. Spring Boot applications, which perform extensive reflection, annotation processing, and condition evaluation during initialization, are particularly sensitive to classloading and JIT behavior.
Ensuring that both execution paths use identical JVM arguments is essential for a scientifically valid comparison.
Filesystem Caching Effects
Operating system caching further complicates informal measurements. If the application is launched once from the IDE and then immediately launched again using java -jar, the second execution benefits from warmed filesystem caches. JAR contents and metadata may already reside in memory, reducing disk access latency.
Without controlling for caching effects—either by rebooting, clearing caches, or running multiple iterations and averaging results—observed differences may reflect environmental artifacts rather than structural advantages.
Spring Boot Startup Characteristics
It is important to remember that Spring Boot startup is classpath-intensive. The framework performs component scanning, auto-configuration condition evaluation, metadata resolution from META-INF resources, and reflection-based inspection of annotations.
These processes are highly sensitive to classloader behavior and I/O patterns. A consolidated archive can, under certain conditions, reduce the cumulative cost of classpath traversal.
From a systems perspective, fewer filesystem roots and more predictable access patterns can outweigh the negligible overhead of archive handling.
Conclusion: Leaner Runtime, Faster Startup
The faster startup of a Spring Boot application via java -jar is neither anomalous nor paradoxical. It typically reflects a cleaner runtime environment: fewer agents, no development tooling, simplified classpath topology, and production-oriented JVM ergonomics.
The fat jar is not slower because it is not being fully decompressed. On the contrary, its consolidated structure can streamline class loading. Meanwhile, the IDE environment often introduces layers of instrumentation and classloader indirection designed for developer convenience rather than performance parity.
For accurate benchmarking, one must eliminate debugging agents, disable DevTools, align JVM arguments, and control for filesystem caching. Only then can meaningful conclusions be drawn.
In short, the difference is not about packaging overhead. It is about execution context. And in many cases, the command-line invocation more closely resembles the optimized conditions under which the application is intended to run in production.
Option[Scala] != Optional
Java Optional and Scala Option: A Shared Goal, Divergent Philosophies
The absence of a value is one of the most deceptively complex problems in software engineering. For decades, mainstream programming languages relied on a single mechanism to represent it: null. While convenient, this design choice has proven to be one of the most costly abstractions in computing, as famously described by Tony Hoare as his “billion-dollar mistake”. Both Java and Scala eventually introduced explicit abstractions—Optional in Java and Option in Scala—to address this long-standing issue. Although these constructs appear similar on the surface, their design, intended usage, and expressive power differ in ways that reflect the deeper philosophies of their respective languages.
Understanding these differences requires examining not only their APIs, but also how they are used in real code.
Historical Background and Design Motivation
Scala introduced Option as a core concept from its earliest releases. Rooted in functional programming traditions, Scala treats the presence or absence of a value as a fundamental modeling concern. The language encourages developers to encode uncertainty directly into types and to resolve it through composition rather than defensive checks.
Java’s Optional, introduced much later in Java 8, emerged in a very different context. It was part of a cautious modernization effort that added functional elements without breaking compatibility with an enormous existing ecosystem. As a result, Optional was intentionally constrained and positioned primarily as a safer alternative to returning null from methods.
Modeling Presence and Absence
In Scala, an optional value is represented as either Some(value) or None. This is a closed hierarchy, and the distinction is explicit at all times.
def findUser(id: Int): Option[String] =
if (id == 1) Some("Alice") else None
In Java, the equivalent method returns an Optional created through a factory method.
Optional<String> findUser(int id) {
return id == 1 ? Optional.of("Alice") : Optional.empty();
}
At first glance, these examples appear nearly identical. The difference becomes more pronounced in how these values are consumed and composed.
Consumption and Transformation
Scala’s Option integrates deeply with the language’s expression-oriented style. Transformations are natural and idiomatic, and optional values behave much like collections with zero or one element.
val upperName =
findUser(1)
.map(_.toUpperCase)
.filter(_.startsWith("A"))
In this example, absence propagates automatically. If findUser returns None, the entire expression evaluates to None without any additional checks.
Java’s Optional supports similar operations, but the style is more constrained and often more verbose.
Optional<String> upperName =
findUser(1)
.map(String::toUpperCase)
.filter(name -> name.startsWith("A"));
Although the semantics are similar, Java’s syntax and type system make these chains feel more deliberate and less fluid, reinforcing the idea that Optional is a special-purpose construct rather than a universal modeling tool.
Extracting Values: Intentional Friction vs Idiomatic Resolution
Scala encourages developers to resolve optional values through pattern matching or total functions such as getOrElse.
val name = findUser(2) match {
case Some(value) => value
case None => "Unknown"
}
A concise fallback can also be expressed directly:
val name = findUser(2).getOrElse("Unknown")
In Java, extracting a value is intentionally more guarded. While get() exists, its use is discouraged in favor of safer alternatives.
String name = findUser(2).orElse("Unknown");
The difference is cultural rather than technical. In Scala, resolving an Option is a normal part of control flow. In Java, consuming an Optional is treated as an exceptional act that should be handled carefully and explicitly.
Optional Values in Composition
Scala excels at composing multiple optional computations using flatMap or for-comprehensions.
for {
user <- findUser(1)
email <- findEmail(user)
} yield email
This code expresses dependent computations declaratively. If any step yields None, the entire expression evaluates to None.
In Java, the same logic requires more explicit wiring.
Optional<String> email =
findUser(1).flatMap(user -> findEmail(user));
While functional, the Java version becomes less readable as the number of dependent steps increases.
Usage as Fields and Parameters
Scala allows Option to be used freely as a field or parameter type, which is common and idiomatic.
case class User(name: String, email: Option[String])
Java, by contrast, discourages the use of Optional in fields or parameters, even though it is technically possible.
// Generally discouraged
class User {
Optional<String> email;
}
This contrast highlights Scala’s confidence in Option as a foundational abstraction, while Java treats Optional as a boundary marker in API design.
Philosophical Implications
The contrast between Option and Optional mirrors the broader philosophies of Scala and Java. Scala embraces expressive power and abstraction to manage complexity. Java favors incremental evolution and clarity, even when that limits expressiveness.
Both approaches are valid, and both significantly reduce errors when used appropriately.
Conclusion
Java’s Optional and Scala’s Option address the same fundamental problem, yet they do so in ways that reflect the deeper identity of their ecosystems. Scala’s Option is a first-class participant in program structure, encouraging composition and declarative reasoning. Java’s Optional is a carefully scoped enhancement, designed to improve API safety without redefining the language.
What appears to be a minor syntactic distinction is, in reality, a clear illustration of two distinct approaches to software design on the JVM.
[DevoxxFR2013] Strange Loops: A Mind-Bending Journey Through Java’s Hidden Curiosities
Lecturers
Guillaume Tardif has been crafting software since 1998, primarily in the Java and JEE ecosystem. His roles span technical leadership, agile coaching, and architecture across consulting firms and startups. Now an independent consultant, he has presented at Agile Conference 2009, XP Days 2009, and Devoxx France 2012, blending technical depth with philosophical inquiry.
Eric Lefevre-Ardant began programming in Java in 1996. His career alternates between Java consultancies and startups, currently as an independent consultant. Together, they explore the boundaries of code, inspired by Douglas Hofstadter’s Gödel, Escher, Bach.
Abstract
Guillaume Tardif and Eric Lefevre-Ardant invite you on a disorienting, delightful promenade through the strangest corners of the Java language — a journey inspired by Douglas Hofstadter’s exploration of self-reference, recursion, and emergent complexity. Through live-coded puzzles, optical illusions in syntax, and meta-programming mind-benders, they reveal how innocent-looking code can loop infinitely, reflect upon itself, or even generate its own source. The talk escalates from simple for loop quirks to genetic programming, culminating in a real-world example of self-replicating machines: the RepRap 3D printer. This is not a tutorial — it is a meditation on the nature of code, computation, and creation.
The Hofstadter Inspiration
Douglas Hofstadter’s Gödel, Escher, Bach explores strange loops — hierarchical systems that refer to themselves, creating emergent meaning. The presenters apply this lens to Java: a language designed for clarity, yet capable of profound self-referential trickery. They begin with a simple puzzle:
for (int i = 0; i < 10; i++) {
System.out.println(i);
i--;
}
What does it print? The answer — an infinite loop — reveals how loop variables can be manipulated in ways that defy intuition. This sets the tone: code is not just logic; it is perception.
Syntactic Illusions and Parser Tricks
The duo demonstrates Java constructs that appear valid but behave unexpectedly due to parser ambiguities. Consider:
label: for (int i = 0; i < 5; i++) {
if (i == 3) break label;
System.out.println(i);
}
The label: seems redundant — until combined with nested loops and continue label to skip outer iterations. They show how the most vexing parse confuses even experienced developers:
new Foo(new Bar());
// vs
new Foo(new Bar()); // same?
Subtle whitespace and operator precedence create optical illusions in code readability.
Reflection and Meta-Programming
Java’s reflection API enables programs to inspect and modify themselves at runtime. The presenters write a method that prints its own source code — a quines-like construct:
public static void printSource() throws Exception {
String path = Quine.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Files.lines(Paths.get(path)).forEach(System.out::println);
}
They escalate to bytecode manipulation with Javassist, generating classes dynamically. This leads to a discussion of genetic programming: modeling source code as a tree, applying mutations and crossovers, and evolving solutions. While more natural in Lisp, Java implementations exist using AST parsing and code generation.
The Ultimate Strange Loop: Self-Replicating Machines
The talk culminates with the RepRap project — an open-source 3D printer designed to print its own parts. Begun in 2005, RepRap achieved partial self-replication by 2008, printing about 50% of its components. The presenters display a physical model, explaining how the printer’s design files, firmware, and mechanical parts form a closed loop of creation.
They draw parallels to John von Neumann’s self-replicating machines and Conway’s Game of Life — systems where simple rules generate infinite complexity. In Java terms, this is the ultimate quine: a program that outputs a machine that runs the program.
Philosophical Implications
What does it mean for code to reflect, replicate, or evolve? The presenters argue that programming is not just engineering — it is art, philosophy, and exploration. Strange loops remind us that:
- Clarity can mask complexity
- Simplicity can generate infinity
- Code can transcend its creator
They close with a call to embrace curiosity: write a quine, mutate an AST, print a 3D part. The joy of programming lies not in solving known problems, but in discovering new ones.
Links
Hashtags: #StrangeLoops #JavaPuzzlers #SelfReference #GeneticProgramming #RepRap #GuillaumeTardif #EricLefevreArdant
[DevoxxUK2025] Concerto for Java and AI: Building Production-Ready LLM Applications
At DevoxxUK2025, Thomas Vitale, a software engineer at Systematic, delivered an inspiring session on integrating generative AI into Java applications to enhance his music composition process. Combining his passion for music and software engineering, Thomas showcased a “composer assistant” application built with Spring AI, addressing real-world use cases like text classification, semantic search, and structured data extraction. Through live coding and a musical performance, he demonstrated how Java developers can leverage large language models (LLMs) for production-ready applications, emphasizing security, observability, and developer experience. His talk culminated in a live composition for an audience-chosen action movie scene, blending AI-driven suggestions with human creativity.
The Why Factor for AI Integration
Thomas introduced his “Why Factor” to evaluate hype technologies like generative AI. First, identify the problem: for his composer assistant, he needed to organize and access musical data efficiently. Second, assess production readiness: LLMs must be secure and reliable for real-world use. Third, prioritize developer experience: tools like Spring AI simplify integration without disrupting workflows. By focusing on these principles, Thomas avoided blindly adopting AI, ensuring it solved specific issues, such as automating data classification to free up time for creative tasks like composing music.
Enhancing Applications with Spring AI
Using a Spring Boot application with a Thymeleaf frontend, Thomas integrated Spring AI to connect to LLMs like those from Ollama (local) and Mistral AI (cloud). He demonstrated text classification by creating a POST endpoint to categorize musical data (e.g., “Irish tin whistle” as an instrument) using a chat client API. To mitigate risks like prompt injection attacks, he employed Java enumerations to enforce structured outputs, converting free text into JSON-parsed Java objects. This approach ensured security and usability, allowing developers to swap models without code changes, enhancing flexibility for production environments.
Semantic Search and Retrieval-Augmented Generation
Thomas addressed the challenge of searching musical data by meaning, not just keywords, using semantic search. By leveraging embedding models in Spring AI, he converted text (e.g., “melancholic”) into numerical vectors stored in a PostgreSQL database, enabling searches for related terms like “sad.” He extended this with retrieval-augmented generation (RAG), where a chat client advisor retrieves relevant data before querying the LLM. For instance, asking, “What instruments for a melancholic scene?” returned suggestions like cello, based on his dataset, improving search accuracy and user experience.
Structured Data Extraction and Human Oversight
To streamline data entry, Thomas implemented structured data extraction, converting unstructured director notes (e.g., from audio recordings) into JSON objects for database storage. Spring AI facilitated this by defining a JSON schema for the LLM to follow, ensuring structured outputs. Recognizing LLMs’ potential for errors, he emphasized keeping humans in the loop, requiring users to review extracted data before saving. This approach, applied to his composer assistant, reduced manual effort while maintaining accuracy, applicable to scenarios like customer support ticket processing.
Tools and MCP for Enhanced Functionality
Thomas enhanced his application with tools, enabling LLMs to call internal APIs, such as saving composition notes. Using Spring Data, he annotated methods to make them accessible to the model, allowing automated actions like data storage. He also introduced the Model Context Protocol (MCP), implemented in Quarkus, to integrate with external music software via MIDI signals. This allowed the LLM to play chord progressions (e.g., in A minor) through his piano software, demonstrating how MCP extends AI capabilities across local processes, though he cautioned it’s not yet production-ready.
Observability and Live Composition
To ensure production readiness, Thomas integrated OpenTelemetry for observability, tracking LLM operations like token usage and prompt augmentation. During the session, he invited the audience to choose a movie scene (action won) and used his application to generate a composition plan, suggesting chord progressions (e.g., I-VI-III-VII) and instruments like percussion and strings. He performed the music live, copy-pasting AI-suggested notes into his software, fixing minor bugs, and adding creative touches, showcasing a practical blend of AI automation and human artistry.
Links:
[DevoxxFR2025] Boosting Java Application Startup Time: JVM and Framework Optimizations
In the world of modern application deployment, particularly in cloud-native and microservice architectures, fast startup time is a crucial factor impacting scalability, resilience, and cost efficiency. Slow-starting applications can delay deployments, hinder auto-scaling responsiveness, and consume resources unnecessarily. Olivier Bourgain, in his presentation, delved into strategies for significantly accelerating the startup time of Java applications, focusing on optimizations at both the Java Virtual Machine (JVM) level and within popular frameworks like Spring Boot. He explored techniques ranging from garbage collection tuning to leveraging emerging technologies like OpenJDK’s Project Leyden and Spring AOT (Ahead-of-Time Compilation) to make Java applications lighter, faster, and more efficient from the moment they start.
The Importance of Fast Startup
Olivier began by explaining why fast startup time matters in modern environments. In microservices architectures, applications are frequently started and stopped as part of scaling events, deployments, or rolling updates. A slow startup adds to the time it takes to scale up to handle increased load, potentially leading to performance degradation or service unavailability. In serverless or function-as-a-service environments, cold starts (the time it takes for an idle instance to become ready) are directly impacted by application startup time, affecting latency and user experience. Faster startup also improves developer productivity by reducing the waiting time during local development and testing cycles. Olivier emphasized that optimizing startup time is no longer just a minor optimization but a fundamental requirement for efficient cloud-native deployments.
JVM and Garbage Collection Optimizations
Optimizing the JVM configuration and understanding garbage collection behavior are foundational steps in improving Java application startup. Olivier discussed how different garbage collectors (like G1, Parallel, or ZGC) can impact startup time and memory usage. Tuning JVM arguments related to heap size, garbage collection pauses, and just-in-time (JIT) compilation tiers can influence how quickly the application becomes responsive. While JIT compilation is crucial for long-term performance, it can introduce startup overhead as the JVM analyzes and optimizes code during initial execution. Techniques like Class Data Sharing (CDS) were mentioned as a way to reduce startup time by sharing pre-processed class metadata between multiple JVM instances. Olivier provided practical tips and configurations for optimizing JVM settings specifically for faster startup, balancing it with overall application performance.
Framework Optimizations: Spring Boot and Beyond
Popular frameworks like Spring Boot, while providing immense productivity benefits, can sometimes contribute to longer startup times due to their extensive features and reliance on reflection and classpath scanning during initialization. Olivier explored strategies within the Spring ecosystem and other frameworks to mitigate this. He highlighted Spring AOT (Ahead-of-Time Compilation) as a transformative technology that analyzes the application at build time and generates optimized code and configuration, reducing the work the JVM needs to do at runtime. This can significantly decrease startup time and memory footprint, making Spring Boot applications more suitable for resource-constrained environments and serverless deployments. Project Leyden in OpenJDK, aiming to enable static images and further AOT compilation for Java, was also discussed as a future direction for improving startup performance at the language level. Olivier demonstrated how applying these framework-specific optimizations and leveraging AOT compilation can have a dramatic impact on the startup speed of Java applications, making them competitive with applications written in languages traditionally known for faster startup.
Links:
- Olivier Bourgain: https://www.linkedin.com/in/olivier-bourgain/
- Mirakl: https://www.mirakl.com/
- Spring Boot: https://spring.io/projects/spring-boot
- OpenJDK Project Leyden: https://openjdk.org/projects/leyden/
- Devoxx France LinkedIn: https://www.linkedin.com/company/devoxx-france/
- Devoxx France Bluesky: https://bsky.app/profile/devoxx.fr
- Devoxx France Website: https://www.devoxx.fr/
[DevoxxFR2025] Building an Agentic AI with Structured Outputs, Function Calling, and MCP
The rapid advancements in Artificial Intelligence, particularly in large language models (LLMs), are enabling the creation of more sophisticated and autonomous AI agents – programs capable of understanding instructions, reasoning, and interacting with their environment to achieve goals. Building such agents requires effective ways for the AI model to communicate programmatically and to trigger external actions. Julien Dubois, in his deep-dive session, explored key techniques and a new protocol essential for constructing these agentic AI systems: Structured Outputs, Function Calling, and the Model-Controller Protocol (MCP). Using practical examples and the latest Java SDK developed by OpenAI, he demonstrated how to implement these features within LangChain4j, showcasing how developers can build AI agents that go beyond simple text generation.
Structured Outputs: Enabling Programmatic Communication
One of the challenges in building AI agents is getting LLMs to produce responses in a structured format that can be easily parsed and used by other parts of the application. Julien explained how Structured Outputs address this by allowing developers to define a specific JSON schema that the AI model must adhere to when generating its response. This ensures that the output is not just free-form text but follows a predictable structure, making it straightforward to map the AI’s response to data objects in programming languages like Java. He demonstrated how to provide the LLM with a JSON schema definition and constrain its output to match that schema, enabling reliable programmatic communication between the AI model and the application logic. This is crucial for scenarios where the AI needs to provide data in a specific format for further processing or action.
Function Calling: Giving AI the Ability to Act
To be truly agentic, an AI needs the ability to perform actions in the real world or interact with external tools and services. Julien introduced Function Calling as a powerful mechanism that allows developers to define functions in their code (e.g., Java methods) and expose them to the AI model. The LLM can then understand when a user’s request requires calling one of these functions and generate a structured output indicating which function to call and with what arguments. The application then intercepts this output, executes the corresponding function, and can provide the function’s result back to the AI, allowing for a multi-turn interaction where the AI reasons, acts, and incorporates the results into its subsequent responses. Julien demonstrated how to define function “signatures” that the AI can understand and how to handle the function calls triggered by the AI, showcasing scenarios like retrieving information from a database or interacting with an external API based on the user’s natural language request.
MCP: Standardizing LLM Interaction
While Structured Outputs and Function Calling provide the capabilities for AI communication and action, the Model-Controller Protocol (MCP) emerges as a new standard to streamline how LLMs interact with various data sources and tools. Julien discussed MCP as a protocol that aims to standardize the communication layer between AI models (the “Model”) and the application logic that orchestrates them and provides access to external resources (the “Controller”). This standardization can facilitate building more portable and interoperable AI agentic systems, allowing developers to switch between different LLMs or integrate new tools and data sources more easily. While details of MCP might still be evolving, its goal is to provide a common interface for tasks like function calling, accessing external knowledge, and managing conversational state. Julien illustrated how libraries like LangChain4j are adopting these concepts and integrating with protocols like MCP to simplify the development of sophisticated AI agents. The presentation, rich in code examples using the OpenAI Java SDK, provided developers with the practical knowledge and tools to start building the next generation of agentic AI applications.
Links:
- Julien Dubois: https://www.linkedin.com/in/juliendubois/
- Microsoft: https://www.microsoft.com/
- LangChain4j on GitHub: https://github.com/langchain4j/langchain4j
- OpenAI: https://openai.com/
- Devoxx France LinkedIn: https://www.linkedin.com/company/devoxx-france/
- Devoxx France Bluesky: https://bsky.app/profile/devoxx.fr
- Devoxx France Website: https://www.devoxx.fr/
[Oracle Dev Days 2025] From JDK 21 to JDK 25: Jean-Michel Doudoux on Java’s Evolution
Jean-Michel Doudoux, a renowned Java Champion and Sciam consultant, delivered a session, charting Java’s evolution from JDK 21 to JDK 25. As the next Long-Term Support (LTS) release, JDK 25 introduces transformative features that redefine Java development. Jean-Michel’s talk provided a comprehensive guide to new syntax, APIs, JVM enhancements, and security measures, equipping developers to navigate Java’s future with confidence.
Enhancing Syntax and APIs
Jean-Michel began by exploring syntactic improvements that streamline Java code. JEP 456 in JDK 22 introduces unnamed variables using _, improving clarity for unused variables. JDK 23’s JEP 467 adds Markdown support for Javadoc, easing documentation. In JDK 25, JEP 511 simplifies module imports, while JEP 512’s implicit classes and simplified main methods make Java more beginner-friendly. JEP 513 enhances constructor flexibility, enabling pre-constructor logic. These changes collectively minimize boilerplate, boosting developer efficiency.
Expanding Capabilities with New APIs
The session highlighted APIs that broaden Java’s scope. The Foreign Function & Memory API (JEP 454) enables safer native code integration, replacing sun.misc.Unsafe. Stream Gatherers (JEP 485) enhance data processing, while the Class-File API (JEP 484) simplifies bytecode manipulation. Scope Values (JEP 506) improve concurrency with lightweight alternatives to thread-local variables. Jean-Michel’s practical examples demonstrated how these APIs empower developers to craft modern, robust applications.
Strengthening JVM and Security
Jean-Michel emphasized JVM and security advancements. JEP 472 in JDK 25 restricts native code access via --enable-native-access, enhancing system integrity. The deprecation of sun.misc.Unsafe aligns with safer alternatives. The removal of 32-bit support, the Security Manager, and certain JMX features reflects Java’s modern focus. Performance boosts in HotSpot JVM, Garbage Collectors (G1, ZGC), and startup times via Project Leyden (JEP 483) ensure Java’s competitiveness.
Boosting Productivity with Tools
Jean-Michel covered enhancements to Java’s tooling ecosystem, including upgraded Javadoc, JCMD, and JAR utilities, which streamline workflows. New Java Flight Recorder (JFR) events improve diagnostics. He urged developers to test JDK 25’s early access builds to prepare for the LTS release, highlighting how these tools enhance efficiency and scalability in application development.
Navigating JDK 25’s LTS Future
Jean-Michel wrapped up by emphasizing JDK 25’s role as an LTS release with extended support. He encouraged proactive engagement with early access programs to adapt to new features and deprecations. His session offered a clear, actionable roadmap, empowering developers to leverage JDK 25’s innovations confidently. Jean-Michel’s expertise illuminated Java’s trajectory, inspiring attendees to embrace its evolving landscape.
Links:
Hashtags: #Java #JDK25 #LTS #JVM #Security #Sciam #JeanMichelDoudoux