DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Java

Java is an object-oriented programming language that allows engineers to produce software for multiple platforms. Our resources in this Zone are designed to help engineers with Java program development, Java SDKs, compilers, interpreters, documentation generators, and other tools used to produce a complete application.

icon
Latest Premium Content
Trend Report
Low-Code Development
Low-Code Development
Refcard #216
Java Caching Essentials
Java Caching Essentials
Refcard #400
Java Application Containerization and Deployment
Java Application Containerization and Deployment

DZone's Featured Java Resources

Getting Started With Qdrant: Building Intelligent Search Applications With Java

Getting Started With Qdrant: Building Intelligent Search Applications With Java

By Otavio Santana DZone Core CORE
Enterprise applications seldom rely solely on similarity for information retrieval. For example, e-commerce platforms must recommend products aligned with customer interests while considering availability, pricing, and categories. Document management systems need to retrieve semantically related information while enforcing access permissions. Combining these requirements efficiently is a key challenge in building intelligent search applications. Qdrant, an open-source vector database for similarity search and structured filtering, addresses this challenge effectively. Qdrant enables Java developers and software architects to build applications that integrate semantic understanding with business constraints. Its support for multiple vector representations, advanced filtering, and hybrid retrieval extends its relevance beyond conversational AI and RAG applications. This article examines Qdrant's features, demonstrates local configuration with Docker, and shows integration with enterprise Java using Eclipse JNoSQL. Before implementation, we will review what sets Qdrant apart and where it delivers practical value. Understanding Qdrant: Capabilities and Real-World Applications Qdrant is an open-source vector database written in Rust that combines similarity search with structured data filtering. Its core data structure, the point, links an identifier, vector representations, and an optional JSON payload. This model is particularly relevant for enterprise systems because it lets you apply business constraints during vector retrieval, eliminating the need for separate application-level filtering. For example, in a travel booking application, a customer searching for “a quiet seaside hotel suitable for families” can benefit from semantic similarity to identify relevant accommodations. Payload filters then narrow results by destination, price range, and availability. Qdrant uses both vector and payload indexes to optimize these queries, removing the need to retrieve all similar results before filtering them in Java. In addition to this use case, Qdrant offers several notable capabilities: Advanced payload filtering: Combines numerical ranges, keywords, geographical conditions, and other structured constraints with vector search.Multiple vector representations: Supports dense, sparse, and multi-vector configurations, including named vectors that associate different representations with the same record.Hybrid retrieval: Combines semantic and keyword-oriented retrieval, with ranking fusion strategies that help balance different relevance signals.Memory optimization: Supports vector quantization and on-disk storage configurations, allowing architects to balance memory consumption, latency, and search quality.Deployment flexibility: Supports local containers, self-hosted distributed deployments, and managed cloud environments. Although these features are not unique to Qdrant, its combination of payload-aware indexing and flexible retrieval is especially valuable for applications that require both semantic relevance and structured business rules. Qdrant in Production Qdrant’s published customer stories illustrate its adoption across several industries: Tripadvisor: Uses Qdrant in its AI-powered travel planning experience to retrieve relevant information from a large collection of reviews and travel content.HubSpot: Uses Qdrant to support intelligent AI assistant capabilities, connecting enterprise information with semantic retrieval.Dailymotion: Applies vector search to video recommendations, helping users discover relevant content.OpenTable: Uses Qdrant to improve restaurant discovery through AI-powered recommendations and search. These examples show that vector search extends beyond chatbot applications. Travel platforms, customer service systems, and media applications can use similarity search to improve how users discover information, products, and services. However, Qdrant may not suit every application. Maintaining vector indexes, selecting embedding models, configuring payload indexes, and evaluating relevance all introduce operational and architectural costs. Additionally, a dedicated vector database may be unnecessary if existing database capabilities meet the application's requirements. For Java architects, Qdrant provides a balance between specialized retrieval capabilities and integration flexibility. Next, set up a local environment and explore how Eclipse JNoSQL allows Java applications to interact with Qdrant using a familiar persistence API. Setting Up Qdrant With Docker Qdrant offers several deployment options, such as self-hosted instances, distributed clusters, and managed cloud environments. In this example, we will run Qdrant locally with Docker to demonstrate vector persistence without additional infrastructure or cloud services. Once Docker is installed, start Qdrant using the command from our example repository: Shell docker run --name qdrant-instance \ -p 6333:6333 -p 6334:6334 \ -d qdrant/qdrant Qdrant provides two main endpoints: port 6333 for HTTP requests and the dashboard, and port 6334 for gRPC communication. After starting the container, access the dashboard at http://localhost:6333/dashboard to review the database and its collections. Connecting Qdrant With Enterprise Java Eclipse JNoSQL offers a persistence abstraction for Java applications that integrates with CDI and Jakarta EE technologies. This enables the use of Qdrant across various application styles, such as REST services, batch processing, and background workers, without tightly coupling business logic to the Qdrant driver. While the framework supports Jakarta EE environments, this example uses Java SE with CDI for simplicity. The Maven configuration includes the Qdrant integration, Vector Mapping module, and LangChain4j for local embedding generation: XML <dependency> <groupId>org.eclipse.jnosql.databases</groupId> <artifactId>jnosql-qdrant</artifactId> <version>${jnosql.databases.version}</version> </dependency> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-embeddings-all-minilm-l6-v2-q</artifactId> <version>${langchain4j.embeddings.version}</version> </dependency> Next, configure the connection in META-INF/microprofile-config.properties using the properties from the Qdrant example: Properties files jnosql.vector.database=products jnosql.qdrant.host=localhost jnosql.qdrant.port=6334 jnosql.qdrant.tls=false jnosql.qdrant.collection.distance=COSINE jnosql.qdrant.collection.vector.size=384 The products collection stores the catalog, and COSINE specifies the similarity metric for vector searches. The vector size is set to 384 to match the dimensions generated by LangChain4j’s local all-MiniLM-L6-v2 embedding model. Unlike solutions that require an external AI service, this application generates embeddings locally using an ONNX model. As a result, you don't need an API key or cloud account. With Qdrant running and the connection configured, you can explore how Java applications persist vectors, perform semantic searches, and combine similarity with structured business conditions. Working With Qdrant Using Eclipse JNoSQL With the database configured, we now focus on the Java API. Eclipse JNoSQL extends Jakarta NoSQL’s persistence model with VectorTemplate, enabling developers to handle vector data using familiar annotations and operations. In this example, we use a product catalog that lets customers search for items by description instead of exact keywords. First, we represent a product as a Jakarta NoSQL entity: Java @Entity public class Product { @Id private String id; @Column private String name; @Column private String description; @Column private ProductType type; @Column private Vector embedding; // Constructors and getters } The @Id annotation identifies the record, while the other attributes store product information and its vector embedding. This mapping is independent of Qdrant’s native data structures, so developers can work with standard Java objects. Generating and Persisting Vectors The vector is generated with LangChain4j and converted to Eclipse JNoSQL’s DenseVector format. This conversion is handled by a CDI component: Java @ApplicationScoped public class TextEmbedder { private final EmbeddingModel model = new AllMiniLmL6V2QuantizedEmbeddingModel(); public Vector embed(String text) { float[] values = model.embed(text) .content() .vector(); return DenseVector.of(values); } } Eclipse JNoSQL does not generate embeddings; it manages their persistence and retrieval. This separation lets developers update AI integration independently from the database layer, as long as stored and query embeddings remain compatible. VectorTemplate specializes Jakarta NoSQL’s Template abstraction, retaining standard persistence operations while introducing similarity search. Java String text = """ Product: %s Description: %s """.formatted(name, description); Vector embedding = embedder.embed(text); Product product = new Product( id, name, description, type, embedding); template.insert(product); In this example, the embedding captures the product’s name and description, while the type remains as structured metadata. This approach is especially useful when combining semantic retrieval with business rules. Semantic Search and Metadata Filtering For example, if a customer searches for “something comfortable for my animal to rest,” the application generates an embedding for the query and requests Qdrant to retrieve the most similar products: Java Vector queryVector = embedder.embed( "something comfortable for my animal to rest" ); List<Product> products = template.search(Product.class) .vector(queryVector) .limit(Limit.of(3)) .result(); Instead of requiring exact search terms, Qdrant evaluates similarity against stored embeddings. In this catalog, the relevant result is a dog bed described as a comfortable sleeping cushion. However, semantic similarity alone may not meet all business requirements. For example, to restrict recommendations to pet products: Java List<Product> products = template.search(Product.class) .vector(queryVector) .where("type").eq(ProductType.PET) .limit(Limit.of(3)) .result(); The fluent API combines vector similarity with structured metadata filtering, a key capability of Qdrant. The database evaluates searches based on its indexes and filtering strategy, while Eclipse JNoSQL maps results to Java entities. Repository Support and Jakarta Specifications Beyond VectorTemplate, Eclipse JNoSQL integrates three complementary Jakarta specifications: Jakarta NoSQL, Jakarta Data, and Jakarta Query. Jakarta NoSQL defines entity mapping and template-based persistence. Jakarta Data introduces declarative repositories. Jakarta Query provides a common query foundation, though its integration with Eclipse JNoSQL is still in development. For example, the same product entity can be exposed through a Jakarta Data repository: Java @Repository public interface ProductRepository extends BasicRepository<Product, String> { } This interface offers common persistence operations without manual database access implementation. However, repository operations and vector similarity searches serve different purposes. For specialized similarity retrieval, developers should continue using VectorTemplate. For enterprise architects, the value is in combining standardized persistence abstractions with specialized database capabilities. Eclipse JNoSQL reduces Java-level dependency on Qdrant while maintaining access to advanced search operations. The complete implementation, including Java SE bootstrap and executable examples, is available in the Qdrant Vector demo. Conclusion Qdrant offers an effective way to combine semantic search with structured filtering, making it well-suited for enterprise applications that demand both relevance and business constraints. Using Java and Eclipse JNoSQL, developers can implement vector persistence through familiar APIs while keeping embedding generation separate from the database layer. Understanding Qdrant’s features and trade-offs enables software architects to design intelligent search solutions without added complexity. For implementation details, review the complete source code and learn more about enterprise Java persistence on the Eclipse JNoSQL website. More
Pitching Kotlin: An Engineering Leader's Guide to Legacy Modernization

Pitching Kotlin: An Engineering Leader's Guide to Legacy Modernization

