Recent Posts
Archives

Posts Tagged ‘ForeignFunctionAPI’

PostHeaderIcon [DevoxxPL2022] Bare Metal Java • Jarosław Pałka

Jarosław Pałka, a staff engineer at Neo4j, captivated the audience at Devoxx Poland 2022 with an in-depth exploration of low-level Java programming through the Foreign Function and Memory API. As a veteran of the JVM ecosystem, Jarosław shared his expertise in leveraging these experimental APIs to interact directly with native memory and C code, offering a glimpse into Java’s potential for high-performance, system-level programming. His presentation, blending technical depth with engaging demos, provided a roadmap for developers seeking to harness Java’s evolving capabilities.

The Need for Low-Level Access in Java

Jarosław began by contextualizing the necessity of low-level APIs in Java, a language traditionally celebrated for its managed runtime and safety guarantees. He outlined the trade-offs between safety and performance, noting that managed runtimes abstract complexities like memory management but limit optimization opportunities. In high-performance systems like Neo4j, Kafka, or Elasticsearch, direct memory access is critical to avoid garbage collection overhead. Jarosław introduced the Foreign Function and Memory API, incubated since Java 14 and stabilized in Java 17, as a safer alternative to the sun.misc.Unsafe API, enabling developers to work with native memory while preserving Java’s safety principles.

Mastering Native Memory with Memory Segments

Delving into the API’s mechanics, Jarosław explained the concept of memory segments, which serve as pointers to native memory. These segments, managed through resource scopes, allow developers to allocate and deallocate memory explicitly, with safety mechanisms to prevent unauthorized access across threads. He demonstrated how memory segments support operations like setting and retrieving primitive values, using var handles for type-safe access. Jarosław emphasized the API’s flexibility, enabling seamless interaction with both heap and off-heap memory, and its potential to unify access to diverse memory types, including memory-mapped files and persistent memory.

Bridging Java and C with Foreign Functions

A highlight of Jarosław’s talk was the Foreign Function API, which simplifies calling C functions from Java and vice versa. He showcased a practical example of invoking the getpid C function to retrieve a process ID, illustrating the use of symbol lookups, function descriptors, and method handles to map C types to Java. Jarosław also explored upcalls, allowing C code to invoke Java methods, using a signal handler as a case study. This bidirectional integration eliminates the complexities of Java Native Interface (JNI), streamlining interactions with native libraries like SDL for game development.

Practical Applications: A Java Game Demo

To illustrate the API’s power, Jarosław presented a live demo of a 2D game built using Java and the SDL library. By mapping C structures to Java memory layouts, he created sprites and handled events like keyboard inputs, demonstrating how Java can interface with hardware for real-time rendering. The demo highlighted the challenges of manual structure mapping and memory management, but also showcased the API’s potential to simplify these tasks. Jarosław noted that Java 19’s jextract tool automates this process by generating Java bindings from C header files, significantly reducing boilerplate.

Safety and Performance Considerations

Jarosław underscored the API’s safety features, such as temporal and spatial bounds checking, which prevent invalid memory access. He also discussed the cleaner mechanism, which integrates with Java’s garbage collector to manage native memory deallocation. While the API introduces overhead comparable to JNI, Jarosław highlighted its potential for optimization in future releases, particularly for serverless applications and caching. He cautioned developers to use these APIs judiciously, given their complexity and the need for careful error handling.

Future Prospects and Java’s Evolution

Looking ahead, Jarosław positioned the Foreign Function and Memory API as a transformative step in Java’s evolution, enabling developers to write high-performance applications traditionally reserved for languages like C or Rust. He encouraged exploration of these APIs for niche use cases like database development or game engines, while acknowledging their experimental nature. Jarosław’s vision of Java as a versatile platform for both high-level and low-level programming resonated, urging developers to embrace these tools to push the boundaries of what Java can achieve.

Links:

PostHeaderIcon [DevoxxPL2022] Java 17 & 18: What’s New and Noteworthy • Piotr Przybył

Piotr Przybył, a seasoned software gardener at AtomicJar, captivated the audience at Devoxx Poland 2022 with a comprehensive deep dive into the new features and enhancements introduced in Java 17 and 18. His presentation, rich with technical insights and practical demonstrations, explored key updates that empower developers to write more robust, maintainable, and efficient code. Piotr’s engaging style, peppered with humor and real-world examples, provided a clear roadmap for leveraging these advancements in modern Java development.

Sealed Classes for Controlled Inheritance

One of the standout features of Java 17 is sealed classes, introduced as JEP 409. Piotr explained how sealed classes allow developers to restrict which classes or interfaces can extend or implement a given type, offering fine-grained control over inheritance. This is particularly useful for library maintainers who want to prevent unintended code reuse while allowing specific extensions. By using the sealed keyword and a permits clause, developers can define a closed set of subclasses, with options to mark them as final, sealed, or non-sealed. Piotr’s demo illustrated this with a library type hierarchy, showing how sealed classes enhance code maintainability and prevent misuse through inheritance.

Enhanced Encapsulation and UTF-8 by Default

Java 17’s JEP 403 strengthens encapsulation by removing illegal reflective access, a change Piotr humorously likened to “closing the gates to reflection demons.” Previously, developers could bypass encapsulation using setAccessible(true), but Java 17 enforces stricter access controls, requiring code fixes or the use of --add-opens flags for legacy systems. Additionally, Java 18’s JEP 400 sets UTF-8 as the default charset for I/O operations, resolving discrepancies across platforms. Piotr demonstrated how to handle encoding issues, advising developers to explicitly specify charsets to ensure compatibility, especially for Windows users.

Deprecating Finalization and Introducing Simple Web Server

Java 18’s JEP 421 marks the deprecation of the finalize method for removal, signaling the end of a problematic mechanism for resource cleanup. Piotr’s demo highlighted the non-deterministic nature of finalization, advocating for try-with-resources as a modern alternative. He also showcased Java 18’s simple web server (JEP 408), a lightweight tool for serving static files during development or testing. Through a programmatic example, Piotr demonstrated how to start a server on port 9000 and dynamically modify CSS files, emphasizing its utility for quick prototyping.

Pattern Matching for Switch and Foreign Function API

Piotr explored Java 18’s pattern matching for switch (JEP 420), a preview feature that enhances switch statements and expressions. This feature supports null handling, guarded patterns, and type-based switching, eliminating the need for cumbersome if-else checks. His demo showed how to switch over objects, handle null cases, and use guards to refine conditions, making code more concise and readable. Additionally, Piotr introduced the Foreign Function and Memory API (JEP 419), an incubator module for safe, efficient interoperation with native code. He demonstrated allocating off-heap memory and calling C functions, highlighting the API’s thread-safety and scope-bound memory management.

Random Generators and Deserialization Filters

Java 17’s JEP 356 introduces enhanced pseudo-random number generators, offering a unified interface for various random number implementations. Piotr’s demo showcased switching between generators like Random, SecureRandom, and ThreadLocalRandom, simplifying random number generation for diverse use cases. Java 17 also improves deserialization filters (JEP 415), allowing per-stream customization to enhance security against malicious data. These updates, combined with other enhancements like macOS Metal rendering and larger G1 heap regions, underscore Java’s commitment to performance and security.

Links: