Wednesday, September 23, 2026

JDK-27: hard sell?

The JDK release train is so stable that many do not pay attention anymore! Nonetheless, the new JDK-27 release is there and quite a few things to unpack.

  • JEP 527: Post-Quantum Hybrid Key Exchange for TLS 1.3: enhances the security of Java applications that require secure network communication by implementing hybrid key exchange algorithms for TLS 1.3. Such algorithms defend against future quantum computing attacks by combining a quantum-resistant algorithm with a traditional algorithm. Applications that use the javax.net.ssl APIs will benefit from these improved algorithms by default, without change to existing code.

  • JEP 523: Make G1 the Default Garbage Collector in All Environments: makes the Garbage-First (G1) garbage collector the default collector in all environments, rather than just server environments. It worth noting that all other collectors are still available and could be specified, only default changes.

  • JEP 534: Compact Object Headers by Default: makes compact object headers the default object header layout in the HotSpot JVM. Compact object headers reduce object headers from 96 bits down to 64 bits on 64-bit architectures, thereby reducing heap size, improving deployment density, and increasing data locality.

  • JEP 536: JFR In-Process Data Redaction: enhances JDK Flight Recorder (JFR) to redact command-line arguments and the initial values of environment variables and system properties in recordings. Redact this data before it leaves the process, so that sensitive information does not leak.

    The new sub-options redact-key and redact-argument have been introduced, allowing to specify one or more filters that select the command-line arguments, environment variables, and system properties to be redacted.

      java -XX:FlightRecorderOptions:'redact-key=confidential,redact-argument=https://*:*@*' ...
      

Quite a few preview and incubating (vectors!) features have been carried over from the previous releases, notably:

  • JEP 538: PEM Encodings of Cryptographic Objects (Third Preview): introduces an API for encoding objects that represent cryptographic keys, certificates, and certificate revocation lists into the widely-used Privacy-Enhanced Mail (PEM) transport format, and for decoding from that format back into objects. This is a preview API feature.

  • JEP 532: Primitive Types in Patterns, instanceof, and switch (Fifth Preview): enhances pattern matching by allowing primitive types in all pattern contexts, and extend instanceof and switch to work with all primitive types. This is a preview language feature.

  • JEP 531: Lazy Constants (Third Preview): introduces an API for lazy constants, which are objects that hold unmodifiable data. Lazy constants are treated as true constants by the JVM, enabling the same performance optimizations that are enabled by declaring a field final. Compared to final fields, however, lazy constants offer greater flexibility as to the timing of their initialization. This is a preview API feature.

  • JEP 533: Structured Concurrency (Seventh Preview): simplifies concurrent programming by introducing an API for structured concurrency. Structured concurrency treats groups of related tasks running in different threads as single units of work, thereby streamlining error handling and cancellation, improving reliability, and enhancing observability. This is a preview API feature.

  • JEP 537: Vector API (12th Incubator): introduces an API to express vector computations that reliably compile at run time to optimal vector instructions on supported CPUs, thus achieving performance superior to equivalent scalar computations. This is an incubating API feature.

The standard library (to my surprise at least) got only a handful of changes and bug fixes introduced, the most interesting ones are below.

That was it. Let us take a look which changes went into JVM itself, including garbage collection:

Moving on to JDK and tooling, a number of highlights here:

The list of different security related fixes and enhancements is truly impressive:

By and large, JDK-27 is not the release that brings a lot to the table. Still, for many the post-quantum cryptography could be the thing warranting the adoption. All eye towards JDK-28 now.

I πŸ‡ΊπŸ‡¦ stand πŸ‡ΊπŸ‡¦ with πŸ‡ΊπŸ‡¦ Ukraine.

Sunday, June 28, 2026

Unexpected usefulness of the MessageDigest::isEqual method

How one would compare two Strings for equality in Java? There are a few options that come to mind, String::equals or Objects::equals would probably be among those. But for certain, not MessageDigest::isEqual, not even close.

So what gives? No doubts, String::equals is very efficient and returns result as soon as possible. In majority of cases, this is the desired behavior. But what if you compare secrets or alike? For example, tokens, API keys, etc. Not a big deal, right? It turns out it is, your code might be susceptible to so called timing attacks. The gist of it is that comparing two String values is the function of a) their sizes b) how many matching characters they have consequently. The attacker could apply brute force tactics and figure out what the size of the expected secret should be and then, with some patience, guess the characters. All that just by capturing how much time the comparison takes.

How MessageDigest::isEqual helps, you may ask? It actually examines all the bytes of the first argument, as such the calculation time depends only on its length and it does not depend on the length of the second argument (nor the contents of both).

So next time you see the snippet like this

MessageDigest.isEqual(
    token1.getBytes(StandardCharsets.UTF_8), 
    token2.getBytes(StandardCharsets.UTF_8));

where there is seemingly nothing going on related to message digests, you know why.

I πŸ‡ΊπŸ‡¦ stand πŸ‡ΊπŸ‡¦ with πŸ‡ΊπŸ‡¦ Ukraine.

Saturday, March 21, 2026

JDK-26: incremental improvement

Time for celebration once again: the JDK-26 was released just a few days ago! Although from all perspectives this release looks like incremental improvement (not a feature fest), it is worth paying close attention to.

  • JEP 500: Prepare to Make Final Mean Final: issues warnings about uses of deep reflection to mutate final fields. These warnings aim to prepare developers for a future release that ensures integrity by default by restricting final field mutation, which will make Java programs safer and potentially faster. Application developers can avoid both current warnings and future restrictions by selectively enabling the ability to mutate final fields where essential using --enable-final-field-mutation=module1,module2,... and --illegal-final-field-mutation=allow|warn}debug|deny command line arguments.

  • JEP 516: Ahead-of-Time Object Caching with Any GC: enhances the ahead-of-time cache, which enables the HotSpot Java Virtual Machine to improve startup and warmup time, so that it can be used with any garbage collector, including the low-latency Z Garbage Collector (ZGC). Achieve this by making it possible to load cached Java objects sequentially into memory from a neutral, GC-agnostic format, rather than map them directly into memory in a GC-specific format.

    GC-specific cached objects are mapped directly into memory, while GC-agnostic cached objects are streamed into memory. You can explicitly create a cache whose objects are in the streamable, GC-agnostic format by specifying -XX:+AOTStreamableObjects.

  • JEP 517: HTTP/3 for the HTTP Client API: updates the HTTP Client API to support the HTTP/3 protocol, so that libraries and applications can interact with HTTP/3 servers with minimal code change.

      var client = HttpClient
          .newBuilder()
          .version(HttpClient.Version.HTTP_3)
          .build();
      

    Interestingly, JDK does not provide HTTP/3 server implementation (yet), however Netty library, the de facto standard in Java ecosystem for implementing high performance protocol servers (and clients), is supporting HTTP/3 in 4.2 release line.

  • JEP 522: G1 GC: Improve Throughput by Reducing Synchronization: increases application throughput when using the G1 garbage collector by reducing the amount of synchronization required between application threads and GC threads.

  • JEP 504: Remove the Applet API: removes the Applet API, which was deprecated for removal in JDK 17. It is obsolete because neither recent JDK releases nor current web browsers support applets.

There are a few JEPs that made into JDK-26 as preview features, all of them are carried over from the previous JDK releases.

  • JEP 524: PEM Encodings of Cryptographic Objects (2nd Preview): introduces an API for encoding objects that represent cryptographic keys, certificates, and certificate revocation lists into the widely-used Privacy-Enhanced Mail (PEM) transport format, and for decoding from that format back into objects. This is a preview API feature.

  • JEP 525: Structured Concurrency (6th Preview): simplifies concurrent programming by introducing an API for structured concurrency. Structured concurrency treats groups of related tasks running in different threads as single units of work, thereby streamlining error handling and cancellation, improving reliability, and enhancing observability. This is a preview API feature.

  • JEP 526: Lazy Constants (2nd Preview): introduces an API for lazy constants, which are objects that hold unmodifiable data. Lazy constants are treated as true constants by the JVM, enabling the same performance optimizations that are enabled by declaring a field final. Compared to final fields, however, lazy constants offer greater flexibility as to the timing of their initialization. This is a preview API feature.

    This feature used to be known as stable values (JDK-25) and was renamed to lazy constants to better capture its intended use cases.

  • JEP 530: Primitive Types in Patterns, instanceof, and switch (4th Preview): enhances pattern matching by allowing primitive types in all pattern contexts, and extend instanceof and switch to work with all primitive types. This is a preview API feature.

  • JEP 529: Vector API (11th Incubator): introduces an API to express vector computations that reliably compile at runtime to optimal vector instructions on supported CPUs, thus achieving performance superior to equivalent scalar computations.