By Yuri Geronimus
I've been on both sides of the Kotlin conversation: the engineer making the case, and the architect who reviews it and recommends a direction before a committee decides. On the reviewing side, the pattern is predictable: most Kotlin pitches die in the second meeting. A tech lead shows up with a list of syntax wins, managers or architects ask about migration risk, and the conversation ends with "we'll revisit this next quarter." The technical case for Kotlin is usually sound, but the pitch stalls because it argues from developer preference, while engineering leaders approve migrations based on cost and risk. I've spent a large part of my career on systems where a defect moves real money (I talked about what that means for Kotlin code at KotlinConf 2026), and when I wrote the Kotlin Enterprise Playbook, I ran this exact argument through a financial model across mobile, edge, and backend domains. The proposals that held up were the ones that priced cost and risk honestly, including the cases where the answer was "not here." This guide is the framework I use when I review these proposals. Decide domain by domain, solution by solution, instead of organization-wide. Make the cost of the status quo measurable. Price the migration, including the parts nobody budgets for. Place gates where decisions stop being reversible. Make sure the people who carry the risk own the outcome. Kotlin is the worked example, but the same framework applies to any large technical migration, whether it's a language, a framework, or a data platform. Technical Debt as an Engineering Friction Metric Before you can pitch a migration, you need to make the cost of staying put visible. That cost is spread across pull request (PR) timelines, defect densities, and onboarding logs. It only becomes clear when you add those numbers up over several months, because an incident report only records one failure at a time. Start with four concrete measurements your team already has access to: PR cycle time on service-layer changes. Verbose Java boilerplate (getters, setters, null checks, builder patterns) means more code per feature, which requires longer reviews. A data class in Kotlin replaces a 40-line Java POJO with four lines in a representative case (Java records narrow this gap for immutable value types, though not for mutable or framework-bound classes), and that compression shows up directly in review time.NullPointerException rate in production. Pull your error-tracking data from the last two or three release cycles. A persistent NPE trend is one of the clearest health signals a Java codebase gives you. Kotlin's type system reduces null-related runtime failures at the compiler level, so this number becomes a defensible baseline for the risk argument.Time-to-productive for new engineers. Ask your most recent hires how long it took them to make their first independent commit to your most heavily annotated service layer. In my experience, boilerplate-heavy Java codebases show longer onboarding ramps, and this measurement tells you whether yours does.Effort on existing code per quarter. Count the engineering hours per quarter spent changing existing code and the hours spent writing new functionality. In mature Java monoliths, the time on existing code tends to grow as the codebase ages. Separate structural changes from bug fixes and behavior changes, because only the structural share is the friction you are pricing. When you present these numbers, frame them as a cost to team throughput. A statement like "We're spending 30% of sprint capacity on structural changes to code that hasn't changed business logic in 18 months" gives leadership a number they can weigh against the cost of migrating, while "Java is too verbose" is a preference leadership can dismiss. If your organization already reports DORA metrics (lead time for changes, deployment frequency, change failure rate, and failed deployment recovery time), use them as the backbone for your case and attach the four friction measurements to each one. Leadership already reads DORA as delivery performance, so your Kotlin case arrives in a format they trust. Adoption Friction and Long-Term Velocity Gains A realistic adoption model will show a short-term slowdown before the long-term gains, and presenting only the gains will cost you credibility with your peers. During the initial rollout, your team will write slower Kotlin than they write Java. Code review will slow down while reviewers build pattern recognition for Kotlin idioms. Budget two to four sprints for the team to get comfortable with the idioms, and expect full velocity parity by sprint 8, midway through phase 2. Your Gradle or Maven build configuration will also need updating to add the Kotlin JVM plugin and compiler targets alongside existing Java compilation. Plan for the less visible costs too. Mixed Java and Kotlin compilation adds build time (the K2 compiler that shipped with Kotlin 2.0 narrowed the gap, and Gradle's build cache and configuration cache help further, but measure it on your own codebase before you promise anything), annotation processors need a path off kapt (now in maintenance mode) toward KSP where your libraries support it, and Spring or JPA code needs the kotlin-spring and kotlin-jpa compiler plugins, because Kotlin classes are final by default and both frameworks rely on proxies and no-arg constructors. Note that kotlin-jpa only adds the no-arg constructor: entities also need allOpen configured for @Entity, @MappedSuperclass, and @Embeddable, or Hibernate's lazy loading turns into eager loading without warning. These line items are where migration estimates fall apart, because the visible conversion work is only the tip of the iceberg. Once your team reaches parity, the gains will compound with each module you convert, because Kotlin produces an estimated 40% fewer lines of code than equivalent Java, which means a smaller surface area to read, review, and debug. Treat that figure as directional, since it's a vendor estimate, and replace it with numbers from your own converted modules as soon as you have them. A stronger reference point is JetBrains' telemetry study of about 28 million development cycles: on comparable work, Kotlin developers spent roughly 15-20% less time from first edit to push than Java developers. Compile-time null safety catches most null-related runtime errors before they reach staging. Extension functions let Kotlin code add convenience APIs on top of existing Java classes without touching the original source, which smooths incremental adoption. They're resolved statically, though, so Java callers see them as ordinary static utility methods. Kotlin is designed for Java interoperability at the JVM level, which means you don't convert a service and then wait for everything else to catch up. New features ship in Kotlin while stable Java modules stay exactly where they are. Both compile to JVM bytecode and call each other's APIs directly, so the adoption boundary moves at whatever pace your team sets. AI-assisted tooling further changes the conversion economics. The kotlin-tooling-java-to-kotlin AI Agent Skill, published by JetBrains, integrates with IntelliJ IDEA's AI Assistant and external agent tools to automate module translation with a structured four-step conversion process. The skill performs a faithful semantic translation first, then refines nullability and mutability, converts collection APIs to idiomatic Kotlin, and restructures for framework idioms. It checks five invariants at every step, verifying that public signatures stay compatible and that annotation site targets don't break reflection-based frameworks like Spring or Jackson. Present this to skeptics as a safety net on the conversion pipeline, since it reduces the manual cleanup burden on each converted file, and your team still reviews and commits the output. One caution from the wider migration literature: LLM-assisted translation can produce code that compiles and passes the existing tests while still changing behavior at the edges. Tests generated by the same pipeline tend to confirm the translation instead of challenging it. Keep the tests that guard a converted module independent of the tool that converted it, and before converting a module, add characterization tests that pin down its current behavior. Why the Case Gets Stronger When AI Writes the Code For most teams, a growing share of new code is now drafted by AI assistants and agents. That moves the bottleneck from writing code to verifying it, and verification is where the language matters. Every non-null type, every exhaustive when expression over a sealed hierarchy, and every value class that keeps two lookalike IDs from being swapped is a check the compiler runs on generated code before any human reviewer looks at it. Explicit types also work as a specification the agent reads: a non-null field in a signature states the contract more reliably than a comment the model may ignore. And less code per feature means less generated code to review, which matters more once generation is cheap, and review isn't. AI doesn't settle the question, though. Models have seen far more Java than Kotlin, so output quality can vary, and AI also makes a modern-Java upgrade cheaper. It also shrinks only the visible part of the migration cost: conversion gets cheaper, but parallel running, governance, and decommissioning cost the same with or without an agent. The question becomes which language lets your reviewers trust code they didn't write. In domains where a wrong value is expensive, a stricter type system pays off. Team Velocity Through a Phased Rollout Incremental adoption turns a high-risk initiative into a gated engineering program. The goal is to give leadership defined checkpoints to evaluate stability before authorizing the next phase, because a plan approved in stages is much easier to sign off on than a multi-year roadmap. Phase 1 (tests-first, sprints 1 to 4). Write all new unit and integration tests in Kotlin. Your existing Java production code stays untouched. The team gets hands-on time with Kotlin syntax in a low-stakes context, and your test suite stays green throughout. It is also the cheapest step in the plan to reverse. If the pilot fails, you delete test files, and nothing changes in production. Phase 2 (leaf modules, sprints 5 to 10). Start with independent utility classes, DTOs, and value objects. These are the leaf nodes of your dependency graph. Because they depend on almost nothing else in your codebase, converting one can't break the code it relies on. Check their fan-in, though. A widely shared DTO is a leaf with many callers, and every nullability decision in its Kotlin signature reaches each Java caller, so convert low-fan-in leaves first and treat shared DTOs as a separate step. Two framework details trip up DTO conversions: Jackson needs jackson-module-kotlin to deserialize data classes, and Kotlin code in a mixed module can't see Lombok-generated members without the Kotlin Lombok compiler plugin. Most of these objects translate cleanly to Kotlin data class declarations (JPA entities are the exception: keep them as regular classes, because data-class equals() and hashCode() conflict with Hibernate's lazy proxies), and conversion regressions are easy to catch with the test suite you built in phase 1. Commit the mechanical J2K conversion on its own, then follow it with an idiomatic cleanup so your code reviewers can diff them separately. Phase 3 (new service boundaries, ongoing). Any new microservice or greenfield module ships in Kotlin from day one. This is the Strangler Fig pattern applied to a language: new capability grows around the legacy system, which keeps running until each domain is ready to retire. Existing Java services stay untouched unless they're candidates for targeted conversion. This is where most of the return sits. When I modeled adoption across a full product portfolio, new development came out clearly positive, while migrating highly stable legacy code often produced a negative net present value (NPV). A good plan says so openly and classifies each domain as Kotlin by default, gated behind a business case, or not now. Use a lightweight decision matrix to triage which modules go into which phase, so the sequencing decision is traceable. The following table applies the decision matrix to modules from an example codebase: ModuleFan-in (modules depending on it)Current friction signalTranslates cleanly to a data class?PhaseNotesOrderDtoLowNPEs in the mapping code around itYes2Leaf used by one service, good J2K candidatePricingServiceHighHigh refactor hours/quarterNo3 (new boundary) or targetedCore business logic, convert only if rewriting anywayNotificationUtilsLowLong PR cycle timeN/A (utility class)2Pure utility class, no callers outside its module; becomes top-level functions, so add @file:JvmName to keep Java call sites unchangedPaymentGatewayClientHighMixedNoHoldHigh fan-in, defer until phase 2 modules are stable Score your own modules on the same four columns: dependency count, which friction metric from the baseline section it shows up in, whether it translates cleanly to a data class, and the phase it belongs to. Modules with low fan-in and a clean data-class shape go to phase 2 first. High fan-in modules wait until the team has review-cycle data from earlier conversions. Velocity through these phases usually follows a predictable curve. You'll see a brief slowdown during phase 1 as the team learns the idioms, a recovery to baseline by sprint 8, and then a compounding improvement as shared modules accumulate in Kotlin. The right milestone gate at the end of phase 1 asks whether the team shipped tests on schedule and whether the suite passes. The gate at the end of phase 2 asks whether conversion regressions appeared and how many review cycles each converted file required. Measure both against a control group: comparable Java modules the team changed over the same period. Without one, a before-and-after comparison picks up everything else that changed that quarter, and a careful reviewer will discount it. Each gate is a go/no-go evaluation point. You should place gates where the next step stops being cheap to reverse. Kotlin tests and new modules are easy to back out. A shared DTO with dozens of Java callers, or an organization-wide default, is not, so that is where the evidence bar goes up. Where you can, encode the gate criteria as fitness functions in the build instead of meeting agendas: architecture checks with Konsist or ArchUnit, a build-time budget, and a rule that rejects new Java files in domains classified as Kotlin by default. A gate that runs on every commit doesn't depend on anyone remembering to hold it. If a team misses gate 1, treat that as data about the plan, not as a scheduling problem to absorb in phase 2. Show leadership a velocity chart comparing your team's adoption path with the trend for your Java codebase if nothing changes, so they see the short-term dip and the long-term payoff on the same timeline. The legacy line trends down as refactoring overhead compounds, while the adoption line follows the dip-and-recovery pattern described above. Use your own baseline numbers from the friction metrics section to recalibrate the axis before presenting it. Four Objections I Check When Reviewing a Kotlin Migration When a Kotlin proposal comes to me for review, how it answers these four objections shapes my recommendation to the committee, and each maps to a concrete technical answer. "What if we need to roll back?" Kotlin's interoperability with Java means each module conversion can be reversed on its own, at least for a while. A Kotlin file compiles to standard JVM bytecode that Java code calls directly, and in most cases existing Java callers need no changes, as long as the converted code keeps a Java-friendly API (@JvmStatic, @JvmOverloads, @Throws, and the kotlin-spring plugin for proxied Spring beans). Once other Kotlin code relies on Kotlin-only features of the converted module (default arguments, extension functions, suspend functions, sealed hierarchies), reverting it breaks those callers, so make the rollback window part of your gate criteria. If a converted module introduces instability, revert the commit. Because the mechanical J2K output lives in its own commit, the rollback is one small, reviewable change. For higher-risk modules, run the Java and Kotlin versions side by side behind a feature flag (under different class names, since both can't share one on the classpath), or shadow a slice of production traffic through both and compare outputs before switching over. In payments, shadow only side-effect-free logic such as fee calculation or routing decisions, never authorizations, captures, or refunds, and keep in mind that mirroring card data widens your Payment Card Industry Data Security Standard (PCI DSS) scope. "The conversion overhead is too high." IntelliJ IDEA's built-in Java-to-Kotlin (J2K) converter handles the syntactic translation automatically. The two-commit pattern (one commit for the J2K output, one commit for idiomatic cleanup) keeps code review tractable. "We'll introduce null-safety regressions during conversion." The compiler catches most of these before they ship. The gap is the Java–Kotlin boundary. Unannotated Java types reach Kotlin as platform types with no compile-time check, so annotate the remaining Java side with JSpecify. The boundary can also fail at runtime in the other direction. Kotlin inserts null checks on public non-null parameters, so a Java caller that used to pass null now fails immediately with an NPE. Check the Java callers of each converted API before you mark a parameter non-null. The J2K converter infers nullability from annotations and usage and inserts non-null assertions (!!) where it can't decide, so your team reviews each one and replaces it with safe calls (?.) or Elvis operators (?:), or keeps the non-null assertion where a contract guarantees it. In practice, the bigger risk runs the other way. A converted field gets marked nullable "just in case," and a broken upstream contract turns into a silent fallback deep in the code. Keep mandatory fields non-null, validate them once at the system boundary, and make invalid input fail loudly there. I covered this pattern in my KotlinConf 2026 talk on type-driven reliability. "Why not just upgrade to modern Java?" This is the objection to take most seriously in 2026. Records, sealed classes, pattern matching, and virtual threads have closed much of the gap that drove early Kotlin adoption. For stable, low-change backends, a Java upgrade plus stronger engineering standards is often the higher-return choice. Kotlin earns its place where the bottleneck is modeling correctness, safe refactoring speed, or business logic shared across channels, especially when those factors show up in incident rates or time to market. A credible proposal compares Kotlin with the Java you could run next year (today, Java 25, the current long-term support release), not the Java 8 or 11 the codebase was written in, and it is willing to say "not here" where Java is enough. Architects in enterprise Java usually ask whether Spring fully supports Kotlin, and JetBrains and the Spring team answered that with a strategic partnership to make Kotlin a first-class language for Spring applications. The collaboration covers full null safety across the Spring portfolio (based on JSpecify annotations and shipped in Spring Boot 4), official Kotlin-first Spring learning materials, faster Kotlin reflection, and evolving configuration DSLs. Coroutine support in Spring WebFlux predates the partnership and has been available since Spring Framework 5.2. Spring and Spring Boot remain among the most widely used backend frameworks in JetBrains' own Kotlin developer surveys, with enterprise teams at Expedia Group, Kakao Pay, and Mercedes-Benz.io among those running Kotlin in production on that stack. Who Says Yes, and the Decision on One Page A proposal that only answers engineering gets approved and then stalls in the next review. Before you write it, map who has to say yes and what each of them protects: finance looks at payback and predictability, security at supply chain and scanning coverage, product at delivery risk during the dip, and platform engineering at a toolchain it will support for years. Then make ownership explicit. The architecture board owns the default, gated, and not-now classification. Platform engineering owns the toolchain and upgrade cadence. A small guild owns Kotlin conventions, with rotating membership so it doesn't harden into a gatekeeping inner circle. Write the result as an architecture decision record (ADR), including the context, the options you rejected and why, the decision, and who owns each consequence. The evidence behind the ADR comes down to four things: Codebase health baseline. Present your current friction metrics, including PR cycle time on service-layer changes, NPE rate from your error-tracking tool, engineering hours per quarter on structural refactoring, and new-engineer time-to-first-independent-commit. These establish the cost of the status quo in terms of team throughput. Pair them with an honest cost estimate that covers training, the learning dip, parallel running, governance, and the eventual decommissioning of legacy code.Phased migration plan with gates. Outline the three phases (tests-first, leaf module conversion, new service boundaries) with sprint estimates and go/no-go criteria at each gate. Request approval for phase 1 only. Add a kill switch: if build time, incident rate, or review load regress past agreed thresholds, expansion pauses until the platform is fixed. Name an owner for Kotlin conventions (a style guide, static analysis with detekt, and a short review checklist), so converted code doesn't turn into Java written in Kotlin syntax.Tooling and safety net inventory. Name the specific tools in the conversion pipeline, including IntelliJ IDEA's J2K converter for mechanical translation, the kotlin-tooling-java-to-kotlin AI Agent Skill for framework-aware idiomatic refinement and invariant checks, and the existing Gradle or Maven build for mixed-codebase compilation. Include the supply-chain controls security will ask about: a software bill of materials (SBOM), dependency scanning, and pinned, approved versions of the Kotlin compiler and Gradle plugins. The Kotlin standard library, kotlin-reflect, and kotlinx-coroutines become new runtime dependencies in your component inventory. Security will want to agree on which code may be sent to an AI conversion tool, especially anything that touches keys, hardware security module (HSM) integration, or cryptography. This answers the "how do we actually do this" question before it's asked.Ecosystem maturity signals. The JetBrains and Spring strategic partnership (announced May 2025), Google's continued backing of Kotlin as Android's recommended language (a sign that investment extends beyond any single vendor, not a reason to scope this migration around mobile), the enterprise case studies at kotlinlang.org/server-side, and the roughly 8.1 million Kotlin developers JetBrains estimates in its State of Kotlin 2026 report give leadership the external validation they need. For most backend teams, ecosystem maturity is no longer the main adoption risk. Treat vendor numbers, including these, as directional: independent case studies and your own pilot data carry more weight with a skeptical review board. Keep the main document to one page, two at most, and move the detail into appendices. Your goal is a decision the committee can make in a single 30-minute review, not a series of follow-up meetings. Building the Case, Section by Section This guide's framework comes down to five moves. Decide domain by domain which code is Kotlin by default, which needs a business case, and which is not now. Quantify the friction in your current Java codebase as throughput metrics, measured against a control group. Model both sides of the adoption curve honestly, including the short-term slowdown and the costs nobody budgets for. Phase the rollout through gates placed where decisions stop being cheap to reverse. Then map who has to say yes, make ownership explicit, and put the recommendation in a short ADR. The tooling makes conversion manageable, but tooling was never what blocked approval. A migration gets approved when the decision is scoped by domain, priced honestly, reversible at each step, and owned by the people who carry its risk. That holds whether the change is Kotlin, a new framework, or a new data platform, and it holds just as well when the honest answer is "not here." For the full financial model (NPV, IRR, payback, and the migration iceberg) and the governance setup behind this guide, see the Kotlin Enterprise Playbook I wrote, available at kotlinlang.org, and the recap of my KotlinConf 2026 talk. Where have you said "not here" to a migration your team wanted, and what evidence settled it? More
Getting Started With Milvus: Vector Search for Enterprise Java Applications
Getting Started With Milvus: Vector Search for Enterprise Java Applications
By Otavio Santana DZone Core CORE
Reading GC Logs: Memory Leak or Undersized Heap?
Reading GC Logs: Memory Leak or Undersized Heap?
By Amit Sonar
Spring Boot's Hidden Secret for Configuration: EnvironmentPostProcessor
Spring Boot's Hidden Secret for Configuration: EnvironmentPostProcessor
By Mikhail Polivakha
Building an AI-Powered Code Review Assistant in Java
Building an AI-Powered Code Review Assistant in Java

