<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Daniyal Azeemi on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Daniyal Azeemi on Medium]]></description>
        <link>https://medium.com/@muhammaddaniyalazeemi?source=rss-8c2721ecb1a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5E1wbpG647YS3tdS.</url>
            <title>Stories by Muhammad Daniyal Azeemi on Medium</title>
            <link>https://medium.com/@muhammaddaniyalazeemi?source=rss-8c2721ecb1a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:49:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammaddaniyalazeemi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The HTTP QUERY Method Is Finally Here — Here’s How to Use It in Spring Boot Today]]></title>
            <link>https://medium.com/@muhammaddaniyalazeemi/the-http-query-method-is-finally-here-heres-how-to-use-it-in-spring-boot-today-3f25c3e369ed?source=rss-8c2721ecb1a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f25c3e369ed</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Muhammad Daniyal Azeemi]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 07:11:17 GMT</pubDate>
            <atom:updated>2026-08-05T07:11:17.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvGS0qkQAaj1jTjLbcojOQ.png" /></figure><h3>RFC 10008 gives us the verb we’ve been faking with POST /search for fifteen years. The spec is done. The ecosystem isn&#39;t. Here&#39;s the honest state of things — and a working bridge pattern for Spring Boot.</h3><p>Every REST API I have ever built, reviewed, or taught eventually grows a POST /search endpoint. Not because POST is the right method for reading data — it isn&#39;t — but because it was the only practical option. In June 2026, that finally changed. The IETF published <strong>RFC 10008: The HTTP QUERY Method</strong>, the first new general-purpose HTTP verb since PATCH in 2010.</p><p>This article covers what QUERY actually is, why it matters for backend engineers, where the Java and Spring ecosystem stands right now, and how to build a working QUERY endpoint in Spring Boot today — including the pitfall in a code snippet that is currently making the rounds on social media and will crash your application at startup.</p><h3>The Fifteen-Year Compromise</h3><p>When you build an advanced search or filtering endpoint, HTTP has historically given you two bad options.</p><p><strong>Option one: </strong><strong>GET.</strong> Semantically correct — it&#39;s a read, after all. It&#39;s safe, idempotent, and cacheable, which means proxies, CDNs, and clients can all treat it intelligently. But GET puts your parameters in the URL. Nested filter objects become unreadable percent-encoded strings, different proxies enforce different (and uncoordinated) URL length limits, and URLs end up in access logs, browser history, and analytics tools far more readily than request bodies do. Once your filter payload stops fitting comfortably in a query string, GET stops being practical.</p><p><strong>Option two: </strong><strong>POST.</strong> Now you can send a clean, nested JSON payload in the request body. The problem is what you give up: POST is neither safe nor idempotent as far as the protocol is concerned. Nothing in HTTP tells intermediaries that your POST /search is actually a harmless read. Caches won&#39;t cache it. If a connection drops mid-request, neither the client nor any proxy can know whether server state changed, so automatic retries are off the table. You&#39;ve been lying to HTTP, and HTTP has been assuming the worst in response.</p><p>We all made this compromise. It was the correct engineering decision at the time. But it was always a compromise.</p><h3>What RFC 10008 Actually Defines</h3><p>The QUERY method is best described as a hybrid: the payload flexibility of POST combined with the semantic guarantees of GET.</p><p>A QUERY request asks the server to process the enclosed content in a <strong>safe and idempotent</strong> manner and respond with the result. Concretely, that means:</p><p><strong>It has a request body.</strong> Your complex, nested search payload travels in the body, exactly as it would with POST. No URL length limits, no percent-encoding gymnastics, no filter criteria leaking into access logs.</p><p><strong>It is safe and idempotent by contract.</strong> The client is promising it does not expect a state change, and the server is expected to honor that. This is the property that unlocks everything else: a dropped connection can be retried automatically, by any layer of the stack, without fear of duplicate side effects.</p><p><strong>It is cacheable.</strong> Unlike POST in practice, QUERY responses can be cached by intermediaries. There&#39;s an important twist, though: because the query lives in the body, the cache key must incorporate the request content, not just the URL. More on why that matters in the security section.</p><p>One deliberate design decision worth understanding: RFC 10008 does <strong>not</strong> define a query language. The media type of the request content defines how the server interprets it. The same endpoint could accept a JSON filter document, a form-encoded string, or any other format — Content-Type carries the meaning. There&#39;s even a new Accept-Query response header that lets a server advertise which query media types a resource supports.</p><p>A bit of trivia for your next code review: the spec spent its first several years named SEARCH, inherited from a 2015 draft. The working group renamed it in 2021, partly to escape the WebDAV baggage attached to the existing SEARCH, PROPFIND, and REPORT methods. Eleven years from first draft to standard. HTTP does not move fast — which is exactly why it’s worth paying attention when it does.</p><h3>Where the Java Ecosystem Stands (August 2026)</h3><p>This is where most of the content circulating online gets sloppy, so let’s be precise.</p><p><strong>Spring Framework.</strong> There is currently <strong>no native QUERY support</strong> in Spring MVC or WebFlux. The RequestMethod enum contains GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, and TRACE — and nothing else. A community pull request (spring-framework #34993) adding full RFC 10008 support is under active review, and the Spring team has stated they intend to ship it with <strong>Spring Framework 7.1, targeted for November 2026</strong>. There&#39;s even a naming problem to resolve first: the obvious shortcut annotation @QueryMapping is already taken by Spring for GraphQL.</p><p><strong>Servlet containers.</strong> Tomcat has merged QUERY support, but it lands in <strong>Tomcat 12</strong>, because adding a doQuery dispatch path requires changes to the Jakarta Servlet API itself — and the Servlet specification is being updated to accommodate it. Jetty has merged support for its 13.x line, covering method registration, redirection rules, form parameter extraction from the body, and the Accept-Query header.</p><p><strong>What this means in practice:</strong> on today’s stable Spring Boot + Tomcat stack, an incoming QUERY request parses fine at the HTTP layer (the method is just a token in the request line), but it falls through DispatcherServlet into HttpServlet.service(), which doesn&#39;t recognize the method and returns <strong>501 Not Implemented</strong> before your controller code ever runs.</p><h3>The Snippet That Will Crash Your App</h3><p>Before showing the working approach, a warning about a pattern currently spreading on LinkedIn and in blog posts:</p><pre>// DO NOT DO THIS — throws IllegalArgumentException at startup<br>@RequestMapping(value = &quot;/search&quot;, method = RequestMethod.valueOf(&quot;QUERY&quot;))</pre><p>RequestMethod is a plain Java <strong>enum</strong>. Enum.valueOf() only resolves declared constants, and QUERY is not one of them, so this line throws IllegalArgumentException the moment Spring processes the mapping. Your application won&#39;t serve a single request.</p><p>The confusion is understandable, because the client-side equivalent <em>does</em> work: since Spring Framework 6, org.springframework.http.HttpMethod is a <strong>class</strong>, not an enum, and HttpMethod.valueOf(&quot;QUERY&quot;) happily constructs an instance for any token. Same method name, completely different behavior. Server-side mapping and client-side invocation are not symmetric here.</p><h3>Building a Working QUERY Endpoint in Spring Boot Today</h3><p>Until Spring Framework 7.1 ships, you need two small bridges: one to stop the servlet layer from returning 501, and one to route the request to a handler despite the missing enum constant.</p><h3>Step 1: Route QUERY through the DispatcherServlet</h3><p>FrameworkServlet only dispatches methods it recognizes; everything else falls through to HttpServlet, which answers unknown verbs with 501. A minimal subclass fixes that:</p><pre>public class QueryAwareDispatcherServlet extends DispatcherServlet {</pre><pre>    private static final String QUERY = &quot;QUERY&quot;;</pre><pre>    @Override<br>    protected void service(HttpServletRequest request, HttpServletResponse response)<br>            throws ServletException, IOException {<br>        if (QUERY.equals(request.getMethod())) {<br>            processRequest(request, response); // bypass HttpServlet&#39;s 501<br>        } else {<br>            super.service(request, response);<br>        }<br>    }<br>}</pre><p>Register it as the dispatcher servlet bean:</p><pre>@Configuration<br>public class QueryMethodConfig {</pre><pre>    @Bean<br>    public DispatcherServlet dispatcherServlet() {<br>        return new QueryAwareDispatcherServlet();<br>    }<br>}</pre><h3>Step 2: Map the endpoint</h3><p>Since you can’t express QUERY in the method attribute, map by path alone (which matches all methods) and enforce the verb inside the handler:</p><pre>@RestController<br>@RequestMapping(&quot;/api/products&quot;)<br>public class ProductQueryController {</pre><pre>    private final ProductService productService;</pre><pre>    public ProductQueryController(ProductService productService) {<br>        this.productService = productService;<br>    }</pre><pre>    @RequestMapping(&quot;/search&quot;)<br>    public ResponseEntity&lt;List&lt;Product&gt;&gt; searchProducts(<br>            HttpServletRequest request,<br>            @RequestBody ProductSearchRequest criteria) {</pre><pre>        if (!&quot;QUERY&quot;.equals(request.getMethod())) {<br>            return ResponseEntity<br>                    .status(HttpStatus.METHOD_NOT_ALLOWED)<br>                    .header(&quot;Allow&quot;, &quot;QUERY&quot;)<br>                    .build();<br>        }</pre><pre>        List&lt;Product&gt; results = productService.complexSearch(criteria);<br>        return ResponseEntity.ok(results);<br>    }<br>}</pre><p>The 405-with-Allow-header response is not just politeness — it&#39;s the discovery mechanism RFC 10008 itself recommends. A client can attempt a QUERY, and on 405 it learns which methods the resource supports and can fall back to POST.</p><p>The search payload itself is an ordinary DTO:</p><pre>public class ProductSearchRequest {<br>    private String category;<br>    private List&lt;String&gt; brands;<br>    private Double maxPrice;</pre><pre>    // getters, setters, constructors<br>}</pre><p>Be honest with yourself about the limits of this bridge. Because it lives outside Spring’s native method-condition infrastructure, things like duplicate-mapping diagnostics, actuator route visibility, and OpenAPI generation won’t behave identically to a real @GetMapping. It&#39;s a bridge for early adoption and internal APIs, not a permanent architecture.</p><h3>Step 3: Calling it from the client side</h3><p>RestClient handles custom verbs cleanly — provided the underlying HTTP engine allows them:</p><pre>@Component<br>public class ProductSearchClient {</pre><pre>    private final RestClient restClient;</pre><pre>    public ProductSearchClient(RestClient.Builder builder) {<br>        this.restClient = builder<br>                .requestFactory(new JdkClientHttpRequestFactory())<br>                .baseUrl(&quot;http://localhost:8080&quot;)<br>                .build();<br>    }</pre><pre>    public List&lt;Product&gt; executeQuery(ProductSearchRequest criteria) {<br>        return restClient.method(HttpMethod.valueOf(&quot;QUERY&quot;))<br>                .uri(&quot;/api/products/search&quot;)<br>                .body(criteria)<br>                .retrieve()<br>                .body(new ParameterizedTypeReference&lt;List&lt;Product&gt;&gt;() {});<br>    }<br>}</pre><p>The request factory choice matters more than it looks. The JDK HttpClient and Apache HttpComponents both accept arbitrary method tokens. The legacy HttpURLConnection — which backs RestTemplate&#39;s default SimpleClientHttpRequestFactory — validates methods against a hardcoded list and will reject QUERY outright. If you must use RestTemplate, swap in a modern request factory first.</p><h3>The Caveats Nobody Puts in the Headline</h3><p><strong>CORS.</strong> QUERY is not a CORS-safelisted method. Every cross-origin QUERY from browser JavaScript triggers a preflight OPTIONS request, and your CORS configuration must explicitly allow the method. This is the main reason I&#39;d adopt QUERY first for internal APIs, backend-to-backend calls, and controlled clients — and keep a POST fallback for public browser-facing APIs until support becomes boring and widespread.</p><p><strong>Infrastructure allowlists.</strong> WAFs, API gateways, reverse proxies, and CDN configurations written before June 2026 almost certainly enumerate methods explicitly — usually GET, POST, PUT, DELETE, PATCH. Some will reject QUERY; more dangerously, some may forward it while <em>skipping body inspection rules written only for POST</em>. Security teams are already treating this as a live review item: if your WAF blocks a malicious payload over POST but passes the identical payload over QUERY, you have an inspection gap, not a feature.</p><p><strong>Caching is powerful and sharp-edged.</strong> Cacheability is one of QUERY’s headline benefits, but the cache key must include the request body — a byte-for-byte hash is the safe approach. Any cache that keys only on the URL, or that tries to be clever by normalizing or decoding the body before hashing, opens the door to cache poisoning and cache deception. Enable caching for QUERY responses deliberately, not by default.</p><h3>Should You Adopt It?</h3><p>My take, as someone who teaches Spring Boot to working engineers: <strong>start now, but start small.</strong></p><p>The spec is solid and finalized. The semantics are exactly what we’ve wanted for a decade. Server and framework support is converging fast — Spring Framework 7.1 in November, Tomcat 12, Jetty 13, OpenAPI 3.2 already able to document it. The bridge pattern above is genuinely small, and the 405-fallback pattern means clients can adopt QUERY without breaking against servers that don’t support it yet.</p><p>Good first candidates: internal search endpoints, dashboard and reporting APIs, service-to-service query traffic. Poor first candidates: public browser-facing APIs behind third-party CDNs and WAFs you don’t control.</p><p>POST /search served us well. But it was always a workaround wearing a method&#39;s clothes. Within a few years, I suspect it will read the way X- headers do today — a legacy idiom from before the protocol caught up with what we were actually doing.</p><p>The method finally matches the meaning.</p><p><em>Have you started experimenting with QUERY, or are you waiting for native Spring 7.1 support? I’d love to hear how your infrastructure handled it — drop a comment.</em></p><p><strong>References:</strong></p><ul><li>RFC 10008 — The HTTP QUERY Method (IETF, June 2026)</li><li>RFC 9110 — HTTP Semantics</li><li>Spring Framework PR #34993 (QUERY method support)</li><li>Apache Tomcat PR #1026 / Jakarta Servlet issue #1068</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f25c3e369ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java’s Project Panama — The revolution software world needs.]]></title>
            <link>https://medium.com/@muhammaddaniyalazeemi/javas-project-panama-the-revolution-software-world-needs-782608cd1d02?source=rss-8c2721ecb1a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/782608cd1d02</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[project-panama]]></category>
            <category><![CDATA[openjdk]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Muhammad Daniyal Azeemi]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 08:02:49 GMT</pubDate>
            <atom:updated>2025-09-25T08:02:49.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java’s Project Panama — The revolution software world needs.</h3><h3>What is Project Panama?</h3><p>Project Panama is an OpenJDK initiative whose goal is to <strong>improve and simplify interoperation</strong> between the Java Virtual Machine (JVM) and “foreign” (non-Java) code, such as native libraries written in C, C++, or other languages that can expose a C-like ABI (Application Binary Interface; It’s like the <em>low-level contract</em> between two pieces of compiled code — for example, between your program and the operating system, or between two libraries.).</p><p>In short: Panama aims to make calling native functions, accessing native memory, and integrating with native libraries safer, more efficient, and easier (less boilerplate) compared to the traditional Java Native Interface (JNI) approach.</p><p>Project Panama is not just a single API — it’s an umbrella project composed of multiple components and enhancements that are being incubated or developed for inclusion in the JDK.</p><p>Some of the key components include:</p><ul><li><strong>Foreign Function &amp; Memory API</strong> (for calling functions and handling memory outside the JVM)</li><li><strong>Vector API</strong> (for expressing data-parallel operations)</li><li><strong>JExtract</strong> (a tool to generate Java bindings from native headers)</li><li>Support for native library management, metadata, runtime hooks, and improvements in class/method resolution or JIT optimizations in relation to native interop</li></ul><p>Because addition of these features directly into the core JDK is risky (stability, backward‐compatibility, etc.), Panama evolves via incubator and preview phases before being merged into the JDK proper. Phew! 😌</p><h3>Why is Panama needed? (Motivations &amp; Problems with JNI)</h3><p>Before Panama, the standard way for Java code to call native functions was via <strong>JNI</strong> (Java Native Interface). JNI works, but has several shortcomings:</p><ul><li>It requires writing “glue” code (native C/C++ code) to wrap native library functions, mapping Java types to native types and back.</li><li>It tends to be verbose, boilerplate-heavy, error-prone (memory leaks, pointer mistakes, unsafe conversions).</li><li>Performance overhead: crossing the boundary between Java and native often incurs cost (boxing/unboxing, checks, marshaling).</li><li>Difficulty in maintaining and evolving over time as native APIs change.</li></ul><p>Panama’s goals are:</p><ol><li><strong>Less boilerplate / wrapper code</strong> — instead of writing C glue code, ideally Java code can directly call native functions.</li><li><strong>More safety</strong> — reduce chances of memory corruption, pointer misuse, leaks.</li><li><strong>Better performance</strong> — amortize the cost of native calls, allow more optimized bridging between Java and native.</li><li><strong>Expressiveness</strong> — lets Java represent native memory layouts, structs, arrays, pointers, etc.</li><li><strong>Easier integration</strong> — making it more straightforward to interoperate with existing native libraries (C, C++, Rust, etc.) by way of the C ABI as a common “glue” interface.</li></ol><p>Thus Panama is a more modern interop layer compared to JNI, built with knowledge of current JVM internals, modern Java APIs (VarHandle, MethodHandle, etc.).</p><h3>Core Concepts &amp; APIs in Panama</h3><p>These are the main building blocks that Panama introduces (or evolves). Let us go through them, explain what they do, and show how they tie together.</p><pre>| Concept / API                                  | Role / Purpose                                                                 | Key Classes / Interfaces                                                                                                                          | Notes &amp; Examples                                                                                                                                                                                                       |<br>|-----------------------------------------------|-------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|<br>| **Memory / MemorySegment / Memory Layout**     | Represent and manage memory outside the Java heap (“foreign” memory)           | `MemorySegment`, `MemoryAddress`, `MemoryLayout`, `ValueLayout`, `StructLayout`, `SequenceLayout`, `Arena` (or `ResourceScope` / `MemorySession`) | You can allocate and free memory explicitly (off-heap), or map native memory, manipulate it in a structured way (e.g. modeling C structs). [Project Panama for Newbies (Part 1)](https://foojay.io/today/project-panama-for-newbies-part-1/?utm_source=chatgpt.com) |<br>| **Linker / FunctionDescriptor / SymbolLookup** | Bridge between Java and native functions; lookup native symbols, perform calls | `Linker`, `FunctionDescriptor`, `SymbolLookup`, `MethodHandle`                                                                                    | You describe a native function’s signature and lookup its symbol address, then you “downcall” from Java to native (or “upcall” native to Java). [Project Panama for Newbies (Part 1)](https://foojay.io/today/project-panama-for-newbies-part-1/?utm_source=chatgpt.com) |<br>| **JExtract**                                   | Tool to auto-generate Java bindings (stubs) from native headers                | `jextract` command-line tool                                                                                                                      | Instead of manually writing Java wrappers for existing C headers, `jextract` can parse header files (e.g. `.h`) and produce Java binding code (interfaces, method signatures) that use the Panama APIs. [OpenJDK](https://openjdk.org/projects/panama/?utm_source=chatgpt.com) |<br>| **Vector API**                                 | Expressing vectorized, SIMD operations in Java                                 | Classes under e.g. `jdk.incubator.vector`                                                                                                         | Though not strictly part of the “native interop” side, this component is often handled within the Panama umbrella to give Java better access to hardware-accelerated operations. [OpenJDK](https://openjdk.org/projects/panama/?utm_source=chatgpt.com) |</pre><p>Let me walk you through the workflow (how things tie together) with a simple “Hello, native” example.</p><h3>Memory &amp; Layouts</h3><p>Suppose you want to allocate a chunk of native memory (off the Java heap), store and retrieve values, or represent C data structures.</p><ul><li><strong>MemorySegment / MemoryAddress</strong>: A MemorySegment is a contiguous region of memory, possibly off-heap. It abstracts over an address and size. A MemoryAddress is more like a pointer / offset into a segment.</li><li><strong>Arena / MemorySession / ResourceScope</strong>: These abstractions manage the lifecycle of memory — tracking when segments should be freed or closed. You typically work inside a try-with-resources block (or scope) so memory is released automatically.</li><li><strong>MemoryLayout, ValueLayout, StructLayout, SequenceLayout</strong>: To model structured memory (e.g. a C struct, or arrays), Panama provides layout abstractions. You define which fields, padding, alignment, sequences, unions, etc., then use VarHandles or path abstractions to load or store individual fields.</li><li><strong>VarHandle</strong>: For accessing memory fields (get/set) using the layout, similar to how VarHandles are used for fields in regular Java.</li></ul><p>This allows you to do things like:</p><pre>try (Arena arena = Arena.ofConfined()) {<br>    MemorySegment seg = arena.allocate(16);  <br>    seg.set(ValueLayout.JAVA_INT, 0, 42);<br>    int x = seg.get(ValueLayout.JAVA_INT, 0);<br>    // Use x …<br>}</pre><p>And for a struct-like layout:</p><pre>StructLayout layout = MemoryLayout.struct(<br>    ValueLayout.JAVA_INT.withName(&quot;a&quot;),<br>    ValueLayout.JAVA_DOUBLE.withName(&quot;b&quot;)<br>);<br>VarHandle aHandle = layout.varHandle(<br>    MemoryLayout.PathElement.groupElement(&quot;a&quot;)<br>);<br>VarHandle bHandle = layout.varHandle(<br>    MemoryLayout.PathElement.groupElement(&quot;b&quot;)<br>);<br><br>try (Arena arena = Arena.ofConfined()) {<br>    MemorySegment seg = arena.allocate(layout);<br>    aHandle.set(seg, 0, 100);<br>    bHandle.set(seg, 0, 123.45);<br>    int a = (int) aHandle.get(seg, 0);<br>    double b = (double) bHandle.get(seg, 0);<br>}</pre><p>This way, you can mirror the layout of a C struct and safely access fields.</p><h3>Symbol Lookup &amp; Foreign Function Calls</h3><p>Once you’ve got memory models, you often want to <strong>call native functions</strong> (downcalls) or receive callbacks from native into Java (upcalls). Panama gives you APIs for that:</p><ol><li><strong>Symbol Lookup</strong><br>You need to locate the address of a native function or global variable in a native library. Panama provides SymbolLookup abstraction, with variants such as:<br>- Linker.nativeLinker().defaultLookup() — default system lookup (e.g. standard C library)<br>- SymbolLookup.loaderLookup() — for libraries loaded via System.loadLibrary(...) <br>- SymbolLookup.libraryLookup(Path, Arena) — explicitly open a dynamic library (like dlopen) and look up symbols.<br>- Then lookup(&quot;funcName&quot;) returns a MemorySegment representing the function’s address (typically zero-length segment; you don’t know its “size” as a function).</li><li><strong>Describing Function Signatures</strong><br> Since the symbol’s address alone tells you nothing about the parameter types and return type, you need a <strong>FunctionDescriptor</strong> to describe the signature (parameter types, return type) using ValueLayout and address layouts.</li><li><strong>Downcall / Upcall via Linker</strong><br> Once you have a symbol address and a descriptor, the Linker can produce a MethodHandle that, when invoked, will execute the native function as if it were a Java method. That is a <strong>downcall</strong> (Java calling native).<br>For <strong>upcalls</strong> (native code invoking Java code via a function pointer), Panama supports callbacks: you can get a function pointer to a Java method and pass it to native code, enabling native to call back. Panama handles the glue/adapter automatically.</li><li><strong>Invocation</strong><br> The MethodHandle behaves similarly to other MethodHandles: you use invokeExact(...) or invoke(...) to call the native function. You pass parameters (converted appropriately) and get return values.<br> Internally, the Linker bridges calling conventions (ABI), marshals arguments and return value, handles platform differences, etc.</li></ol><p>For example, calling printf from Java (a canonical “Hello, native” example) looks roughly like:</p><pre>Linker linker = Linker.nativeLinker();<br>SymbolLookup symbolLookup = ...;  // e.g. loaderLookup or default<br>MemorySegment printfAddr = symbolLookup.lookup(&quot;printf&quot;).orElseThrow();<br>FunctionDescriptor fd = FunctionDescriptor.of(<br>    ValueLayout.JAVA_INT,  // return type (int)<br>    ValueLayout.ADDRESS    // first argument: pointer to C string<br>    // possibly more args ...<br>);<br>MethodHandle mh = linker.downcallHandle(printfAddr, fd);<br>MemorySegment cStr = arena.allocateUtf8String(&quot;Hello, Panama!\n&quot;);<br>mh.invokeExact(cStr.address());</pre><p>That’s the high-level view. Many details (varargs, pointers, conversions, memory ownership) need care.</p><h3>Lifecycle, Safety, and Ownership</h3><p>One of the tricky parts when mixing Java and native memory is <strong>memory safety</strong> and <strong>ownership / lifetime</strong>:</p><ul><li>Panama enforces that MemorySegments are tied to scopes (arenas / sessions) so that once a scope is closed, you cannot use those segments. This helps prevent use-after-free.SymbolLookup.libraryLookup(Path, Arena) — explicitly open a dynamic library (like dlopen) and look up symbols.</li><li>There are checks (bounds, alignment) to prevent illegal memory access (e.g. out-of-bounds) when using the higher-level API.</li><li>For “unsafe” memory (e.g. pointers returned from native code without bounds), you may need to <strong>reinterpret</strong> them with a known size, or coerce them into a MemorySegment with bounds you control.</li><li>Some memory segments may not be “attached” to a life‐cycle control (i.e. raw pointers), so you must be careful not to access them after the underlying memory is invalid.</li><li>The API is careful to prevent misuse across threads or scopes (depending on whether segments are “confined” or “shared”)</li></ul><p>Because Panama must maintain JVM safety, it cannot allow arbitrary native memory misuse to crash the VM — many safety checks and constraints exist to mitigate that.</p><h3>JExtract: Bridging Native Headers to Java Stubs</h3><p>Writing all the native-to-Java binding code by hand is tedious and error-prone. That’s where <strong>JExtract</strong> comes in.</p><ul><li>jextract is a tool that takes C header files (.h) and corresponding native libraries, then <em>automatically</em> generates Java binding code (interfaces, classes, methods) using the Panama APIs.</li><li>The generated binding code handles symbol lookups, function descriptors, memory layouts, and other boilerplate so developers can more easily call native APIs from Java.</li><li>JExtract helps reduce mismatch errors, type mismatch, and manual repetition.</li></ul><p>Thus, instead of manually writing:</p><ul><li>Symbol lookups</li><li>Linker bindings</li><li>Layouts for C structs</li><li>Conversion from Java strings to C strings</li><li>Exception handling, etc.,</li></ul><p>You can rely on generated Java bindings that are consistent and updated when the native API changes.</p><h3>Current Status, Preview, and Limitations</h3><p>Project Panama is still evolving. Many parts are in <strong>preview</strong> or <strong>incubator</strong> status; API shapes may change. For instance, as of JDK 21, the Foreign Function &amp; Memory API is provided in preview.</p><p>Some cautions and caveats:</p><ul><li>Because it is preview/incubating, you must enable preview features (e.g. --enable-preview) when compiling / running code that uses the new APIs.</li><li>API changes or deprecations may occur as Panama matures (e.g. method names, argument ordering, class names).</li><li>Complexity remains: working with pointers, memory, alignment, lifetime is inherently trickier than pure Java programming.</li><li>Panama’s support is primarily via the <strong>C ABI</strong> (i.e. you can only interoperate with functions that abide by a C calling convention). For libraries in C++ (with name mangling) or other languages, you often need extern &quot;C&quot; or bridging to C ABI.</li><li>Varargs support, complex data types, variadic functions, complex calling conventions, or edge platform-specific details may still require careful handling or special bridging.</li><li>Safety and performance tradeoffs exist — for example, sometimes runtime checks are involved.</li></ul><p>Nevertheless, Panama is already usable for many practical interop tasks and is gradually being stabilized.</p><h3>Why Panama Matters — Use Cases &amp; Benefits</h3><p>Here are some of the key benefits and scenarios where Panama is especially helpful:</p><ul><li><strong>Calling high-performance native libraries</strong><br> E.g. image processing (OpenCV), numerical/linear algebra libraries (BLAS, LAPACK), physics or simulation engines, etc. Rather than reimplementing in Java, you can call existing well-optimized native code.</li><li><strong>Systems / OS-level integration</strong><br> Accessing low-level OS APIs, device drivers, specialized hardware, or system libraries directly from Java.</li><li><strong>Bridging with languages like C++ / Rust / Swift / etc.</strong><br> Many languages can expose a C-style API, so Java can interoperate via Panama with them (indirectly). Articles show integrating with C++, Swift, Rust, Python (via C API), etc.</li><li><strong>Efficient memory manipulation / off-heap data structures</strong><br> For large data sets, direct memory access, zero-copy data pipelines, etc.</li><li><strong>Vector / SIMD processing</strong><br> Via the Vector API component, letting Java efficiently express data-parallel code that maps to SIMD hardware.</li><li><strong>Reducing the JNI burden</strong><br> Less glue code, fewer native modules to maintain, better safety and maintainability.</li><li><strong>Better performance / lower overhead</strong><br> Because the interop is more tightly integrated and optimized, native calls via Panama can be faster and more inlineable than JNI paths in many cases.</li></ul><h3>Challenges &amp; Open Problems</h3><p>Even with its advantages, Panama still must confront challenges:</p><ul><li><strong>Portability &amp; ABI variation</strong><br> Different platforms (x86_64, ARM, Windows vs Linux vs macOS) have different ABIs (calling conventions, data alignment, padding). The linker must handle this complexity.</li><li><strong>Evolving APIs</strong><br> Because Panama is in flux, early adopters must be prepared for API changes, backward incompatibilities, etc.</li><li><strong>Safety vs Performance tradeoff</strong><br> Some checks (bounds, alignment) add overhead. Balancing safety and raw performance is tricky.</li><li><strong>Complex native patterns</strong><br> Legacy C APIs, variadic functions, setjmp/longjmp, C++ overloading and templates, union types — not always trivial to map well in Java.</li><li><strong>Garbage collection / pinned memory</strong><br> Sometimes native code expects memory not to move (pinned). JVM’s garbage collector might move memory unless it’s off-heap. Ensuring safe interaction with GC might require special handling.</li><li><strong>Debugging &amp; tooling</strong><br> Debugging native interop issues, memory corruption, or mismatch errors is always harder than pure Java. Tools need to mature to help diagnose cross-language issues.</li><li><strong>Adoption &amp; ecosystem shift</strong><br> Since many libraries currently use JNI or other bridging (JNA, JavaCPP), migrating to Panama or providing bindings will take effort.</li></ul><h3>Roadmap &amp; Future Prospects</h3><p>Panama is being merged into the JDK in stages. As of recent statements:</p><ul><li>Foreign Function &amp; Memory API is in preview in modern JDKs.</li><li>Vector API is also evolving and maturing.</li><li>JExtract is being developed in parallel to the JDK lifecycle.</li><li>Over time, when stability is achieved, the APIs will be finalized and no longer require preview mode.</li><li>Further enhancements might include better support for other foreign ABIs (beyond just C), more tooling, performance optimizations, and deeper JVM integration (e.g. JIT support, escape analysis, etc.).</li></ul><p>OpenJDK’s page describes Panama’s components and that the project is incubating these modules for eventual inclusion. <a href="https://openjdk.org/projects/panama">projectPanama( );</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=782608cd1d02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>