Indeed, the list of JEPs is not very impressive, but it does not make JDK-26 less important. There are quite a lot of interesting fixes and improvements in this release.

For more elaborate overview of GC changes, please refer to JDK 26 G1/Parallel/Serial GC changes blog post. Besides just JEP 517, the java.net.http.HttpClient got quite a lot of attention in this JDK release, certainly worth highlighting separately.

Another notable changes in JDK include:

This is pretty much it but we haven't talked about security related changes, it is just about time.

If you look for a bit more in-depth overview of the security related changes, please check out JDK 26 Security Enhancements blog post.

To summarize, the gems of JDK-26 release, in my opinion, are JEP 522: G1 GC: Improve Throughput by Reducing Synchronization, JEP 517: HTTP/3 for the HTTP Client API, and JDK-8369238: Allow virtual thread preemption on some common class initialization paths. Those are truly game changing enhancements for quite a wide audience of applications and services. Java continues to impress!

I πŸ‡ΊπŸ‡¦ stand πŸ‡ΊπŸ‡¦ with πŸ‡ΊπŸ‡¦ Ukraine.

Friday, December 19, 2025

DuckDB: very useful were least expected

If you haven't heard about DuckDB yet, you definitely have to check it out. It is fascinating piece of technology for quick data exploration and analysis. But today we are going to talk about somewhat surprising but exceptionally useful area where DuckDB could be tremendously helpful - dealing with chatty HTTP/REST services.

One of the best things about DuckDB is that it is just a single binary (per OS/arch), with no additional dependencies, so the installation process is a breath.

Let me set the stage here. I have been working with OpenSearch (and Elasticsearch) for years, those are great search engines with very reach HTTP/REST APIs. The production grade clusters constitute hundreds of nodes, and at this scale, mostly every single cluster wide HTTP/REST endpoint invocation returns unmanageable JSON blobs. Wouldn't it be cool to somehow transform such JSON blobs into structured, queryable form somehow? Like relational table for example and run SQL queries over it, without writing a single line of code? It is absolutely doable with DuckDB and its JSON Processing Functions.

As an exercise, we are going to play with Nodes API which returns a detailed per node response, following deep nested JSON structure:

{
  "cluster_name" : "...",
  "_nodes" : {
     ...
  },
  "nodes" : {
    <node1> : {
        ...
    },
    <node2> : {
        ...
    },
    ...
    <nodeN> : {
        ...
    }
  }

Ideally, what we want is to flatten this structure into a table where each row represents individual node and each JSON key becomes an individual column by itself. To put things in the context, each node structure has nested arrays and objects, we will not recursively traverse them (although it is possible but needs more complex transformations). With that, let us start our exploration journey!

The first step is the simplest: extract nodes collection of objects from the Nodes API response and just feed it directly into DuckDB.

$ curl "https://localhost:9200/_nodes?pretty" -u admin:<password> -k --raw -s | duckdb -c "
  WITH nodes AS (
    SELECT key as id, value FROM  read_json_auto('/dev/stdin') AS r, json_each(r, '$.nodes')
  )
  SELECT * FROM nodes"

We would get back something like this (the OpenSearch cluster I use for tests has only two nodes, hence we see only two rows):

┌──────────────────────┬────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│          id          │                                                                 value                                                                  │
│       varchar        │                                                                  json                                                                  │
├──────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ YQzVQ_kHT-WnYTReh0…  │ {"name":"opensearch-node2","transport_address":"10.89.0.3:9300","host":"10.89.0.3","ip":"10.89.0.3","version":"3.0.0","build_type":"…  │
│ J9a5OM8STainCdkaLm…  │ {"name":"opensearch-node1","transport_address":"10.89.0.2:9300","host":"10.89.0.2","ip":"10.89.0.2","version":"3.0.0","build_type":"…  │
└──────────────────────┴────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

Although we could stop just here (since DuckDB lets you query over JSON values easily), we would like to do something useful with value blob: we want it to become a table with real columns. There are many ways that could be accomplished in DuckDB, some do require precise JSON structure (schema) to be provided, some require predefined list of keys upfront. We would stick to dynamic exploration instead and extract all keys from the actual JSON data.

$ curl "https://localhost:9200/_nodes?pretty" -u admin:<password> | duckdb -c "
  WITH nodes AS (
    SELECT key as id, value FROM  read_json_auto('/dev/stdin') AS r, json_each(r, '$.nodes')
  ),
  all_keys AS (
    SELECT distinct(unnest(json_keys(value))) AS key FROM nodes
  )
  SELECT * FROM all_keys"

In the version of the OpenSearch I am running, there are 22 unique keys (JSON field names) returned, an example of the output is below:

┌────────────────────────────────┐
│              key               │
│            varchar             │
├────────────────────────────────┤
│ plugins                        │
│ jvm                            │
│ host                           │
│ version                        │
│ build_hash                     │
│ ...                            │
│ modules                        │
│ build_type                     │
│ os                             │
│ transport                      │
│ search_pipelines               │
│ attributes                     │
├────────────────────────────────┤
│            22 rows             │
└────────────────────────────────┘

Good progress so far, but we need to go over the last mile and build a relational table out of these pieces. This is where DuckDB's powerful PIVOT statement comes in very handy.

$ curl "https://localhost:9200/_nodes?pretty" -u admin:<password> | duckdb -c "
  WITH nodes AS (
    SELECT key as id, value FROM  read_json_auto('/dev/stdin') AS r, json_each(r, '$.nodes')
  ),
  all_keys AS (
    SELECT distinct(unnest(json_keys(value))) AS key FROM nodes
  ),
  keys AS (
    SELECT * FROM all_keys WHERE key not in ['plugins', 'modules']
  )
  SELECT id, node.* FROM nodes, (PIVOT keys ON(key) USING first(json_extract(value, '$.' || key))) as node"

And here we are:

┌──────────────────────┬──────────────────────┬──────────────────────┬──────────────────────┬───┬──────────────────────┬──────────────────────┬──────────────────────┬───────────────────┬─────────┐
│          id          │     aggregations     │      attributes      │      build_hash      │ … │     thread_pool      │ total_indexing_buf…  │      transport       │ transport_address │ version │
│       varchar        │         json         │         json         │         json         │   │         json         │         json         │         json         │       json        │  json   │
├──────────────────────┼──────────────────────┼──────────────────────┼──────────────────────┼───┼──────────────────────┼──────────────────────┼──────────────────────┼───────────────────┼─────────┤
│ YQzVQ_kHT-WnYTReh0…  │ {"adjacency_matrix…  │ {"shard_indexing_p…  │ "dc4efa821904cc2d7…  │ … │ {"remote_refresh_r…  │ 53687091             │ {"bound_address":[…  │ "10.89.0.3:9300"  │ "3.0.0" │
│ J9a5OM8STainCdkaLm…  │ {"adjacency_matrix…  │ {"shard_indexing_p…  │ "dc4efa821904cc2d7…  │ … │ {"remote_refresh_r…  │ 53687091             │ {"bound_address":[…  │ "10.89.0.2:9300"  │ "3.0.0" │
├──────────────────────┴──────────────────────┴──────────────────────┴──────────────────────┴───┴──────────────────────┴──────────────────────┴──────────────────────┴───────────────────┴─────────┤
│ 2 rows                                                                                                                                                                      21 columns (9 shown) │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

As we set for the goal, we have transformed each node from JSON to structured table. There is one subtle quirk to mention, the presence of the additional step to filter out plugins and modules fields from the transformations, DuckDB seems to have difficulties pivoting those:

Binder Error:
PIVOT is not supported in correlated subqueries yet

I hope you find it useful, typical enterprise grade HTTP/REST services often throw a pile of JSON at you, try to make sense of it!

I πŸ‡ΊπŸ‡¦ stand πŸ‡ΊπŸ‡¦ with πŸ‡ΊπŸ‡¦ Ukraine.

Sunday, September 21, 2025

JDK-25: The Next Big Thing

Not exactly sure why but JDK-25 is a long awaited release. Probably because it is the next LTS (or whatever it means these days), or probably because it establishes a new baseline where there is no place for SecurityManager anymore. In any case, let us talk about everything that JDK-25 bundles in, starting with the stable features first.

  • JEP-506: Scoped Values: introduces scoped values, which enable a method to share immutable data both with its callees within a thread, and with child threads. Scoped values are easier to reason about than thread-local variables. They also have lower space and time costs, especially when used together with virtual threads and structured concurrency.

    Since the API is final now, let us take a look at it closely.

       private static final ScopedValue<Object> CONTEXT = ScopedValue.newInstance();
    
       executor.submit(() -> ScopedValue.where(CONTEXT, new Object()).run(() -> {
           final Object context = CONTEXT.get();
           // Use 'context'
        }));
      

    In simple terms, you can think of scoped values as an immutable ThreadLocals, however their true power kicks in with structured concurrency, which sadly is still in preview in JDK-25.

  • JEP-511: Module Import Declarations: enhances the Java programming language with the ability to succinctly import all of the packages exported by a module. This simplifies the reuse of modular libraries, but does not require the importing code to be in a module itself.

    This is pretty useful and simple enhancement that helps with imports explosion, for example:

      import module jdk.jfr;
     
  • JEP-512: Compact Source Files and Instance Main Methods: evolves the Java programming language so that beginners can write their first programs without needing to understand language features designed for large programs. Far from using a separate dialect of the language, beginners can write streamlined declarations for single-class programs and then seamlessly expand their programs to use more advanced features as their skills grow. Experienced developers can likewise enjoy writing small programs succinctly, without the need for constructs intended for programming in the large.

    It is now possible to omit some boilerplate when using the language:

      void main() {
          IO.println("Hello, World!");
      }
      
  • JEP-510: Key Derivation Function API: introduces an API for Key Derivation Functions (KDFs), which are cryptographic algorithms for deriving additional keys from a secret key and other data.

  • JEP-503: Remove the 32-bit x86 Port: removes the source code and build support for the 32-bit x86 port. This port was deprecated for removal in JDK 24.

  • JEP-514: Ahead-of-Time Command-Line Ergonomics: makes it easier to create ahead-of-time caches, which accelerate the startup of Java applications, by simplifying the commands required for common use cases.

    This is really nice improvement over two-step workflow in JDK 24 (please notice a new -XX:AOTCacheOutput command line flag), only one step is now required:

    $ java -XX:AOTCacheOutput=app.aot -cp app.jar com.example.App ...

    As a convenience, when operating in this way the JVM creates a temporary file for the AOT configuration and deletes the file when finished. The command line to run the application stays the same:

    $ java -XX:AOTCache=app.aot -cp app.jar com.example.App ...

    A new environment variable, JDK_AOT_VM_OPTIONS, can be used to pass command-line options that apply specifically to cache creation (AOTMode=create), without affecting the training run (AOTMode=record). The syntax is the same as for the existing JAVA_TOOL_OPTIONS environment variable. This enables the one-step workflow to apply even in use cases where it might seem that two steps are necessary due to differences in the command-line options.

  • JEP-513: Flexible Constructor Bodies: in the body of a constructor, allows statements to appear before an explicit constructor invocation, i.e., super(...) or this(...). Such statements cannot reference the object under construction, but they can initialize its fields and perform other safe computations. This change allows many constructors to be expressed more naturally. It also allows fields to be initialized before they become visible to other code in the class, such as methods called from a superclass constructor, thereby improving safety.

    In my opinion, this feature would greatly improve the readability of the class initialization, let us take a look at the example:

         class ByteArrayInputStreamInputStream extends ByteArrayInputStream {
            public ByteArrayInputStreamInputStream(int size) {
                if (size <= 0) {
                    throw new IllegalArgumentException("The size has to be greater than 0");
                }
                super(new byte[size]);
            }
        }
        

    In pre-JDK-25, super(...) had to be the first statement in the constructor body and we would have no choice but to implement a function to validate the size and return new byte array (or throw an IllegalArgumentException exception).

  • JEP-519: Compact Object Headers: changes compact object headers from an experimental feature (introduced in JDK 24) to a product feature. To enable this feature pass command line option:

    $ java -XX:+UseCompactObjectHeaders
  • JEP-521: Generational Shenandoah: changes the generational mode of the Shenandoah garbage collector from an experimental feature (introduced in JDK 24) to a product feature. The generational mode could be enabled through command line flags:

    $ java -XX:+UseShenandoahGC -XX:ShenandoahGCMode=generational
  • JEP-515: Ahead-of-Time Method Profiling: improves warmup time by making method-execution profiles from a previous run of an application instantly available, when the HotSpot Java Virtual Machine starts. This will enable the JIT compiler to generate native code immediately upon application startup, rather than having to wait for profiles to be collected.

  • JEP-518: JFR Cooperative Sampling: improves the stability of the JDK Flight Recorder (JFR) when it asynchronously samples Java thread stacks. Achieves this by walking call stacks only at safepoints, while minimizing safepoint bias.

    There is a new event introduced, jdk.SafepointLatency, which records the time it takes for a thread to reach a safepoint, for example:

        $ java -XX:StartFlightRecording:jdk.SafepointLatency#enabled=true,filename=recording.jfr
        $ jfr print --events jdk.SafepointLatency recording.jfr
        
  • JEP-520: JFR Method Timing & Tracing: extends the JDK Flight Recorder (JFR) with facilities for method timing and tracing via bytecode instrumentation.

    There are two new JFR events introduced, jdk.MethodTiming and jdk.MethodTrace, they both accept a filter to select the methods to time and trace, couple of the examples below:

        $ java '-XX:StartFlightRecording:jdk.MethodTrace#filter=java.util.HashMap::resize,filename=recording.jfr' ...
        $ jfr print --events jdk.MethodTrace --stack-depth 20 recording.jfr
        
        $ java '-XX:StartFlightRecording:filename=fd.jfr,method-trace=java.io.FileDescriptor::<init>java.io.FileDescriptor::close' ..
        $ jfr view --cell-height 5 MethodTrace fd.jfr
        
        $ java '-XX:StartFlightRecording:method-timing=::<clinit>,filename=clinit.jfr' ...
        $ jfr view method-timing clinit.jfr
       

    A filter can also name an annotation. This causes all methods bearing the annotation, and all methods in all classes bearing the annotation, to be timed or traced.

        $ jcmd <pid> JFR.start method-timing=@jakarta.ws.rs.GET
        

    It is also possible to use JMX and the JFRs RemoteRecordingStream class to configure timing and tracing over the network.

From all perspectives, the list of the finalized features that made it into JDK-25 is rock solid. But the release also bundles a number of a new experimental and preview APIs, in addition to carried over ones.

Besides JEPs, JDK-25 has plenty of enhancements across the board, including bugfixes and changes in the behavior that may affect the existing applications.

Moving on to the standard library, JDK-25 delivers rather moderate changes, but quite handy nonetheless. Let us take a look at those.

With respect to security, there are a few changes worth mentioning:

Last but not least, few regressions slipped into JDK-25 at the last moment, please be aware of those:

My personal retrospective on the JDK-25 release, among many other things, highlights a significant progress of the Project Leyden and substantial investments into JDK Flight Recorder (JFR) tooling and instrumentation. Let us see what comes next, the lineup for JDK-26 already looks exciting.

I πŸ‡ΊπŸ‡¦ stand πŸ‡ΊπŸ‡¦ with πŸ‡ΊπŸ‡¦ Ukraine.