Code review is the highest-leverage activity on most engineering teams, yet it is also the most expensive in terms of senior-developer time. What if you could offload a first pass to an LLM that understands Java idioms, common anti-patterns, SOLID principles, and security pitfalls — and get back structured, actionable feedback before a human even opens the PR? In this post, we will build exactly that: a self-contained Java application that accepts a Java source snippet, sends it to an LLM (OpenAI GPT-4o or a locally running Ollama model — your choice), and returns a structured list of code-quality findings with severity levels and suggested fixes. What you will build: A CodeReviewAssistant Java service backed by LangChain4j, which analyses Java code and returns structured improvement suggestions — runnable in under 10 minutes on your laptop. Prerequisites ToolVersionNotesJava JDK17+Records & sealed types usedMaven or GradleAny recentMaven snippets shown hereLangChain4j0.36.xLatest stable at time of writingOpenAI API key or Ollama—We show both No Spring, no frameworks — this is plain Java, so you can drop it into any stack. Step 1: Add LangChain4j to Your Project LangChain4j is the Java-native counterpart of the Python LangChain library. It gives you a clean, type-safe API over multiple LLM providers — OpenAI, Anthropic, Azure, Hugging Face, Ollama, and more — with zero vendor lock-in. Add the BOM and the provider module you want: XML <!-- pom.xml --> <dependencyManagement> <dependencies> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-bom</artifactId> <version>0.36.2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- Core --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j</artifactId> </dependency> <!-- Choose ONE provider below --> <!-- Option A: OpenAI (GPT-4o, GPT-3.5-turbo, …) --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-open-ai</artifactId> </dependency> <!-- Option B: Ollama (runs locally, no API key needed) --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-ollama</artifactId> </dependency> </dependencies> Tip — local-first development: Start with Ollama + codellama or mistral so you can iterate without burning API credits. Switch to OpenAI GPT-4o for production quality by changing one line. Step 2: Model the Review Output as a Java Record LangChain4j's Structured Output feature can instruct the LLM to respond with JSON that maps directly onto a Java type. We define our domain model first: Java // Finding.java public record Finding( String severity, // "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFO" String category, // e.g. "Null Safety", "Performance", "Security" String description, // human-readable explanation String suggestedFix // concrete code-level recommendation ) {} // CodeReviewResult.java import java.util.List; public record CodeReviewResult( String summary, List<Finding> findings ) {} Using Java Records keeps the model immutable and removes boilerplate. LangChain4j will automatically build the JSON schema from these types and include it in the system prompt. Step 3: Define the AI Service Interface LangChain4j's AI Services abstraction is the cleanest part of the library. You declare an interface, annotate it with prompts, and the library generates a proxy at runtime — no boilerplate, no manual HTTP calls. Java import dev.langchain4j.service.SystemMessage; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface CodeReviewService { @SystemMessage(""" You are a senior Java engineer performing a thorough code review. Analyse the provided Java code for: - Correctness and potential bugs - Null safety issues - Performance anti-patterns - Security vulnerabilities (injection, insecure randomness, etc.) - SOLID principle violations - Readability and naming conventions Return ONLY a JSON object matching the CodeReviewResult schema. Be concise but actionable. Severity: CRITICAL, HIGH, MEDIUM, LOW, INFO. """) @UserMessage("Review this Java code:\n\n```java\n{{code}\n```") CodeReviewResult review(@V("code") String javaCode); } How it works: The @SystemMessage sets the LLM's persona and instructions. The @UserMessage is the per-call prompt. @V("code") is a template variable — LangChain4j substitutes it at call time. Zero boilerplate. Step 4: Wire It All Together Now we create the LLM model, register our output type, and build the AI Service proxy. The entire wiring fits in one short class: Java import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.model.ollama.OllamaChatModel; import dev.langchain4j.service.AiServices; public class CodeReviewAssistant { public static void main(String[] args) { // ── Choose your provider ────────────────────────────────────────── // Option A: OpenAI (set env var OPENAI_API_KEY) var model = OpenAiChatModel.builder() .apiKey(System.getenv("OPENAI_API_KEY")) // never hardcode keys! .modelName("gpt-4o") .responseFormat("json_object") // enforce JSON mode .temperature(0.2) // low temp = consistent output .build(); // Option B: Ollama running locally on port 11434 // var model = OllamaChatModel.builder() // .baseUrl("http://127.0.0.1:11434") // .modelName("codellama") // .build(); // ───────────────────────────────────────────────────────────────── CodeReviewService reviewer = AiServices.builder(CodeReviewService.class) .chatLanguageModel(model) .build(); // ── Sample code to review ───────────────────────────────────────── String javaCode = """ public class UserService { private static Map<String, String> cache = new HashMap<>(); public String getUser(String id) { if (cache.containsKey(id)) return cache.get(id); String sql = "SELECT * FROM users WHERE id = " + id; // ... execute query return null; } } """; CodeReviewResult result = reviewer.review(javaCode); // ── Print results ───────────────────────────────────────────────── System.out.println("Summary: " + result.summary()); System.out.println(); for (Finding f : result.findings()) { System.out.printf("[%s] %s — %s%n", f.severity(), f.category(), f.description()); System.out.printf(" Fix: %s%n%n", f.suggestedFix()); } } } Step 5: Sample Output Running the above against that deliberately flawed snippet produces output like: Plain Text Summary: The code has a critical SQL injection vulnerability, a thread-safety issue with the shared HashMap cache, and returns null without documentation. [CRITICAL] Security — String concatenation builds a raw SQL query, making the method vulnerable to SQL injection attacks. Fix: Use PreparedStatement with parameterised queries: "SELECT * FROM users WHERE id = ?" with stmt.setString(1, id) [HIGH] Concurrency — HashMap is not thread-safe. Concurrent reads/writes will cause data corruption in multi-threaded environments. Fix: Replace with ConcurrentHashMap<>() or add explicit synchronisation. [MEDIUM] Null Safety — getUser() returns null without documentation. Callers have no contract to guard against NPEs. Fix: Return Optional<String> and document the empty-case semantics. [LOW] Performance — cache.containsKey() + cache.get() performs two lookups. Fix: Use cache.computeIfAbsent(id, k -> fetchFromDb(k)) instead. Going Further: Production Hardening 1. Streaming Responses for Large Files For large classes, swap the return type of your AI Service method to TokenStream and use onNext() / onComplete() to stream findings incrementally rather than waiting for the full response. 2. Memory and Conversation History LangChain4j's MessageWindowChatMemory lets you maintain multi-turn conversations — useful if you want the developer to ask follow-up questions about a specific finding. Java CodeReviewService reviewer = AiServices.builder(CodeReviewService.class) .chatLanguageModel(model) .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) .build(); 3. RAG: Ground Findings in Your Own Style Guide Use EmbeddingStore + ContentRetriever to inject excerpts from your team's coding standards into every review. The LLM will then apply your own rules rather than falling back on generic advice. 4. CI/CD Integration Wrap the service in a small CLI tool (using picocli), wire it into your GitHub Actions or Jenkins pipeline, and post findings as PR comments via the GitHub REST API. This enables a first-pass AI review before any human reviewer opens the PR. Key Takeaways LangChain4j AI Services let you express LLM interactions as plain Java interfaces — no HTTP plumbing, no JSON parsing.Structured Output (records + JSON schema) eliminates fragile string parsing; you get strongly typed results directly.Provider-agnostic design means you swap one builder line to move between OpenAI, Ollama, Anthropic, or Azure with zero business logic changes.Keep API keys in environment variables — never in source code.Start local (Ollama) to iterate fast, then promote to a hosted model for production quality. Further Reading LangChain4j official docsAI Services tutorialOllama — CodeLlama modelOpenAI Structured Outputs guide

By Akhil Sabu
Modernizing a Legacy Java Application With OpenRewrite: What We Automated and What We Didn't
Modernizing a Legacy Java Application With OpenRewrite: What We Automated and What We Didn't

OpenRewrite in a Real Enterprise Migration Recently, we modernized a 9-year-old enterprise application that involved two major changes happening together: Java 8 → Java 25Spring Boot 2.3.3 → Spring Boot 3.3.4 At the same time, we were also moving the application from a monolithic architecture toward microservices. One of the biggest challenges was the sheer volume of source-code changes. With Java 17 being the minimum required baseline for Spring Boot 3 and major namespace changes such as javax.* → jakarta.*, manually modifying a large codebase would have been time-consuming and risky. We decided to use OpenRewrite to automate the mechanical parts of the migration. The result was significant: 2,384 Java files were refactored in minutes. The manual effort that we estimated at roughly 5–7 days was reduced to automated transformation followed by code review and testing. But the most interesting part wasn't simply how much OpenRewrite changed. It was understanding what it could automate, what it couldn't, and where human judgment was still required. What Is OpenRewrite? OpenRewrite is an automated refactoring framework designed to transform source code using recipes. Instead of manually searching through thousands of files and applying the same transformation repeatedly, you define a recipe and let OpenRewrite perform the transformation consistently across the codebase. For large migrations, this is particularly useful for changes that are: RepetitiveSyntacticWell-understoodApplicable across many files The important distinction is that OpenRewrite automates code transformation. It does not understand every business rule or runtime behavior in an enterprise application. Our Migration The application was originally running on: Plain Text Java 8 Spring Boot 2.3.3 We moved toward: Plain Text Java 25 Spring Boot 3.3.4 One of the major changes introduced by Spring Boot 3 was the migration from the older Java EE namespace to Jakarta EE. For example: Java import javax.persistence.Entity; became: Java import jakarta.persistence.Entity; When you have thousands of source files, this is exactly the kind of transformation that should not be performed manually. Configuring OpenRewrite For our migration, we used the OpenRewrite Maven plugin: XML <plugin> <groupId>org.openrewrite.maven</groupId> <artifactId>rewrite-maven-plugin</artifactId> <version>5.41.0</version> <configuration> <exportDatatables>true</exportDatatables> <activeRecipes> <recipe>org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3</recipe> </activeRecipes> </configuration> <dependencies> <dependency> <groupId>org.openrewrite.recipe</groupId> <artifactId>rewrite-spring</artifactId> <version>5.20.0</version> </dependency> </dependencies> </plugin> We then executed: Shell mvn rewrite:run That's it. The tool analyzed the codebase and applied the configured recipe. What Happened? The results were better than we expected. 2,384 files changed. OpenRewrite modified approximately 2,384 Java files. The majority of the changes were mechanical framework migration changes. Some of the important changes included: 1. javax → jakarta A large number of imports were automatically migrated. For example: Java javax.persistence.* became: Java jakarta.persistence.* This is one of the areas where automated refactoring provides tremendous value. A developer doesn't need to manually locate every affected file. 2. Spring Batch API Changes Our application also contained Spring Batch code. Older APIs such as: Java JobBuilderFactory StepBuilderFactory needed to be migrated toward the newer builder APIs: Java JobBuilder StepBuilder OpenRewrite handled a significant portion of these changes automatically. This was particularly useful because Spring Batch code was spread across the application. 3. Other Spring Boot Migration Changes The Spring Boot migration recipes can also handle many other framework-level changes, including API and configuration changes. The exact transformations depend on the Spring Boot version and the recipe version being used. The OpenRewrite Spring Boot migration documentation provides the applicable transformation set and before/after examples. How Much Time Did It Save? This was probably the biggest practical benefit. Our initial estimate for manually performing the large-scale refactoring was approximately 5–7 days. OpenRewrite completed the core source transformation in minutes. We then spent approximately 4 hours reviewing the generated changes. This is an important distinction. We did not treat the generated code as automatically correct. The workflow was: Plain Text OpenRewrite ↓ Automated transformation ↓ Code review ↓ Compilation ↓ Unit/integration testing ↓ Manual fixes This turned the migration from a large manual refactoring exercise into a much more controlled process. But OpenRewrite Did Not Migrate Everything This was the most important lesson from our experience. OpenRewrite was extremely effective for structural and mechanical changes. However, there were areas where application-specific knowledge was required. The DAO layer was one example. Our application contained a significant amount of legacy SQL code. SQL Built Using String Concatenation Some queries were constructed using direct string concatenation. For example: Java String sql = "SELECT ... WHERE customer_id = " + customerId; These situations required manual intervention. The problem wasn't simply changing Java syntax. We needed to understand the SQL, parameter handling, and application behavior. OpenRewrite could transform Java source code, but it could not safely determine the business intent behind every SQL statement. Legacy Named Parameters We also discovered another interesting problem during testing. Some legacy DAO code used parameters such as: SQL :1 :2 The code compiled successfully after the migration. However, during runtime testing, some of these parameters failed to bind correctly. We had to manually replace them with explicit names such as: SQL :customerId :employeeId This was a good example of why successful compilation does not mean a migration is complete. The problem surfaced only when the application actually executed the affected code. What About Java 25? There is another important point when planning a Java 8 → Java 25 migration. Spring Boot migration and Java migration are related, but they are not the same transformation. OpenRewrite provides Java migration recipes as well. For example, there is a dedicated recipe for migrating to Java 25: Java org.openrewrite.java.migrate.UpgradeToJava25 The Java 25 migration guide currently describes this recipe as part of the rewrite-migrate-java recipe module. The important thing is to select the recipes appropriate for the actual migration path. For example: Plain Text Java 8 ↓ Java 17 ↓ Java 21 ↓ Java 25 or combine applicable migration recipes depending on the project's starting point and the changes required. A Java 25 recipe should not be treated as a replacement for the Spring Boot migration recipe. They address different parts of the modernization. Useful OpenRewrite Recipes for Java/Spring Modernization One of the things I like about OpenRewrite is that the migration doesn't have to stop with one recipe. Depending on the application, you can combine recipes for different modernization goals. Some useful categories include: Spring Boot For example: Java org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3 This was the recipe we used for our Spring Boot 3.3 migration. OpenRewrite also maintains Spring Boot migration recipes for newer Spring Boot versions. Java For Java modernization, OpenRewrite provides recipes such as: Java org.openrewrite.java.migrate.UpgradeToJava25 The Java migration recipes can target language/API modernization separately from Spring-specific changes. Other Framework/API Migrations The OpenRewrite recipe ecosystem also contains recipes for other common modernization scenarios. This is where OpenRewrite becomes more interesting than a simple search-and-replace tool. Recipes can encode relationships between APIs and perform structured transformations rather than blindly replacing text. What OpenRewrite Is Good At Based on our experience, I would categorize the work this way. Excellent Candidates for Automation Plain Text javax → jakarta Known API replacements Deprecated API migrations Repetitive source changes Large-scale mechanical refactoring Areas Requiring Engineering Judgment Plain Text Business logic SQL semantics Security behavior Application-specific configuration Runtime behavior This distinction is critical. You don't want to ask: "Can OpenRewrite migrate my application?" A better question is: "Which parts of my migration can be safely automated?" Automation Does Not Remove Testing One of the biggest mistakes would be to run: Shell mvn rewrite:run and assume the migration is finished. Our experience showed the opposite. The automated changes actually allowed us to spend more time on the areas that mattered. Instead of having developers spend days changing thousands of imports and APIs, we could focus our engineering effort on: Reviewing generated changesFixing application-specific issuesValidating SQL behaviorTesting Spring Batch behaviorValidating security configurationRunning integration testsInvestigating runtime failures The tool didn't remove engineering work. It moved engineering effort from repetitive refactoring to higher-value validation. Our Takeaway The most impressive part of OpenRewrite wasn't that it changed 2,384 files. It was that it allowed us to approach a large migration differently. Without automation: Plain Text Thousands of files ↓ Manual changes ↓ 5–7 days ↓ High risk of inconsistency With OpenRewrite: Plain Text Migration recipe ↓ 2,384 files transformed ↓ Minutes ↓ Code review ↓ Testing ↓ Manual fixes where required The lesson I took from the migration is simple: Automate the mechanical work. Keep human judgment for the work that requires application context. OpenRewrite doesn't eliminate the complexity of a Java/Spring modernization. But for a large legacy application, it can dramatically reduce the amount of repetitive work engineers need to perform — and make the overall migration much more controlled and repeatable.

By Kirankumar Phirangi
From Database Changes to Real-Time Actions at Scale: Oracle GoldenGate and Java
From Database Changes to Real-Time Actions at Scale: Oracle GoldenGate and Java

DB changes can be streamed in real time via Oracle GoldenGate. Java applications can then consume them to validate/act on/route events without polling the DB. Goal Listen to real-time transactions in the DB, act on all operations within transactions, and maintain transaction boundaries with near real-time SLAs. Component Details 1. Source DB This is the source DB from which the Java service listens for transaction changes in real time. It can be any DB supported by the GoldenGate service (e.g., MySql/ Oracle). 2. OCI Source GoldenGate Service Deployment Input: DB Redo logsOutput: Trail file The GoldenGate service has two primary components: Extract and Replicat. Extract reads changes from the source DB in the form of redo and archive logs. It commits each transaction's DML operations until either COMMIT or ROLLBACK is identified. If it encounters a COMMIT, it stores the transaction in TRAIL files. If ROLLBACK is encountered, it discards those changes. The output of this deployment is a TRAIL file with an ordered list of all transactions that occurred in the source DB. 3. OCI Target GoldenGate Big Data Deployment Input: Trail files generated by traditional GG deploymentOutput: Ordered stream of operations within a transaction This is another deployment type that can be used for transaction management. We can use the DATA STREAMS feature instead, but this uses the AsyncAPI publish/subscribe interface, whereas big data deployment is a managed integration runtime for CDC delivery to Kafka. 4. Streaming Service Input: Trail files generated by traditional GG deploymentOutput: Ordered stream of operations within a transaction Ideally, Kafka keeps up with the scale of GoldenGate and downstream scalability. Kafka provides an option to add partitions while the partitions are receiving data. This feature is particularly useful for handling traffic bursts or batch SQL jobs on the source DB. 5. Java Service Kubernetes Deployment Input – Kafka messages, in this case individual operationsOutput – Application logic A Java application instance that can scale horizontally depending on the Kafka partition backlog. Use Case Java service is interested in listening to the entire transaction in the order that it is happening for a predefined set of tables.It does not want to listen to all the source table changesIt also does not want all columns of the changed row. It is interested in listening to only specific set of columns from given list of tables. Component Setup The detailed setup guide here can be used as general guidance, but I will focus on the specific changes needed to achieve the use case above. 1. Source DB Here we want to listen to redo logs from the source DB. To enable supplemental logging on the source DB, use the command below. SQL ALTER DATABASE ADD SUPPLEMENTAL LOG DATA In our use case, we also want to make sure we always get only the columns from the table that the Java service is interested in, and not all the columns. To enable table-specific supplemental logs, use the command below. SQL ALTER TABLE HR.EMPLOYEE ADD SUPPLEMENTAL LOG GROUP emp_group_loc (EMPLOYEE_ID, EMP_NAME, EMP_DEPARTMENT_ID); 2. OCI Source GG Deployment In this step, OCI source GG deployment is configured to listen to redo logs of the source DB. As per our use case the important step is to configure only required tables in Extract's parameter file. The list of tables basically makes sure transactions happening on only those tables will be identified by GG and will be collected in trail files. You can use this article to set up Extract. Example of parameter file for extract: SQL table HR.EMPLOYEE; Along with extract, a distribution path needs to be created within the same source deployment. This distribution path makes sure the target big data deployment can access the trail file records easily. The details to create the distribution path can be found in TASK 3 of the article. 3. OCI Target GoldenGate Big Data Deployment In this deployment, a process called 'replicat' is created; replicat reads transaction data from the distribution path created in step 2 above, then publishes those transactions. Replicat works using two configuration files. Parameter File Similar to Extract, Replicat also has a parameter file. This file contains mapping information on how operations from the source DB map to the target schema and table. Since we are not replicating transactions in the DB, a JSON with the target table mapped in the parameter file gets written to kafka topic instead. Example for a complete setup guide: use this guide. SQL MAP HR.EMPLOYEE, TARGET *.*; Properties File Three important parameters that decide how the source transactions get written to the target are 1. TopicMappingTemplate – Tells replicat about the target, where source transactions will be written, 2. opMode – How the source transaction will be written. Complete transaction or one operation at a time.3. keyMappingTemplate – This parameter is the hashing key used by the replicat Kafka producer. For all the parameters that are available in the properties file, please refer to section "11.2.10.1.3.2.2 Kafka Handler Configuration" in this guide. 4. Streaming Service and Java Consumer Service Since GG hashes based on transaction ID, it is guaranteed that all operations in a transaction will always be in the same partition. The Java service needs a consumer group used by all pods. At bootstrap, all pods register their client ID with the Kafka broker and reserve a partition. This mechanism makes sure a single pod always listens to one partition until a rebalance happens due to a pod going down or other reasons. This setup ensures the Kafka consumer in the Java service can poll and collect transactions while maintaining operation boundaries and sequence for downstream application logic within the same service. Separating polling logic from processing logic in the Java service helps avoid various timeout scenarios. We can dive deep into this mechanism in a follow-up article. Summary With this setup, we can guarantee that transactions at the source DB are accessed by a Java service in order and can run within a single transaction at a time. This workflow is useful for industries that need an eventing mechanism, such as fraud detection and financial applications, telecommunications and real-time billing, Retail and real-time inventory management, and AI and semantic search pipelines.

By Sushant Sakolkar
Persisting Cookies Across JAX-WS Service Calls Using a Custom SOAP Handler
Persisting Cookies Across JAX-WS Service Calls Using a Custom SOAP Handler

The Cookie That Never Came Back The first call authenticated the user. The second failed. I was integrating with a customer-provided SOAP service exposed through a single WSDL, with JAX-WS client classes generated by IBM Rational Application Developer from the WSDL and its XSDs. The first call authenticated the user and came back with a Set-Cookie header. Every call after it needed that cookie. The generated client sent none of it. Each invocation behaved as an independent conversation, and the workflow broke on its second step. No exception, no warning. Just a server that had forgotten who you are. The Built-in Answer, and Why It Failed The JAX-WS specification anticipated this: every proxy generated from a WSDL implements BindingProvider, and the spec defines a request-context property for exactly this purpose: Java CheckPort port = new Check().getCheckPort(); ((BindingProvider) port).getRequestContext() .put(BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); Set that flag, and the runtime is supposed to maintain session state. In most tutorials, this is where the article ends. Mine broke in deployment for three reasons: First is scope. The property is set on one proxy instance, and the runtime's cookie store lives with that proxy. RAD-generated code encourages pulling a fresh port per unit of work. Every fresh port gets a fresh store, so the authentication session is discarded when the method returns. Holding one proxy for the workflow fixes it, but pins the session lifetime to the object lifetime. Second is opacity. The spec does not say where the runtime keeps the cookie. The JDK's bundled implementation delegates to java.net.CookieHandler.getDefault(), null unless somebody installed one. IBM's runtime, which RAD-generated clients typically run on under WebSphere, does it its own way. Same client class, different behavior per container, and the failure is silent. Third is the obvious fix: install a default CookieManager inline. Java `CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));` A JVM-wide static. Fine in a standalone client, but inside an application server, it is shared by every deployed application and every outbound HTTP client in the JVM. It is also the wrong model for a server-side client: a CookieManager is built for a browser, where one cookie jar belongs to one user. A server handling concurrent requests would pool every user's session cookies into one store, and CookieManager applies RFC domain and path matching, so if the service sits behind a load balancer, the cookie is quietly dropped. The Options on the Table I wanted cookie handling scoped to the call, visible in the code, and independent of the container. The alternatives fell short. Holding one proxy for the whole workflow is the simplest change, but it marries the session to an object's lifetime, and the strain shows across components or threads. Installing a default CookieManager is one line and works in a standalone client. But inside an app server, it becomes shared mutable state across applications and users, which rules it out for anything concurrent. Hand-rolling the client on plain HTTP gives full header control with no container surprises, but you lose the WSDL tooling: generated types, binding, error handling. Too much machinery to rebuild for several operations. A custom SOAP handler was the fourth option: roughly sixty lines you own, sitting in the message path of the existing generated client. Nothing JVM-wide, nothing container-specific, nothing hand-edited in generated classes. The costs: you match the cookie by name instead of trusting RFC rules, and you own the stored value's lifecycle. Acceptable for this integration. How the Handler Works The contract is SOAPHandler<SOAPMessageContext>; the direction comes from a Boolean on the context. The listing below is illustrative, adapted from the class I used, and not presented as tested code. Java public boolean handleMessage(SOAPMessageContext ctx) { if (Boolean.TRUE.equals(ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY))) { attachCookie(ctx); } else { captureCookie(ctx); } return true; } @SuppressWarnings("unchecked") private void captureCookie(SOAPMessageContext ctx) { Map<String, List<String>> headers = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_RESPONSE_HEADERS); if (headers == null) { return; } for (Map.Entry<String, List<String>> entry : headers.entrySet()) { if (!"Set-Cookie".equalsIgnoreCase(entry.getKey())) { continue; } for (String raw : entry.getValue()) { String pair = raw.split(";", 2)[0].trim(); if (pair.startsWith("JSESSIONID=")) { SESSION_COOKIE.set(pair); } } } } @SuppressWarnings("unchecked") private void attachCookie(SOAPMessageContext ctx) { String cookie = SESSION_COOKIE.get(); if (cookie == null) { return; } Map<String, List<String>> existing = (Map<String, List<String>>) ctx.get(MessageContext.HTTP_REQUEST_HEADERS); Map<String, List<String>> headers = (existing == null) ? new HashMap<>() : new HashMap<>(existing); headers.put("Cookie", Collections.singletonList(cookie)); ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers); } public boolean handleFault(SOAPMessageContext ctx) { return true; } public void close(MessageContext ctx) { } public Set<QName> getHeaders() { return Collections.emptySet(); } } Three details in that listing exist because earlier versions broke. Copying the existing request headers before adding Cookie keeps the handler additive: putting a fresh map into HTTP_REQUEST_HEADERS replaces whatever was already there, and my first version did exactly that, until another handler down the chain set a custom authorization header that then vanished. Matching the header name case-insensitively is for portability, since a case-insensitive map is an implementation choice, not a spec guarantee. Splitting on the first semicolon keeps response attributes such as Path, Expires, and HttpOnly out of the request; echoing them produces a Cookie value the server will not parse. Iterating over every value rather than taking index zero covers responses that set more than one cookie, where the session cookie is not guaranteed to be first. Why ThreadLocal, and Where It Bites The integration ran several workflows concurrently, so a static field would leak one user's session into another's request. A ThreadLocal gives each thread its own value, which fits a workflow that runs start to finish on one thread. The cost is that thread pools reuse threads. If a workflow ends without clearing the value, the next request on that thread inherits a stale session cookie. In the worst case, it sends one user's session identifier on another user's behalf. Clearing it when the workflow ends closes that hole: SESSION_COOKIE.remove(); Note that close() is intentionally empty: the container calls it at the end of each message exchange, not the workflow, so clearing there would discard the cookie from the authentication call. Cleanup belongs at the logout step or in a finally block around the workflow. And if the workflow hands off between threads, ThreadLocal is the wrong container: the cookie then belongs in whatever object already represents the conversation. Registering the handler JAX-WS lets handlers be declared in an external XML file: XML <?xml version="1.0" encoding="UTF-8"?> <handler-chains xmlns="http://java.sun.com/xml/ns/javaee"> <handler-chain> <handler> <handler-class>com.company.cc.handler.SessionCookieHandler</handler-class> </handler> </handler-chain> </handler-chains> The file sits in the same package as the generated service class, since the annotation resolves relative to that class: Java @WebServiceClient( name = "check", targetNamespace = "http://ws.example.com/", wsdlLocation = "META-INF/wsdl/spellingCheck.wsdl" ) @HandlerChain(file = "sessionCookieHandler.xml") public class Check extends Service { } Every proxy from that service now runs through the handler. One caveat: regenerating from an updated WSDL overwrites the service class and removes the annotation, so keep it in a small subclass or script the regeneration step. Edge Cases Cookie rotation needs no special handling: capture runs on every inbound response, so a new cookie mid-workflow replaces the old value on the next exchange. Expiry is different: a ThreadLocal cannot know when the server-side session times out, so an idle workflow keeps attaching a dead cookie. That fix belongs to the workflow level: catch the session-expired response and re-authenticate. Testing It Without a Container A test can build a stub message context, inject HTTP_RESPONSE_HEADERS, run handleMessage, and check the Cookie header on the next outbound call. Cover the cases that burned earlier versions: two Set-Cookie values in one response, a header name in unexpected case, a pre-existing request map that must survive the copy, and the remove() at the end of the workflow. For integration confidence, run the real client against a stub endpoint that returns Set-Cookie on the first call and asserts the Cookie header on the second. The Takeaway JAX-WS has a session mechanism. It is scoped to a proxy instance, implemented differently across runtimes, and backed by a JVM-wide singleton that does not fit a server-side client handling concurrent users. A custom SOAP handler replaces it with a small class you own, an explicit scope you choose, and behavior identical wherever the application deploys. For teams maintaining legacy SOAP integrations that will not be modernized soon, that trade is usually the right one.

By Vishal Rameshchandra Shah
Best of Three Worlds: AI Agents Writing In Rust and Java Beat the C Library
Best of Three Worlds: AI Agents Writing In Rust and Java Beat the C Library

Every app that accepts photo uploads meets HEIC sooner or later. iPhones save in it by default. Neither Java nor Rust can read it out of the box, and the usual answer, libheif, is a C library: native packages in every container image, a C toolchain in the build, and a parser written in C reading files that strangers upload. I had the problem twice, in a Java product and in a Rust one. So I went the other way: decoders written in the language itself, built and improved by AI coding agents, with me steering. Here is how it went. 1. Make It Work, In Each Project One agent per codebase, each starting from an existing open-source decoder in its own language: Openize.HEIC for Java, HEIC decoder for Rust. The first versions lived inside each app. They read the photos, and that was enough to ship. They were ready in no time, given there were upstream libraries to start from, even if some features had to be added to match libheif. It was tempting to stop there. Nobody complains about an upload that works. 2. Extract and Iterate Next, I had each decoder pulled out as a standalone library, open source, with its own tests and releases, aligned with the best practices for each language (and mine). Then I asked each agent to iterate on its own: measure, improve, measure again. That alone went a long way. The Java decoder went from 19 seconds to 3.2 for our ten test photos. 3. Compare Everything With Everything Working alone, each agent eventually ran out of obvious ideas. What changed the game was putting both decoders next to libheif on the same machine with the same photos, and then comparing them stage by stage. Every gap became a lead. If another implementation did a step fast, there was a way to do it even faster, and the size of the gap told me whether it was worth chasing. A gap is a hint with a number attached. The comparison also kept us honest. It showed where we were ahead, and it showed that part of libheif's lead came from doing less work: it copied color samples where our decoder interpolated them. 4. Make the Agents Talk Here is the part that led to further improvements. Each agent, working in its own session, was told to talk with the other agent. I had the Rust agent brief the Java agent on what it had found, and the other way around. A gap one side had already closed became a recipe for the other. The Java decoder took the Rust decoder's entropy decoding approach; the Rust decoder took the Java decoder's parallel tiles and transform tricks. Later, the two agents, who were then aware of each other, even coordinated on their own, communicating which CPU cores each could benchmark on. Connecting them was the most useful step in the project. 5. Repeat On the Gaps That Remain Then we ran the same loop again: compare, find the largest remaining gap, close it, then measure. One more round on the Rust side closed the last single-core gap with libheif. The Java side tried the JVM's vector instructions and gained another 9 to 14%. Not every idea survived. The trick the C library is famous for, wide vector instructions, gained almost nothing in Rust: its slow parts were elsewhere. We measured it, wrote it down, and dropped it. Be Strict About Evidence A computer is never idle. Browsers, chat apps, other agents: everything competes for the CPU, and the numbers move with it. When we measured the very same code twice, back to back, the second run came out about 0.4% slower. Noise with a direction looks exactly like progress, or like a regression. So I asked for proof, not impressions: count CPU work instead of wall-clock time, run old and new in alternating order, split results by type of photo, and drop any "gain" smaller than the noise. Several changes didn't make it. One that looked good overall turned out to slow down rotated photos, which are most of what phones upload, until the agent found why. Where They Stand Today Measured together on the same machine, the same ten photos, all three doing the same work: 8 cores: Rust 0.46 s, Java 0.55 s, libheif 0.81 s1 core: Rust 1.38 s, libheif 1.45 s, Java 1.96 sRust can also interpolate color for sharper edges and still matches libheif: 1.45 s Memory is on par with libheif or below, and a long way from where the two decoders started. What I Take Away Iterating alone gets you far. Comparing gets you further. The gap between two implementations is the best to-do list.Cross-pollinating agents helps a lot. The ideas were there, in two separate sessions. Making them talk to each other triggered more optimizations.Be strict about evidence. Ask for measurements that hold up against noise, and be ready to throw away a change that doesn't.Two implementations in two languages beat one. Each made the other faster. Getting a third as reference (libheif) helped even more.Java is fast, too. “Java is slow” is a meme, not a measurement. Optimized the right way, it comes close to the C library on one core and beats it on eight. Both decoders are open source: Rust: github.com/Valuya/heic-decoder-rustJava: github.com/Valuya/openize-heic-java

By Yannick Majoros
Java to TypeScript in a Day: AI Migration Playbook
Java to TypeScript in a Day: AI Migration Playbook

Introduction In 2020, while working at Priceline, I created a specialized open-source in-memory database. Designing and implementing took four months. Years later, AI helped me create a TypeScript version in a single day. But what made a single-day rewrite possible was not just AI. A structured design doc, hundreds of unit and behavior tests, and a well-reviewed and published algorithm made that possible. In short, AI is a super tool if used correctly, with the right ingredients. The Java library still exists and is still supported. The goal was not to replace it, but to make the same capabilities available to browser and Node.js developers. This article describes the workflow I would reuse on any similar project, and the mistakes that are easy to make when an AI writes most of the code. Fig-1. The TypeScript version reused the engineering investment. These are different scopes of work, not a speedup ratio. What Is Kiara DB? Kiara DB is an in-memory database optimized for read-heavy scenarios that empowers users to search by any combination of fields or attributes without having to create any special index. Simply load the database and search using any attribute with typo forgiveness — no fine-tuning or index creation needed to obtain high-read performance. The algorithm is based on my 2020 research paper published in the Journal of Algorithms and Computation (JAC). The TypeScript version brings the same capabilities to browsers and Node.js, with zero runtime dependencies. You don't need to know Kiara DB to follow along. Substitute any library or service you want to make available in another language. 1. Start by Converting Behavior Tests The most valuable thing I had going into the migration was not the Java source. It was the test suite. There are two kinds of tests in most projects, and they translate very differently: Behavior and integration tests treat the system as a black box by defining how a system should behave. Those tests are language agnostic and carry over directly.Implementation-focused unit tests depend heavily on the implementation, its underlying platform and the patterns and feature available in the authoring language. These tests translate poorly or maybe not at all. Converting the behavior tests first gave the AI a precise, executable definition of "done." From there, the rest of the migration had one job: make those tests pass. Example. A Java test: Java List<Condition> conditions = new LinkedList<>(); conditions.add(new Condition("country", Operator.EQUAL, "US")); conditions.add(new Condition("state", Operator.EQUAL, "FL")); List<Airport> result = storeSearch.query(airportStore, conditions); assertEquals(3, result.size()); And its TypeScript counterpart: TypeScript const result = store.search([ { field: "country", operator: Operator.EQUAL, values: ["US"] }, { field: "state", operator: Operator.EQUAL, values: ["FL"] }, ]); expect(result).toHaveLength(3); The setup and syntax changed. The expected answer did not. That is the property you want to protect. Make the Tests Trustworthy Before Writing Code A few rules made this step reliable: Pin the source version. Record the exact commit the tests come from. A moving branch is not a stable specification.Run the original tests first. Review and fix any inconsistencies, because if there are any issues, this is a good time to fix them before we copy over unwanted errors to the new repo.Translate the tests using AI with a human review. During translation, maintain a level of isolation. AI model should only see the tests in the source language and not the main application code. The instructions should define the main goal as a test translation without thinking about application code. This prevents AI from bending corners in tests if the application’s code translation in some parts becomes challenging. AI models are very creative in hacking through to meet their goals and then covering their tracks.Cover the edges. Include invalid input, empty values, nulls, duplicates, and boundary values, not just successful queries.Lock the expectations. An expected result changes only through a reviewed decision. The AI may never edit an assertion just to make its code pass. At the end, all 448 Java tests were translated to TypeScript tests. In the next phase of code translation, these immutable tests would be used to verify every changed iteration. Fig-2. Shared fixtures provide a stable contract. A second model's agreement is not a substitute for source-derived expected results. 2. Define Clear Responsibilities for Every Agent If we simply ask an agent to translate the code to another language, the agent will try to take the shortest path and may produce code that, although it passes behavior tests, creates application code riddled with unstable patches, broken algorithms that adversely affect performance, missed features, etc. Careful planning matters; the devil is in the details. Breaking down a bigger task into several agents (with clear responsibilities and how they interact with each other in a loop) gave us the results we hoped for. Agent #1: The Code Analyzer Job: Examine codebase structures to define project specifications. Produces: A requirements inventory with references back to the source: Functional requirements, in the format of request-response, input normalization, error behavior, and result limits.Non-functional requirements, like latency, memory usage, dependencies, and supported runtimes.Any Algorithmic requirements, meaning the translation preserves core data structures and algorithms — for this translation of KiaraDB, this was very important. The last category is the one most often missed. KiaraDB's value comes from its search algorithm. A simple Array.filter() over every record can return the right answers on a small test dataset while losing everything that makes the library useful at scale. Rule: The core algorithm must be translated as is, not replaced. Write idiomatic TypeScript while maintaining core data structures and search methods. Should papers, code, or test outcomes diverge, an automated analyzer mandates human review for resolution of conflict. Agent 2: Planner Job: Turn requirements into small, verifiable steps. Produces: An implementation plan with each step defining the requirements it covers, the tests that prove it is done, and known risks. For example, in the case of KiaraDB, the planner broke down the translation into individual features, implemented separately in sequence. Plain Text Schema and data loading -> structured queries -> collections, ranges, and keyword search -> browser worker support and release checks The planner should also be instructed to scope the work strictly to rewrite and not introduce improvements present in the target language, so new features don't sneak into a code rewrite. Agent 3: Developer Job: Implement one planned step at a time in the target language. Grounded in: Your team's coding policies, for example, strict typing, explicit error handling, no skipped tests, no unrelated refactoring, and documentation of any intentional difference. Language differences show up here. Java can inspect a class's fields at runtime, while TypeScript types disappear after compilation. The TypeScript version therefore offers both explicit schema definitions and decorators that feed the same search engine. That changes how users describe their data, not how queries behave. The developer can propose changing an expected result. However, an agent cannot approve that change; it must coordinate with the other agents we created, who will work together in a loop and bring in a human whenever required Agent 4: Tester and Gap Analyzer Job: Audit both programming projects for structural discrepancies and find missing components Produces: A ranked list of gaps, each with a reproducible example. This agent looks beyond the developer's own tests: requirements with no tests, tests whose expected values came from the AI, changed algorithms, and missing public APIs. A useful gap report is specific, for example: NOT_CONTAINS on a collection field returns 2 rows; Java returns 3. Tests for this use case are missing in both TypeScript and Java. Range queries in TypeScript are significantly slower than the Java version because of an algorithm mismatch. Agent 5: Product Manager Job: Communicate work produced during releases to interested stakeholders. Produces: Public technical notes plus announcement drafts describing working, tested modules. This agent acts like a quality gate for the final product delivery. While producing final artifacts, if it finds that the delivered product doesn’t meet expectations, then it will work with Code analyzer, planner, developer, and tester agents in a loop until the identified gaps are filled. A Reusable Prompt Template Each role works better with a short, explicit brief. Here is the shape I'd reuse: Plain Text Role: Tester and gap analyzer. Inputs: Java repo at <commit>, TypeScript repo, requirements list, latest test results. Task: Find the highest-impact behavior or algorithm gap between the two. Output: One gap with requirement ID, expected vs. actual, and a failing test. Rules: Do not modify implementation code. Do not change expected results. Stop when: One gap is reported, or none is found after checking all requirements. 3. Connect the Agents in a Loop That Knows When to Stop The agents work as a cycle. The analyzer defines goals. The planner chooses sequential moves. The developer builds functions, and the testers verify output consistency. Each gap goes back to the role that can fix it Misunderstood source behavior goes to the analyzer.Missing or mis-ordered work goes to the planner.A bug goes to the developer.A request to accept a difference from Java goes to a human. When everything passes, the product manager prepares the release communication and does a final quality check. Fig-3. Every gap has an owner and every loop has a budget. Running out of budget leads to escalation, not release. Define "Done" Before the Loop Starts The loop needs an exit condition the agents can't negotiate. Mine looked like this: All converted behavior tests pass, including error and edge cases.Secure all high and critical risks.Rewritten algorithm matches the source with no unapproved modifications.Build, type checks, and browser tests pass.Performance and memory meet thresholds agreed on before implementation.Every remaining difference from Java is documented and approved. Track Gaps in One Shared List Rather than forcing agents to repeat the whole project review, every phase maintains one unified tracker. Each entry records the requirement, expected versus actual behavior, a reproducer, severity, owner, and status. Agents report what changed, not everything they know. 4. Avoid Common Mistakes Infinite and Trivial Loops That Burn Tokens While breaking down a big task into multiple agents working together in a loop is essential for success, agents can create endless dialogue without meaningful iterative progress. Therefore, it is essential to keep the agentic loop in check. Set an explicit control policy. I started by capping work at five iterations per batch and reviewing results before approving more. You can use instructions like the following for your main orchestrator agent: Plain Text Work on one planned step at a time. Run at most five implement-and-verify cycles per batch. After each cycle, record what changed and the test result. If two cycles in a row produce no new fix or evidence, stop and escalate. Never skip tests, weaken assertions, or expand scope to claim success. Five is not a magic number. The point is we will allow a human to intervene and check if more iterations are required to achieve the focused goal, instead of going in a loop and burning up tokens. Not Isolating Behavior Tests The agent rewriting the code must never be allowed to rewrite behavior tests to avoid agents tweaking the tests to just pass them. An independent agent who has no knowledge of other agents doing rewrites should first translate the behavior tests and, once done, they should be immutable. Matching Results but Losing the Algorithm A brute force algorithm can pass every test but performs poorly at scale, which is why reviewing and comparing the underlying algorithm must be part of the validation. Treating Runtime Differences as Syntax Some differences between Java and TypeScript look minor but change results: AreaWhat to watch OUT forNumbersJava long values can exceed what a JavaScript number represents exactly. Test large values explicitly.Test dataJSON numbers can lose precision before a test even runs. Store large integers as strings.NullsMissing, null, empty strings, and the text "null" may behave differently. Test each one.Dates and localesPin the time zone and locale. Reject unsupported date formats rather than guessing.ReflectionTypeScript types are erased at runtime. Provide metadata explicitly.Web workersClass instances lose their methods when sent to a worker. Test the actual message boundary. Moving the Goalposts Don't relax a performance threshold because the implementation missed it. Don't relabel a missing feature as optional without approval. Improvements are welcome, but they should be explicit options, not silent changes to how the original behaved. Conclusion The TypeScript transition in a single day was made possible by reusing previous human labor. The published algorithm, along with extensive test history, established the foundation for success. If you have a similar project, here are my suggestions: Convert behavior tests first, with expected results taken from the original system.Split the work into focused agent roles that can't approve their own output.Orchestrate the agents in a loop with guardrails to protect against going into infinite loops.The validation set should include both functional and non-functional requirements, such as automated tests, comparison of source and target algorithms, gap analysis for missing features, etc. The two codebases that we worked on are open source, so you can compare them side by side: Java: github.com/kapoorlabs/kiaraTypeScript: github.com/kapoorlabs/kiara-ts References Kapoor, A. "Efficient Storage and Retrieval of In-Memory Static Data." Journal of Algorithms and Computation.Kiara DB Java repository and the pinned migration baseline.Kiara TS TypeScript repository.Migration plan, parity ledger, and compatibility decisions.TypeScript 5.2 decorator metadata.

By Anuj Kapoor
Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade

When JDK 27 was released on 15 September 2026, most of the attention went to compact object headers and post-quantum TLS. JEP 523 received less coverage, partly because its description sounds like housekeeping: G1 becomes the default garbage collector in all environments. For most applications, that changes nothing. For a specific class of container, it changes the collector silently, with no warning in the logs and no failure at startup. This article covers what the fallback did, which workloads lose it, how to identify affected services, and how to run a comparison that produces usable numbers rather than noise. What the Serial GC Fallback Did G1 has been the nominal default since Java 9. What is less widely known is that HotSpot inspected the machine at startup and overrode that choice in constrained environments. The JVM selected Serial GC when either condition was true: ConditionThresholdAvailable processors1Physical memoryLess than 1,792 MB The reasoning was sound at the time. Serial GC is single-threaded with a very small native memory footprint. On a single-core machine, a concurrent collector spends time competing with application threads for the only available core, and the bookkeeping structures G1 maintains were expensive relative to a small heap. G1 has improved substantially since then. Its native memory footprint has been reduced across several releases, and JDK 26 delivered JEP 522, which removed synchronization overhead from G1's write barriers by introducing a second card table. JEP 523 concludes that work. The fallback is removed, and G1 is now selected in every environment regardless of CPU count or available memory. Serial GC remains fully supported and can still be selected explicitly: Shell java -XX:+UseSerialGC -jar application.jar Applications that already specify a collector, whether G1, ZGC, Parallel, or Shenandoah, are unaffected by this change. Which Workloads Are Affected The change only reaches services that never had an explicit collector flag and that run in a constrained environment. In practice, this describes a predictable set of deployments: Sidecar containers. Log shippers, metrics agents, and service mesh components typically receive a fraction of a CPU and a few hundred megabytes of memory. They are rarely tuned.Batch and queue workers. Short-lived jobs scheduled onto whatever capacity is available.Low-traffic internal services. Admin APIs, configuration services, and internal tooling that are deliberately given small pods.CI runners and development containers. Environments where JVM flags are seldom set because the workload is not production.Pods with fractional CPU limits. This case is easy to miss. A container configured with cpu: 500m may report a single available processor to the JVM, which placed it in Serial GC territory on earlier releases. These are the workloads least likely to appear in a performance test plan, which is precisely why the change deserves deliberate verification. Step 1: Identify Your Current Collector Before changing anything, determine which of your services are actually running Serial GC today. The GarbageCollectorMXBean interface exposes this directly: Java import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; public final class RuntimeFacts { public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); System.out.printf("java version : %s%n", Runtime.version()); System.out.printf("available cpus : %d%n", rt.availableProcessors()); System.out.printf("max heap MB : %,d%n", rt.maxMemory() / (1024 * 1024)); for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { System.out.printf("collector : %s%n", gc.getName()); } } } The collector names identify which implementation is active: CollectorReported MXBean namesSerial GCCopy, MarkSweepCompactG1G1 Young Generation, G1 Concurrent GCParallelPS Scavenge, PS MarkSweepZGCZGC Cycles, ZGC Pauses For a Spring Boot application, registering this as a startup listener puts the information into your existing log aggregation without any additional infrastructure: Java import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.util.stream.Collectors; @Component public class GcFactsLogger { @EventListener(ApplicationReadyEvent.class) public void logCollector() { Runtime rt = Runtime.getRuntime(); String collectors = ManagementFactory.getGarbageCollectorMXBeans() .stream() .map(GarbageCollectorMXBean::getName) .collect(Collectors.joining(", ")); System.out.printf( "JVM %s | cpus=%d | heap=%,dMB | gc=%s%n", Runtime.version(), rt.availableProcessors(), rt.maxMemory() / (1024 * 1024), collectors); } } Deploy this across your estate, then filter your logs for entries reporting Copy as a collector name. That result set defines the scope of your testing. Step 2: Understand the Native Memory Difference Discussions about garbage collector selection usually center on pause times. For this particular change, native memory consumption is the more consequential metric. G1 maintains bookkeeping structures that Serial GC does not require, including remembered sets, card tables, and per-region metadata. This memory is allocated outside the Java heap, which means it counts against a container memory limit without appearing in heap metrics. Measurements published after the JDK 27 release place G1's native memory overhead at approximately 43 MB, compared with roughly 1.7 MB for Serial GC. Ankur Mundra measured both collectors on Spring Boot 4.1 within real cgroup limits and reported these figures. The absolute difference is modest. The proportional impact depends entirely on container size: Container memory limitApproximate G1 overhead share1024 MB4%512 MB8%256 MB16% On a tightly sized container, this overhead is consumed before the application allocates its first object. Where memory limits were set with minimal headroom, the change alone can produce OOM kills after an upgrade that altered nothing else. Native Memory Tracking provides the per-category breakdown if you want to confirm the figure in your own environment: Shell java -XX:NativeMemoryTracking=summary \ -XX:+UnlockDiagnosticVMOptions \ -jar application.jar Then, against the running process: Shell jcmd <pid> VM.native_memory summary The GC section of the output reports committed native memory attributable to the collector. Step 3: Run a Controlled Comparison A meaningful comparison requires the smallest container size you actually deploy, representative load, and a run long enough to reach steady state. A thirty-second run measures startup behavior rather than collection behavior. Capture GC logs for both configurations: Shell # Pre-Java 27 behaviour java -XX:+UseSerialGC \ -Xlog:gc*:file=serial.log:time,uptime,level,tags \ -jar application.jar # Java 27 default java -Xlog:gc*:file=g1.log:time,uptime,level,tags \ -jar application.jar Three measurements matter, and the third is the one most often omitted: Total pause time. Sum the pause durations across the run rather than comparing individual collections. Serial GC performs fewer, longer pauses; G1 performs more, shorter ones. Only the aggregate is comparable.Tail latency. G1 runs concurrent phases. On a single-core container, those phases contend with request handling for the only available processor. This effect is invisible in a mean and clearly visible at p99.Resident set size under load. This is where the native memory difference becomes operationally relevant. Sample RSS throughout the run rather than reading it once at startup: Shell while true; do ps -o rss= -p "$PID" | awk '{printf "%s %d MB\n", strftime("%H:%M:%S"), $1/1024}' sleep 5 done If RSS approaches your container limit under G1 where it did not under Serial, you have found the problem before it found you. Step 4: Pin the Collector When G1 Loses If measurement shows that G1 performs worse on a constrained workload, the appropriate response is not to defer the JDK upgrade. It is to state the collector explicitly: Shell java -XX:+UseSerialGC -jar application.jar This is a supported configuration. Serial GC is neither deprecated nor scheduled for removal, and JEP 523 explicitly preserves it. In a Kubernetes deployment, express the choice where it will be reviewed: YAML spec: containers: - name: batch-worker env: - name: JAVA_TOOL_OPTIONS value: "-XX:+UseSerialGC" There is an argument for setting the flag explicitly even where G1 performs well. An explicit collector choice is self-documenting. A future engineer reading the manifest can see that a decision was made and tested, rather than inferring what the JVM selected at runtime. Conclusion JEP 523 is a reasonable change. G1 has genuinely closed the gap that justified the fallback, and removing a hidden conditional from the JVM's startup logic simplifies the mental model for everyone. The operational consideration is narrower: a set of small, rarely tested containers will change collectors on upgrade without any signal that it happened. Identifying those containers takes one log statement. Testing them takes one load run. The cost of skipping both is a latency regression or an OOM kill that appears unrelated to any change your team made. Java 27 is not a long-term support release, and many teams will remain on Java 25. That does not remove the relevance of this work. The same default will arrive with the next LTS, and evaluating it on a short-term release carries considerably less risk than discovering it mid-migration. Further Reading JEP 523: Make G1 the Default Garbage Collector in All EnvironmentsJEP 522: G1 GC: Improve Throughput by Reducing SynchronizationJDK 27 Release Notes

By Garima Agarwal
Build a GitHub Contribution City With Java and Quarkus
Build a GitHub Contribution City With Java and Quarkus

GitHub's contribution calendar gives you an already iconic overview of your activity over the year. Each day has a square, and its color changes with the contribution level. And of course, those days and contributions can also be arranged into buildings, with a week becoming a small part of a city and busier weeks adding height to the skyline. I had some spare minutes and built Quarkus Contribution City around this idea, using Java and Quarkus to generate an SVG from GitHub's contribution data. The visual inspiration came from Pink Pixel's skyline, and you can see a version with my real data on my GitHub profile. A scheduled GitHub Action updates the image at night. For a Java developer, this is a small project you can follow from the API request through to the image. You can use the released action on your own profile, then change the drawing code locally once you have a feel for how the city is put together. For this article, I created a special DZone example that adds a small piece of character art above the buildings. Add the City to Your Profile Your GitHub profile README lives in a public repository with the same name as your account. For my account, that repository is myfear/myfear. Open your own profile repository, or create it with a README if you haven't used this GitHub feature before. Copy the project's complete publishing workflow into .github/workflows/contribution-city.yml on the default branch. This example checks out your profile repository and the action's v1 release line. It then generates the image and publishes it to an output branch. The workflow includes the repository write permission needed for that last step. The generation step uses the repository owner's username, so the same configuration can be copied between personal profile repositories. You can add the layout options to that step: - name: Generate contribution city id: city uses: ./.city-action with: github-token: ${{ secrets.CONTRIBUTION_TOKEN || secrets.GITHUB_TOKEN } username: ${{ github.repository_owner } weeks: '53' height: '14' theme: github-dark The local path refers to the action checkout made earlier in the example workflow. The built-in GITHUB_TOKEN is the starting point for reading your visible contribution data. An optional CONTRIBUTION_TOKEN secret can supply a personal token when additional access is needed. The calendar returned by GitHub depends on the token's permissions and your account's contribution visibility settings. After committing the workflow, open Actions in your profile repository, select publish-contribution-city, and choose Run workflow. A successful run creates contribution-city.svg on the output branch. Add this image reference to your profile README, replacing both occurrences of USERNAME: ![My GitHub contribution city](https://raw.githubusercontent.com/USERNAME/USERNAME/output/contribution-city.svg) The example also has a daily schedule for 03:17 UTC. Subsequent runs create a commit when the generated image changes. For this setup, the workflow and its run history can be found in your profile repository, while the Java implementation is maintained in the action's repository. Give Each Week a Building The city is arranged in time order, with the most recent week on the right. Every building is two character cells wide, so all weeks occupy the same horizontal space. Weekly contribution totals determine the height, and daily contribution levels provide the window colors. Month labels beneath the street help you find your place in the year. Height needs a little extra thought. A very busy week can have many times the contributions of a quiet one. With a linear scale, those quieter weeks would be compressed close to the street. The city uses a logarithmic scale, which gives them more room while preserving the order of weekly totals. For each week, the calculation can be expressed as: int height = weeklyTotal == 0 ? 1 : 1 + (int) Math.round( Math.log1p(weeklyTotal) / Math.log1p(maximumWeeklyTotal) * (maxHeight - 1)); With a maximum of 20 contributions and a height limit of 14, a week with three contributions gets seven window rows. The busiest week gets 14, and a week with zero contributions keeps one row. Quiet periods therefore retain their position in the calendar. An antenna marks the busiest displayed week; when totals are tied, the most recent week receives it. The two columns of windows are filled by cycling through the days of the week. This repeats the daily pattern in taller buildings, so window count is a visual texture. The weekly total controls height, while the window colors carry the daily contribution levels. Together, they give you a view of the pattern across your calendar. You can change weeks to 12 for a shorter view. The tallest building is then calculated from those recent weeks, which lets the selected period use the available height. Keep this in mind when comparing images: the same week can appear taller in a shorter view. The displayed contribution total still covers the full calendar returned by GitHub. Follow the Data Through Java The released project uses Quarkus with the Quarkus GitHub Action extension. That extension connects an @Action method to workflow inputs, outputs, and the job summary. Inside the method, the drawing process comes down to three steps: ContributionCalendar calendar = contributionClient.fetch( configuration.username(), inputs.getGitHubToken().orElseThrow(), context.getGithubGraphQLUrl()); Scene scene = cityBuilder.build(calendar, configuration.options()); String svg = svgRenderer.render(scene, configuration.options().theme()); The client reads the contribution calendar with one GraphQL request and converts the response into Java records for the calendar, weeks, and days. CityBuilder uses these records to place roofs, windows, and the street in a grid. SvgRenderer turns that grid into the final SVG. Changes to the skyline can therefore be made in plain Java classes, with the GitHub connection kept in the client. The SVG contains the shapes and text needed to display the city. Adjacent characters with the same color are grouped during rendering, and their horizontal positions are set explicitly to keep the columns aligned. Identical data and options produce identical file contents, which allows the publisher to compare images before creating a commit. The action sets up Java and JBang, builds the selected source revision, and runs the packaged application. Change the Layout Locally To try a change, install JDK 21 and JBang, with Git and Bash available. The repository includes a Maven wrapper. JBang is also used by the integration tests to run the packaged action through the same launcher used in GitHub Actions. git clone --branch v1.0.0 https://github.com/myfear/quarkus-contribution-city.git cd quarkus-contribution-city ./mvnw verify The tests use local test data and a local GraphQL server, so you can run them without GitHub credentials. They also generate SVG previews under target/previews. Open github-dark.svg, recent-12.svg, and empty.svg in a browser to compare a full calendar, a shorter period, and a calendar with zero contributions. Start with the height calculation in CityBuilder, then run the same command again and compare the previews. The saved data stays the same between runs, which makes the effect of your change easier to see. The project is available under the Apache License 2.0, and the v1.0.0 release gives you a fixed starting point. Give the City a DZone Landmark Version 1.0.0 exposes weeks, height, and the two built-in themes through workflow inputs. For a custom shape, you extend the Java code in your fork. The Scene record gives you a grid of cells to change before the SVG is rendered, and that is where we'll add the DZone lettering. Each cell has a character, a role such as roof or window, and the color information used by the renderer. A character mask is enough to describe a new shape: # marks a filled block, and spaces leave the background visible. By arranging those blocks, you can draw letters, an arch, or a stepped tower. For this example, the lettering is placed above the weekly buildings. It has its own fixed shape, while the buildings below continue to show the contribution calendar. The image uses a snapshot of my real account data, with 534 contributions returned by GitHub on October 5, 2026, when I wrote this article. A DZone-inspired palette and decorative lettering added to my contribution city. The weekly building heights and daily window patterns come from the same calendar used by the regular view. Add this class to the existing city package in your fork, at src/main/java/com/themainthread/contributioncity/city/DZoneLandmark.java: package com.themainthread.contributioncity.city; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.themainthread.contributioncity.render.Theme; public final class DZoneLandmark { public static final Theme THEME = new Theme("dzone-example", "#161b22", "#242c36", "#303947", "#f58a42", "#9ba9ba", "#edf2f7", List.of("#536070", "#86431f", "#b85b25", "#e57d36", "#ffb365")); private static final List<String> MASK = List.of( "#### ##### ### # # #####", "# # # # # ## # # ", "# # # # # ## # # ", "# # # # # # # # #### ", "# # # # # # ## # ", "# # # # # # ## # ", "#### ##### ### # # #####"); private DZoneLandmark() { } public static Scene addTo(Scene city) { int landmarkWidth = MASK.getFirst().length() * 2; int width = Math.max(city.width(), landmarkWidth); int left = (width - landmarkWidth) / 2; List<List<Cell>> rows = new ArrayList<>(); Cell block = new Cell('█', CellKind.ROOF, 0, -1); for (String line : MASK) { List<Cell> row = new ArrayList<>(Collections.nCopies(width, Cell.SKY)); for (int column = 0; column < line.length(); column++) { if (line.charAt(column) == '#') { row.set(left + column * 2, block); row.set(left + column * 2 + 1, block); } } rows.add(row); } rows.add(Collections.nCopies(width, Cell.SKY)); for (List<Cell> sourceRow : city.rows()) { List<Cell> row = new ArrayList<>(sourceRow); row.addAll(Collections.nCopies(width - city.width(), Cell.SKY)); rows.add(row); } return new Scene(city.username(), city.totalContributions(), rows); } } The theme defines the background, two building shades, roof, street, and label colors, followed by the five window colors. Those window colors follow GitHub's contribution levels from zero through four. Here, the roof color is also used for the lettering, so the decoration has a consistent orange color across all seven rows. Inside addTo, each marked position is expanded to two cells because the renderer's cells are taller than they are wide. The lettering is centered, a blank row is added beneath it, and the original city rows are copied below. Short calendars receive extra background space on the right to make room for the lettering. The dates, counts, and order of the weekly buildings are preserved. To use the decoration in your fork, import DZoneLandmark from the city package in ContributionCityAction. Replace the existing scene-building and rendering lines with: Scene scene = cityBuilder.build(calendar, configuration.options()); Scene decorated = DZoneLandmark.addTo(scene); String svg = svgRenderer.render(decorated, DZoneLandmark.THEME); This selects the example's palette in Java. The published @v1 action continues to accept github-dark and mono; your fork contains the additional drawing code. For a local preview, add the following after the existing Files.writeString call in PreviewTest.write, with the same import for DZoneLandmark: Scene decorated = DZoneLandmark.addTo(builder.build(calendar, options)); Files.writeString(directory.resolve(name.replace(".svg", "-dzone.svg")), renderer.render(decorated, DZoneLandmark.THEME)); Run ./mvnw verify again and open target/previews/github-dark-dzone.svg. The build also writes the shorter and empty versions with the -dzone.svg suffix, so you can check how the decoration fits several calendars. When you're ready to use your fork on GitHub, update the second checkout in the publishing workflow to your fork's repository and a commit containing your changes. The generation step then runs the customized action from that checkout. Try It With Your Own Contributions Try Quarkus Contribution City with your own GitHub account and add the generated SVG to your profile. Start with the released action, then fork the project and change the character mask to give your city a landmark of its own. You could draw a stepped tower from your hometown or add your team's initials above the street, using the DZone version as a starting point. Share your version in a GitHub issue, or open a pull request if you'd like to contribute a new shape.

By Markus Eisele
Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
Stop Writing Database Migration Scripts: Declarative Schema Sync for Java

If you have worked on a mature Java backend application, your src/main/resources/db/migration folder probably looks like a chaotic history ledger: Plain Text V1__init_schema.sql V2__add_users_table.sql ... V142__add_status_column.sql V143__fix_status_typo.sql V144__drop_old_status.sql V145__add_missing_index.sql Tools like Flyway and Liquibase have been the industry standard for over a decade. They operate on an imperative model: “Apply this exact sequence of scripts to transition the database from version N to version N+1.” In the early stages of a project, this model feels logical. But at scale, imperative migrations create severe operational friction. Two engineers branching off main will inevitably create conflicting V146__... scripts. Standing up a new test environment from scratch requires replaying hundreds of sequential scripts. Most dangerously, if an engineer accidentally commits a script containing an unsafe DROP TABLE or ALTER COLUMN, the migration tool will blindly execute it against the production database, potentially causing catastrophic data loss. Modern infrastructure tooling—such as Kubernetes and Terraform—moved away from imperative scripts years ago. They utilize declarative state reconciliation: “Here is exactly what the system should look like right now. Figure out how to make it so, safely.” It is time we manage relational database schemas with that same declarative philosophy. Enter SchemaSynchronizer SchemaSynchronizer is an open-source library for Java and Spring Boot that brings declarative, desired-state schema evolution to relational databases (PostgreSQL, MySQL, MariaDB, SQL Server, and Oracle). Instead of maintaining a perpetually growing chain of migration scripts, your application maintains a single schema-definition.json file representing the current, desired state of your database structure. JSON { "formatVersion": 2, "dialect": "postgresql", "tables": { "work_items": { "createSql": "CREATE TABLE IF NOT EXISTS work_items (id UUID PRIMARY KEY, status VARCHAR(32))", "columns": [ {"name": "id", "definition": "UUID NOT NULL"}, {"name": "status", "definition": "VARCHAR(32)"} ], "indexes": [ "CREATE INDEX IF NOT EXISTS idx_work_items_status ON work_items (status)" ] } }, "changes": [] } On startup, SchemaSynchronizer does not just blindly execute SQL. It executes a state-reconciliation loop. How the Synchronization Engine Works Under the Hood When your Spring Boot application boots, SchemaSynchronizer connects to the database via JDBC and extracts the live catalog metadata. It inspects existing tables, column types, default values, nullability constraints, and indexes. It then computes a diff against your JSON definition and applies changes based on dialect-specific rules. Database engines are notoriously fragmented in how they handle Data Definition Language (DDL). Transactional DDL: On PostgreSQL and SQL Server, SchemaSynchronizer wraps the synchronization process in a transaction. If something fails, the entire schema change is rolled back cleanly.Implicit Commits: MySQL, MariaDB, and Oracle natively commit open transactions the moment a DDL statement is executed. SchemaSynchronizer adjusts its execution strategy for these dialects, relying on granular verification checks rather than transaction rollbacks.Distributed Locking: To prevent multiple application instances from fighting over the schema during a rolling deployment, the library utilizes native distributed lock primitives (pg_try_advisory_xact_lock in Postgres, sp_getapplock in SQL Server, GET_LOCK in MySQL, and DBMS_LOCK in Oracle). The Safety Boundary: Fail-Closed Design The most critical architectural requirement for automated database tooling is preventing accidental data destruction. SchemaSynchronizer is built around a strict, fail-closed safety boundary. It divides schema evolution into two distinct categories: 1. Safe Additive Changes (Automated) If you add a nullable description column to your JSON definition, SchemaSynchronizer detects the missing column and issues the ALTER TABLE ... ADD COLUMN statement automatically on startup. The same applies to creating new tables, creating indexes, widening compatible data types (e.g., VARCHAR(50) to VARCHAR(100)), or relaxing NOT NULL constraints. 2. Destructive or Ambiguous Changes (Manual Review) What happens if you delete a column from the JSON definition? SchemaSynchronizer never infers a DROP operation. If it detects an orphaned live column, or a type narrowing that could truncate data, it halts the synchronization process and outputs the exact SQL required to resolve the difference. Plain Text [SchemaSynchronizer] Destructive difference detected. Manual review required: ALTER TABLE work_items DROP COLUMN old_status; This enforces a hard operational boundary. Routine additive drift is repaired automatically, reducing developer friction, but destructive reconciliation always requires explicit human intervention and approval. Handling Complex Migrations With Checksummed Ledgers Not every database operation can be cleanly inferred from a declarative table structure. Operations that carry specific business logic — such as data backfills, complex CHECK constraints, triggers, or specific user grants — require explicit execution. To handle these, SchemaSynchronizer includes an ordered changes array within the JSON document. These act as an immutable, checksummed ledger, similar to traditional migrations, but with a critical addition: Verification SQL. JSON "changes": [ { "id": "001-work-item-status", "description": "Backfill and constrain work item status", "statements": [ "UPDATE work_items SET status = 'PENDING' WHERE status IS NULL", "ALTER TABLE work_items ALTER COLUMN status SET NOT NULL" ], "verificationSql": "SELECT NOT EXISTS (SELECT 1 FROM work_items WHERE status IS NULL)", "phase": "AFTER_SCHEMA" } ] The verificationSql must be a read-only query that returns a boolean true. This ensures idempotency. If the database already satisfies the verification query (perhaps because a DBA manually applied the fix during an incident), SchemaSynchronizer records the change set as completed without attempting to blindly replay the UPDATE statements. Implementation: Spring Boot and CLI SchemaSynchronizer integrates natively into Java applications. For Spring Boot, add the dependency to your build file: Maven: XML <dependency> <groupId>com.thinkaillc</groupId> <artifactId>schema-synchronizer</artifactId> <version>2.0.0</version> </dependency> Configure your application.properties to enable the initializer and tell Hibernate to back off and only validate the schema: Properties files schema-synchronizer.enabled=true schema-synchronizer.schema=public schema-synchronizer.fail-on-pending=true # Let SchemaSynchronizer handle DDL; tell Hibernate to just validate spring.jpa.hibernate.ddl-auto=validate The Standalone CLI Pipeline Many organizations prefer to decouple schema migrations from application startup, executing them directly from a CI/CD pipeline (like GitHub Actions or Jenkins). SchemaSynchronizer ships a standalone executable JAR bundling the JDBC drivers for all supported engines. You can dry-run a deployment against a target database to see exactly what would change, without committing any DDL: Shell export SCHEMA_DB_PASSWORD='target-password' java -jar schema-synchronizer-cli-2.0.0-standalone.jar dry-run \ jdbc:postgresql://localhost:5432/target_app app_user - \ schema-definition.json public schema_synchronizer_history Ready to Drop the Migration Scripts? Imperative migration scripts served the Java ecosystem well for years, but as our deployment topologies grow more complex, managing hundreds of linear state-transition files becomes a liability. By adopting a declarative approach, you can eliminate merge conflicts on migration files, instantly stand up new environments from a single source of truth, and enforce a strict safety boundary that prevents automated tooling from ever dropping production data. Check out the architecture, dialect support, and Quick Start guides on the repository: GitHub: eugenena/SchemaSynchronizer

By Eugene Naoumov
Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

The message left the first service at 2:14 PM and never reached the last one. Between those facts: four pipeline stages, six topics, a pub/sub API moving every record. The engineer on call had Kafdrop open, the offsets looked fine, and nobody could say which stage had eaten the record. That gap is why we built message search for Kafdrop at a hackathon. The setup was familiar from my day job: a platform moving data between pipeline stages over a pub/sub API, with no way to ask where a message went when something breaks. Kafdrop showed partitions and offsets. It couldn't search inside the messages. Kafka has no index. That is the whole problem in one sentence. A topic is an append-only log split across partitions, and the consumer API reads by offset: hand it 41,207, and it returns record 41,207. There is no "find the record containing order-88412." To search, you pick a starting point and read forward until you find what you want or stop. So that is what our feature does, with guardrails that keep the search from hurting the cluster. The interesting part was the caps, the consumer setup, and the SRE agreement. Why a Full Scan Is Not an Option The obvious approach is to read the whole topic and grep. Topics hold days of data, so the whole thing doesn't fit in memory. Reading every record on every search hammers the brokers, and during an incident that is the worst time to add load. Most searches end with a few matches, so nearly all of that work is wasted. The other approach is to mirror every topic into a search engine. That works, and plenty of teams do it. It also means running a second distributed system and explaining index lag during every incident. For a hackathon debugging tool, that was too much machinery. The Design: Seek, Scan, and Stop The feature takes four inputs: a topic, a query string, a start time, and two caps. The start time bounds how far back the search goes. Kafka's offsetsForTimes maps a timestamp to the first offset at or after it per partition, or null when the partition holds nothing that new. The user picks "the last hour" or "since the deploy." The result cap bounds memory: return the first N matches and stop. Debugging usually needs one record, not ten thousand. The scan cap bounds broker load: stop after M records even with no match. Every search becomes a fixed amount of work, whatever the user types. A typo costs M reads. The scan can never grow beyond that. Polls use bounded batches, so the tool never holds more than one page of records at a time. Nothing loads a whole topic. Safety: Assign, Don't Subscribe The consumer setup is where a search tool can quietly cause damage. Three decisions were non-negotiable. First, the search consumer uses assign, not subscribe. Subscribe joins a consumer group, bringing coordination and rebalances. A debugging tool has no business in any of that. Assign hands the consumer a fixed partition list and stays out of group coordination entirely. Second, the consumer never commits offsets. Auto-commit is off, and the code never calls commit. The default config commits automatically, so this is the one that bites: a search tool that advances a production group's offsets is a horror story, and the fix is one config line. Third, the scan cap doubles as a safety control: every search reads at most M records, a worst case SRE can read before approving. The Search Loop Here is the core in Java. The three constants are the whole design: matches to return, records to read in the worst case, records per poll. The values are illustrative; tune them to your topics. Java private static final int RESULT_CAP = 25; private static final int SCAN_CAP = 50_000; private static final int POLL_BATCH = 500; public List<FoundMessage> search(String topic, String query, long startTimeMs) { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, String.valueOf(POLL_BATCH)); List<FoundMessage> matches = new ArrayList<>(); try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) { List<TopicPartition> partitions = new ArrayList<>(); for (PartitionInfo p : consumer.partitionsFor(topic)) { partitions.add(new TopicPartition(topic, p.partition())); } consumer.assign(partitions); Map<TopicPartition, Long> times = new HashMap<>(); for (TopicPartition tp : partitions) times.put(tp, startTimeMs); for (Map.Entry<TopicPartition, OffsetAndTimestamp> e : consumer.offsetsForTimes(times).entrySet()) { if (e.getValue() != null) consumer.seek(e.getKey(), e.getValue().offset()); else consumer.seekToEnd(Collections.singletonList(e.getKey())); } long scanned = 0; while (scanned < SCAN_CAP && matches.size() < RESULT_CAP) { ConsumerRecords<String, String> batch = consumer.poll(Duration.ofMillis(500)); if (batch.isEmpty()) break; for (ConsumerRecord<String, String> r : batch) { if (++scanned > SCAN_CAP) break; if (r.value() != null && r.value().contains(query)) { matches.add(new FoundMessage(r.topic(), r.partition(), r.offset(), r.timestamp(), r.value())); if (matches.size() >= RESULT_CAP) break; } } } } return matches; } From the top: the config disables auto-commit and fixes the poll batch size. Assign takes a fixed partition list. offsetsForTimes turns the start time into a starting offset per partition; the null branch seeks to the end for partitions with nothing that new. The loop reads forward and stops at whichever cap hits first. Nothing commits, and try-with-resources closes the consumer. Matching is a substring check on the record value. Tombstones carry nulls, so the null check is load-bearing. Shipping It: A Container, Kubernetes, and the SRE Agreement The app ships as a container image: the search service and its config, nothing else. It runs on Kubernetes as a small deployment with tight resource limits, since the result cap already bounds memory. One replica is plenty. YAML apiVersion: apps/v1 kind: Deployment metadata: name: kafdrop-search spec: replicas: 1 selector: matchLabels: app: kafdrop-search template: metadata: labels: app: kafdrop-search spec: containers: - name: search image: registry.example.com/kafdrop-search:1.0.0 resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" env: - name: KAFKA_BROKERS value: "kafka:9092" The manifest is deliberately boring: one replica, tight memory limits, brokers passed as config. The SRE conversation was short, because the design answered their questions first. The tool only reads: assign instead of subscribe, no offset commits, read-only Kafka credentials. Every search is bounded by the scan cap, so the worst case was a number everyone could read. That agreement mattered more than the code. The caps were the trust. A Debugging Routine That Works First, search the topic for the message using something unique: an order ID, a request ID. Found it? Note the offset and timestamp. Second, check consumer group lag for the downstream stage. If the group consumed past your message's offset, the stage read it, and the problem is in the consumer's logic. If lag is stuck or growing, the consumer is behind, crashed, or wedged on a poison record. Third, look at the consumer: logs around the message's timestamp, error handling, the dead-letter path. The order matters. It separates "the message never arrived" from "the message arrived and something went wrong." Before, step one was guesswork. Now it takes minutes. What We Kept Kafka gives you ordering and durability, not search. Bolting search onto an append-only log means accepting the scan. Make it bounded and boring: seek to a timestamp, read forward in small batches, stop at the first cap. Keep the three decisions that made it safe. Assign instead of subscribe, so the tool never joins a consumer group. Never commit offsets, so reading changes nothing. A scan cap that turns every search into a known quantity of broker work. Get those right, and SRE will let you run it against production. Get them wrong, and you have built a very efficient way to cause your next incident. After the hackathon, the team kept the tool for one job: finding where a message stopped. A search, a lag check, and a look at the consumer, done in minutes. Diagnosis time during incidents fell.

By Shreyamsh Kamate

Monthly Top Java Experts

expert thumbnail

Markus Eisele

Developer Strategist,
IBM Research

Markus Eisele is a Java Champion, former Java EE Expert Group member, Java community leader of German DOAG, founder of JavaLand, reputed speaker at Java conferences around the world, and a very well known figure in the Enterprise Java world. You’ve known and seen him at different conferences and Java User Groups meetups or read his blogs or are following his social media presence. While talking about middleware for many years you’ll continue to hear him talk about enterprise grade Java going forward. Focussed on education about the latest trends in building enterprise systems with Java. He’s been looking into containers and microservices architectures more deeply and also wrote a book about modern Java EE Design Patterns with O’Reily. He is excited to educate more about how microservices architectures can integrate and complement existing platforms, and will also talk about how to successfully build resilient applications with Java. twitter: @myfear
expert thumbnail

Hüseyin Akdoğan

Software Craftsman

Backend engineer with 20+ years of enterprise Java experience. Since 2005, I have builtenterprise systems, led teams, and delivered training and consultancy on Java runtimessuch as Spring and Quarkus, as well as messaging, reactive and data technologies. Most recently, I have focused on Identity and Access Management built on Keycloak,working on authorization infrastructure, Java SDKs and large-scale identity migrations,and contributing upstream to the Keycloak project. Across all of this work, I care aboutsoftware craftsmanship: understanding complex systems, solving problems at scale andimproving engineering practices. I am one of the leaders of JUG İstanbul, a frequent conference speaker, and the author of Elasticsearch Indexing. I follow the evolution of the Java platform closely, includingOpenJDK projects Loom, Valhalla, Amber, Panama and Leyden.
expert thumbnail

Otavio Santana

Award-winning Software Engineer and Architect,
OS Expert

Otavio is an award-winning software engineer and architect passionate about empowering other engineers with open-source best practices to build highly scalable and efficient software. He is a renowned contributor to the Java and open-source ecosystems and has received numerous awards and accolades for his work. Otavio's interests include history, economy, travel, and fluency in multiple languages, all seasoned with a great sense of humor.
expert thumbnail

Daniel Oh

Senior Principal Developer Advocate,
IBM

Java Champion, CNCF Ambassador & TAG DevEX Co-Chair, AAIF Ambassador, Microsoft MVP, Developer Advocate, Technical Marketing, Keynote Speaker, Published Author

The Latest Java Topics

article thumbnail
Getting Started With Weaviate: Building AI-Powered Search Applications With Java
Explore Weaviate vector search with enterprise Java using Eclipse JNoSQL, Docker, and LangChain4j for semantic retrieval and vector persistence.
November 23, 2026
by Otavio Santana DZone Core CORE
· 264 Views
article thumbnail
Getting Started With Qdrant: Building Intelligent Search Applications With Java
Learn about Qdrant vector search with Java and Eclipse JNoSQL, combining semantic retrieval with structured filtering for enterprise applications.
November 20, 2026
by Otavio Santana DZone Core CORE
· 865 Views
article thumbnail
Getting Started With Milvus: Vector Search for Enterprise Java Applications
Integrate Milvus vector search into Java applications with Eclipse JNoSQL, LangChain4j, and familiar Jakarta persistence APIs.
November 19, 2026
by Otavio Santana DZone Core CORE
· 834 Views · 1 Like
article thumbnail
Pitching Kotlin: An Engineering Leader's Guide to Legacy Modernization
Most Kotlin pitches stall on developer preference. This reviewer's framework prices the friction, phases the rollout behind gates, and wins approval.
November 17, 2026
by Yuri Geronimus
· 1,061 Views · 1 Like
article thumbnail
Reading GC Logs: Memory Leak or Undersized Heap?
A large live set after repeated full GCs doesn't prove a leak. Rising post-GC floor = accumulation; stable high floor = undersized heap.
November 17, 2026
by Amit Sonar
· 810 Views
article thumbnail
Spring Boot's Hidden Secret for Configuration: EnvironmentPostProcessor
Learn how to use Spring Boot's EnvironmentPostProcessor to load, merge, and prioritize configuration from shared libraries.
November 16, 2026
by Mikhail Polivakha
· 1,045 Views · 1 Like
article thumbnail
Building an AI-Powered Code Review Assistant in Java
Wire up LangChain4j to an LLM, submit Java code snippets, and get structured improvement suggestions back, all from plain Java.
November 16, 2026
by Akhil Sabu
· 1,202 Views
article thumbnail
Modernizing a Legacy Java Application With OpenRewrite: What We Automated and What We Didn't
A practical look at OpenRewrite for large-scale Java/Spring refactoring, including automated transformations, SQL limitations, and runtime issues.
November 16, 2026
by Kirankumar Phirangi
· 1,330 Views
article thumbnail
From Database Changes to Real-Time Actions at Scale: Oracle GoldenGate and Java
Learn how to stream database changes through Oracle GoldenGate and Kafka to Java services while preserving transaction order and boundaries.
November 13, 2026
by Sushant Sakolkar
· 1,105 Views
article thumbnail
Persisting Cookies Across JAX-WS Service Calls Using a Custom SOAP Handler
A custom SOAP handler preserves JAX-WS session cookies across calls without JVM-wide state, using ThreadLocal isolation and explicit cleanup to prevent session leaks.
November 12, 2026
by Vishal Rameshchandra Shah
· 1,115 Views
article thumbnail
Best of Three Worlds: AI Agents Writing In Rust and Java Beat the C Library
How two pure-language image decoders: one in Rust and one in Java, ended up beating libheif, and what I learned about getting AI agents to improve each other's work.
November 12, 2026
by Yannick Majoros
· 1,470 Views · 1 Like
article thumbnail
Java to TypeScript in a Day: AI Migration Playbook
Learn from my journey using AI to build a TypeScript version of a Java in-memory database (Kiara DB), including the workflow and pitfalls to avoid.
November 4, 2026
by Anuj Kapoor
· 318 Views · 1 Like
article thumbnail
Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
If a container has 1 CPU or under 1,792 MB, Java 27 silently switches it from Serial GC to G1. Test those services before you upgrade.
November 3, 2026
by Garima Agarwal
· 1,853 Views · 1 Like
article thumbnail
Build a GitHub Contribution City With Java and Quarkus
Turn your contribution calendar into an SVG skyline, add it to your profile, and build a DZone-inspired version with a custom palette and character shapes.
November 2, 2026
by Markus Eisele
· 1,383 Views · 1 Like
article thumbnail
Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
Learn to bring declarative, desired-state schema evolution to your Java applications, eliminating migration merge conflicts and preventing accidental data loss.
October 29, 2026
by Eugene Naoumov
· 2,448 Views · 4 Likes
article thumbnail
Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
Build bounded Kafka message search into Kafdrop using Java, with timestamp-based scans, memory limits, and safe consumer configuration.
October 28, 2026
by Shreyamsh Kamate
· 2,202 Views · 2 Likes
article thumbnail
Part 4: Multi-Agent Orchestration — Pairing Goose With Quarkus Flow State Machines
Bridge Goose agent interactions with Quarkus Flow state machines governed by AGENTS.md rules and integrated via the A2A protocol to enforce human-in-the-loop approvals.
October 27, 2026
by Daniel Oh DZone Core CORE
· 2,235 Views · 1 Like
article thumbnail
Introduction to Error Prone: How to Catch Bugs at Compile Time
Error Prone plugs into javac and fails the build on code that compiles but is almost certainly wrong. It often suggests the fix, too, and you can add your own checks.
October 27, 2026
by Hüseyin Akdoğan DZone Core CORE
· 1,867 Views · 1 Like
article thumbnail
ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
Explore ScyllaDB for enterprise Java applications using Eclipse JNoSQL with Jakarta NoSQL templates and Jakarta Data repositories.
October 23, 2026
by Otavio Santana DZone Core CORE
· 1,739 Views
article thumbnail
Member Spotlight: Shai Almong
DZone Core Member Shai Almog shares open-source maintenance lessons, why his team stopped accepting outside pull requests, and how agentic dev helps small teams compete.
October 23, 2026
by Dominique Pugh
· 2,444 Views · 4 Likes
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×