Recent Posts
Archives

Posts Tagged ‘Java’

PostHeaderIcon [SpringIO2022] JobRunr: Simplifying Distributed Job Scheduling with Spring

At Spring I/O 2022 in Barcelona, Ronald Dehuysser introduced JobRunr, an open-source Java library designed to streamline distributed background job processing. His engaging session, blending practical insights with live coding, showcased how JobRunr empowers developers to transform Java 8 lambdas into scalable, fault-tolerant jobs without complex infrastructure. Tailored for businesses handling moderate data volumes, Ronald’s talk highlighted JobRunr’s seamless integration with Spring and its potential to revolutionize job scheduling.

The Genesis of JobRunr: Solving Real-World Challenges

Ronald, a contractor from Belgium, kicked off by sharing the origins of JobRunr, born from a challenging “greenfield” fintech project. Tasked with building an invoicing platform on Google Cloud, he encountered a microservice architecture plagued by issues: no retry mechanisms, poor monitoring, and lost invoices due to untracked failures. The project’s eight microservices led to code duplication, prompting Ronald to question the microservice hype and advocate for simpler, modular monoliths. Frustrated by the lack of developer-friendly, open-source job scheduling tools, he created JobRunr to address these gaps, emphasizing ease of use, existing infrastructure, and automatic retries.

JobRunr’s philosophy is rooted in simplicity and practicality. Unlike solutions requiring heavy infrastructure like Apache Kafka or vendor-specific cloud services, JobRunr leverages SQL or NoSQL databases for persistence, making it embeddable with a single JAR. Ronald stressed that most businesses don’t need to process terabytes daily like tech giants. Instead, JobRunr targets complex business processes with gigabytes of data, offering a plug-and-play solution with built-in monitoring and fault tolerance.

Core Features: From Lambdas to Distributed Jobs

The heart of JobRunr lies in its ability to convert Java 8 lambdas into distributed background jobs. Ronald demonstrated this with a Spring service example, where a static BackgroundJob.enqueue method schedules jobs without altering existing code. Jobs are serialized as JSON, stored in a database, and processed by BackgroundJobServer instances across JVMs, enabling horizontal scaling in Kubernetes. A dashboard provides real-time insights into job status, with automatic retries (up to 10 by default) using an exponential backoff policy to handle failures gracefully.

For scheduling flexibility, JobRunr supports immediate, delayed, or recurring jobs. Ronald showcased the schedule API for jobs running after a delay (e.g., 24 hours) and the scheduleRecurrently method for daily tasks, using a readable Cron class to simplify cron expressions. The dashboard allows manual triggering of recurring jobs for testing, enhancing developer control. To prevent duplicate processing, JobRunr offers mutex support, though advanced features like this are part of the paid Pro version, balancing open-source accessibility with sustainability.

Under the Hood: Bytecode Magic and Spring Native

Delving into JobRunr’s internals, Ronald revealed its use of ASM for bytecode manipulation, translating lambdas into executable jobs. While some criticized this as “black magic,” he countered with assurances of binary compatibility, backed by Oracle’s Java Language Specification and his participation in Oracle’s Quality Outreach Program. JobRunr’s compatibility spans Java 8 to 17, tested across JVMs using Testcontainers, ensuring robustness. The introduction of JobRequest and JobRequestHandler in version 4 further simplifies job definition, aligning with the command handler pattern for explicit job processing.

A highlight was JobRunr’s integration with Spring Native, enabling compilation to GraalVM native images for millisecond startup times and low memory usage. Ronald collaborated with the Spring team to ensure reflection compatibility, making JobRunr a natural fit for cloud-native deployments. The live coding demo, despite minor hiccups, showcased JobRunr’s ease of use: Ronald built an uptime monitoring service, scheduling recurring website checks with a few lines of code, monitored via the dashboard. This practicality resonated with attendees, who appreciated JobRunr’s developer-friendly approach.

Impact and Future: Empowering Developers

JobRunr’s adoption spans medical image processing, web crawling, and document generation, with 30,000 monthly Maven downloads. Ronald shared a compelling anecdote: a company reported a 20% developer productivity boost by using the dashboard’s requeue feature for first-line support, reducing interruptions. Looking ahead, JobRunr aims to enhance GraalVM support, add OpenID Connect for dashboard authentication, and incorporate community-driven features. The Pro version funds development, with 5% of profits supporting environmental causes like tree planting.

Ronald’s session underscored JobRunr’s mission to simplify distributed job scheduling, making it an invaluable tool for Spring developers tackling real-world business challenges with minimal overhead.

Links:

PostHeaderIcon A Decade of Devoxx FR and Java Evolution: A Detailed Retrospective and Forward-Looking Analysis


Introduction:

The Devoxx FR conference has served as a key barometer of the Java platform’s dynamic evolution over the past ten years. This period has been marked by numerous releases, including major advancements that have significantly reshaped how we architect, develop, and deploy Java applications. This presentation offers a detailed retrospective analysis of significant announcements and the substantial changes within Java, emphasizing the critical importance of embracing these enhancements to optimize our applications for performance, maintainability, and security. Beyond a surface-level examination of syntax and API modifications, this session provides a comprehensive rationale for migrating to newer Java versions, addressing the common concerns and challenges that often accompany such transitions with practical insights and actionable strategies.

1. A Detailed Look Back: Java’s Evolution Over the Past Decade

Jean-Michel “JM” Doudoux begins the session by establishing a parallel timeline of the ten-year history of the Devoxx FR conference and Java’s continuous development. He emphasizes the importance of understanding the reception and adoption rates of different Java versions to contextualize the current state of the Java ecosystem.

Java 8:

JM highlights Java 8 as a watershed release, noting its widespread adoption and the introduction of transformative features that fundamentally changed Java development. Key features include:

  • Lambda Expressions: Revolutionized functional programming in Java, enabling more concise and expressive code.
  • Stream API: Introduced a powerful and efficient way to process collections of data.
  • Method References: Simplified the syntax for referring to methods, further enhancing code readability.
  • New Date/Time API (java.time): Addressed the shortcomings of the old java.util.Date and java.util.Calendar APIs, providing a more robust and intuitive way to handle date and time.
  • Default Methods in Interfaces: Allowed adding new methods to interfaces without breaking backward compatibility.

Java 11:

JM points out the slower adoption rate of Java 11, despite being a Long-Term Support (LTS) release, which typically encourages enterprise adoption due to extended support guarantees. Notable features include:

  • HTTP Client API: Introduced a new and improved HTTP Client API, supporting HTTP/2 and WebSocket.

Java 17:

Characterized as a release that has garnered significant developer enthusiasm, building upon the foundation laid by previous versions and further refining the language.

Java 9:

Acknowledged as a disruptive release, primarily due to the introduction of the Java Platform Module System (JPMS), which brought modularity to Java. Doudoux discusses the profound impact of modularity on the Java ecosystem, affecting code organization, accessibility, and deployment.

Java 10, 12-16:

These releases are characterized as more transient, feature releases, with less widespread adoption compared to the LTS versions. However, they introduced valuable features such as:

  • Local Variable Type Inference (var): Simplified variable declaration.
  • Enhanced Switch Expressions: Improved the switch statement, making it more expressive and usable as an expression.

2. Navigating Migration: Java 17 and Strategic Considerations

The presentation transitions to a practical discussion on the complexities of migrating to newer Java versions, with a strong emphasis on the benefits and challenges of migrating to Java 17. Doudoux addresses the common obstacles developers encounter when advocating for migration within their organizations, particularly the challenge of securing buy-in from operations teams and management.

Strategies for Persuasion:

The speaker offers valuable strategies to help developers build a compelling case for migration, focusing on:

  • Highlighting Performance Improvements: Emphasizing the performance gains offered by newer Java versions.
  • Improved Security: Stressing the importance of security updates and enhancements.
  • Increased Developer Productivity: Showcasing how new language features can streamline development workflows.
  • Long-Term Maintainability: Arguing that staying on older versions increases technical debt and maintenance costs in the long run.

Migration Considerations:

While a detailed, step-by-step migration guide is beyond the scope of the session, Doudoux outlines the essential high-level considerations and key steps involved in the migration process, such as:

  • Dependency Analysis: Assessing compatibility with updated libraries and frameworks.
  • Testing: Thoroughly testing the application after migration.
  • Gradual Rollouts: Considering phased deployments to minimize risk.

3. The Future of Java: Trends and Directions

The session concludes with a concise yet insightful look at the future trajectory of the Java platform. This segment provides a glimpse into upcoming features, emerging trends, and the ongoing evolution of Java, ensuring the audience is aware of the continuous innovation within the Java ecosystem.

Summary:

This presentation provides a detailed and comprehensive overview of Java’s journey over the past decade, carefully contextualized within the parallel evolution of the Devoxx FR conference. It goes beyond a simple recitation of features, offering in-depth analysis of the impact of key advancements, practical guidance on navigating the complexities of Java migration, and a valuable perspective on the future of the platform.

PostHeaderIcon [DevoxxFR 2022] Exploiter facilement des fonctions natives avec le Projet Panama depuis Java

Lors de Devoxx France 2022, Brice Dutheil a présenté une conférence de 28 minutes sur le Projet Panama, une initiative visant à simplifier l’appel de fonctions natives depuis Java sans les complexités de JNI ou de bibliothèques tierces. Brice, contributeur actif à l’écosystème Java, a introduit l’API Foreign Function & Memory (JEP-419), montrant comment elle relie le monde géré de Java au code natif en C, Swift ou Rust. À travers des démonstrations de codage en direct, Brice a illustré le potentiel de Panama pour des intégrations natives fluides. Suivez Brice sur Twitter à twitter.com/Brice_Dutheil pour plus d’insights Java.

Simplifier l’intégration de code natif

Brice a débuté en expliquant la mission du Projet Panama : connecter l’environnement géré de Java, avec son garbage collector, au monde natif de C, Swift ou Rust, plus proche de la machine. Traditionnellement, JNI imposait des étapes laborieuses : écrire des classes wrapper, charger des bibliothèques et générer des headers lors des builds. Ces processus étaient sujets aux erreurs et chronophages. Des alternatives comme JNA et JNR amélioraient l’expérience développeur en générant des bindings au runtime, mais elles étaient plus lentes et moins sécurisées.

Lancé en 2014, le Projet Panama répond à ces défis avec trois composantes : les API vectorielles (non couvertes ici), les appels de fonctions étrangères et la gestion de la mémoire. Brice s’est concentré sur l’API Foreign Function & Memory (JEP-419), disponible en incubation dans JDK 18. Contrairement à JNI, Panama élimine les complexités du build et offre des performances proches du natif sur toutes les plateformes. Il introduit un modèle de sécurité robuste, limitant les opérations dangereuses et envisageant de restreindre JNI dans les futures versions de Java (par exemple, Java 25 pourrait exiger un flag pour activer JNI). Brice a souligné l’utilisation des method handles et des instructions d’invocation dynamique, inspirées des avancées du bytecode JVM, pour générer efficacement des instructions assembleur pour les appels natifs.

Démonstrations pratiques avec Panama

Brice a démontré les capacités de Panama via du codage en direct, commençant par un exemple simple appelant la fonction getpid de la bibliothèque standard C. À l’aide du SystemLinker, il a effectué une recherche de symbole pour localiser getpid, créé un method handle avec un descripteur de fonction définissant la signature (retournant un long Java), et l’a invoqué pour récupérer l’ID du processus. Ce processus a contourné les lourdeurs de JNI, nécessitant seulement quelques lignes de code Java. Brice a insisté sur l’activation de l’accès natif avec le flag –enable-native-access dans JDK 18, renforçant le modèle de sécurité de Panama en limitant l’accès à des modules spécifiques.

Il a ensuite présenté un exemple plus complexe avec la fonction crypto_box de la bibliothèque cryptographique Libsodium, portable sur des plateformes comme Android. Brice a alloué des segments de mémoire avec un ResourceScope et un NativeAllocator, garantissant la sécurité mémoire en libérant automatiquement les ressources après usage, contrairement à JNI qui dépend du garbage collector. Le ResourceScope prévient les fuites mémoire, une amélioration significative par rapport aux buffers natifs traditionnels. Brice a également abordé l’appel de code Swift via des interfaces compatibles C, démontrant la polyvalence de Panama.

Outils et potentiel futur

Brice a introduit jextract, un outil de Panama qui génère des mappings Java à partir de headers C/C++, simplifiant l’intégration de bibliothèques comme Blake3, une fonction de hachage performante écrite en Rust. Dans une démo, il a montré comment jextract créait des bindings compatibles Panama pour les structures de données et fonctions de Blake3, permettant aux développeurs Java de tirer parti des performances natives sans bindings manuels. Malgré quelques accrocs, la démo a souligné le potentiel de Panama pour des intégrations natives transparentes.

Brice a conclu en soulignant les avantages de Panama : simplicité, rapidité, compatibilité multiplateforme et sécurité mémoire renforcée. Il a noté son évolution continue, avec JEP-419 en incubation dans JDK 18 et une deuxième preview prévue pour JDK 19. Pour les développeurs d’applications desktop ou de systèmes critiques, Panama offre une solution puissante pour exploiter des fonctions spécifiques aux OS ou des bibliothèques optimisées comme Libsodium. Brice a encouragé le public à expérimenter Panama et à poser des questions, renforçant son engagement via Twitter.

PostHeaderIcon [DevoxxFR 2018] Java in Docker: Best Practices for Production

The practice of running Java applications within Docker containers has become widely adopted in modern software deployment, yet it is not devoid of potential challenges, particularly when transitioning to production environments. Charles Sabourdin, a freelance architect, and Jean-Christophe Sirot, an engineer at Docker, collaborated at DevoxxFR2018 to share their valuable experiences and disseminate best practices for optimizing Java applications inside Docker containers. Their insightful talk directly addressed common and often frustrating issues, such as containers crashing unexpectedly, applications consuming excessive RAM leading to node instability, and encountering CPU throttling. They offered practical solutions and configurations aimed at ensuring smoother and more reliable production deployments for Java workloads.

The presenters initiated their session with a touch of humor, explaining why operations teams might exhibit a degree of apprehension when tasked with deploying a containerized Java application into a production setting. It’s a common scenario: containers that perform flawlessly on a developer’s local machine can begin to behave erratically or fail outright in production. This discrepancy often stems from a fundamental misunderstanding of how the Java Virtual Machine (JVM) interacts with the resource limits imposed by the container’s control groups (cgroups). Several key problems frequently surface in this context. Perhaps the most common is memory mismanagement; the JVM, particularly older versions, might not be inherently aware of the memory limits defined for its container by the cgroup. This lack of awareness can lead the JVM to attempt to allocate and use more memory than has been allocated to the container by the orchestrator or runtime. Such overconsumption inevitably results in the container being abruptly terminated by the operating system’s Out-Of-Memory (OOM) killer, a situation that can be difficult to diagnose without understanding this interaction.

Similarly, CPU resource allocation can present challenges. The JVM might not accurately perceive the CPU resources available to it within the container, such as CPU shares or quotas defined by cgroups. This can lead to suboptimal decisions in sizing internal thread pools (like the common ForkJoinPool or garbage collection threads) or can cause the application to experience unexpected CPU throttling, impacting performance. Another frequent issue is Docker image bloat. Overly large Docker images not only increase deployment times across the infrastructure but also expand the potential attack surface by including unnecessary libraries or tools, thereby posing security vulnerabilities. The talk aimed to equip developers and operations personnel with the knowledge to anticipate and mitigate these common pitfalls. During the presentation, a demonstration application, humorously named “ressources-munger,” was used to simulate these problems, clearly showing how an application could consume excessive memory leading to an OOM kill by Docker, or how it might trigger excessive swapping if not configured correctly, severely degrading performance.

JVM Memory Management and CPU Considerations within Containers

A significant portion of the discussion was dedicated to the intricacies of JVM memory management within the containerized environment. Charles and Jean-Christophe elaborated that older JVM versions, specifically those prior to Java 8 update 131 and Java 9, were not inherently “cgroup-aware”. This lack of awareness meant that the JVM’s default heap sizing heuristics—for example, typically allocating up to one-quarter of the physical host’s memory for the heap—would be based on the total resources of the host machine rather than the specific limits imposed on the container by its cgroup. This behavior is a primary contributor to unexpected OOM kills when the container’s actual memory limit is much lower than what the JVM assumes based on the host.

Several best practices were shared to address these memory-related issues effectively. The foremost recommendation is to use cgroup-aware JVM versions. Modern Java releases, particularly Java 8 update 191 and later, and Java 10 and newer, incorporate significantly improved cgroup awareness. For older Java 8 updates (specifically 8u131 to 8u190), experimental flags such as -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap can be employed to enable the JVM to better respect container memory limits. In Java 10 and subsequent versions, this behavior became standard and often requires no special flags. However, even with cgroup-aware JVMs, explicitly setting the heap size using parameters like -Xms for the initial heap size and -Xmx for the maximum heap size is frequently a recommended practice for predictability and control. Newer JVMs also offer options like -XX:MaxRAMPercentage, allowing for more dynamic heap sizing relative to the container’s allocated memory. It’s crucial to understand that the JVM’s total memory footprint extends beyond just the heap; it also requires memory for metaspace (which replaced PermGen in Java 8+), thread stacks, native libraries, and direct memory buffers. Therefore, when allocating memory to a container, it is essential to account for this total footprint, not merely the -Xmx value. A common guideline suggests that the Java heap might constitute around 50-75% of the total memory allocated to the container, with the remainder reserved for these other essential JVM components and any other processes running within the container. Tuning metaspace parameters, such as -XX:MetaspaceSize and -XX:MaxMetaspaceSize, can also prevent excessive native memory consumption, particularly in applications that dynamically load many classes.

Regarding CPU resources, the presenters noted that the JVM’s perception of available processors is also influenced by its cgroup awareness. In environments where CPU resources are constrained, using flags like -XX:ActiveProcessorCount can be beneficial to explicitly inform the JVM about the number of CPUs it should consider for sizing its internal thread pools, such as the common ForkJoinPool or the threads used for garbage collection. Optimizing the Docker image itself is another critical aspect of preparing Java applications for production. This involves choosing a minimal base image, such as alpine-jre, distroless, or official “slim” JRE images, instead of a full operating system distribution, to reduce the image size and potential attack surface. Utilizing multi-stage builds in the Dockerfile is a highly recommended technique; this allows developers to use a larger image containing build tools like Maven or Gradle and a full JDK in an initial stage, and then copy only the necessary application artifacts (like the JAR file) and a minimal JRE into a final, much smaller runtime image. Furthermore, being mindful of Docker image layering by combining related commands in the Dockerfile where possible can help reduce the number of layers and optimize image size. For applications on Java 9 and later, tools like jlink can be used to create custom, minimal JVM runtimes that include only the Java modules specifically required by the application, further reducing the image footprint. The session strongly emphasized that a collaborative approach between development and operations teams, combined with a thorough understanding of both JVM internals and Docker containerization principles, is paramount for successfully and reliably running Java applications in production environments.

Links:

Hashtags: #Java #Docker #JVM #Containerization #DevOps #Performance #MemoryManagement #DevoxxFR2018 #CharlesSabourdin #JeanChristopheSirot #BestPractices #ProductionReady #CloudNative

PostHeaderIcon [DevoxxUS2017] 55 New Features in JDK 9: A Comprehensive Overview

At DevoxxUS2017, Simon Ritter, Deputy CTO at Azul Systems, delivered a detailed exploration of the 55 new features in JDK 9, with a particular focus on modularity through Project Jigsaw. Simon, a veteran Java evangelist, provided a whirlwind tour of the enhancements, categorizing them into features, standards, JVM internals, specialized updates, and housekeeping changes. His presentation equipped developers with the knowledge to leverage JDK 9’s advancements effectively. This post examines the key themes of Simon’s talk, highlighting how these features enhance Java’s flexibility, performance, and maintainability.

Modularity and Project Jigsaw

The cornerstone of JDK 9 is Project Jigsaw, which introduces modularity to the Java platform. Simon explained that the traditional rt.jar file, containing over 4,500 classes, has been replaced with 94 modular components in the jmods directory. This restructuring encapsulates private APIs, such as sun.misc.Unsafe, to improve security and maintainability, though it poses compatibility challenges for libraries relying on these APIs. To mitigate this, Simon highlighted options like the --add-exports and --add-opens flags, as well as a “big kill switch” (--permit-illegal-access) to disable modularity for legacy applications. The jlink tool further enhances modularity by creating custom runtimes with only the necessary modules, optimizing deployment for specific applications.

Enhanced APIs and Developer Productivity

JDK 9 introduces several API improvements to streamline development. Simon showcased factory methods for collections, allowing developers to create immutable collections with concise syntax, such as List.of() or Set.of(). The Streams API has been enhanced with methods like takeWhile, dropWhile, and ofNullable, improving expressiveness in data processing. Additionally, the introduction of jshell, an interactive REPL, enables rapid prototyping and experimentation. These enhancements reduce boilerplate code and enhance developer productivity, making Java more intuitive and efficient for modern application development.

JVM Internals and Performance

Simon delved into JVM enhancements, including improvements to the G1 garbage collector, which is now the default in JDK 9. The G1 collector offers better performance for large heaps, addressing limitations of the Concurrent Mark Sweep collector. Other internal improvements include a new process API for accessing operating system process details and a directive file for controlling JIT compiler behavior. These changes enhance runtime efficiency and provide developers with greater control over JVM performance, ensuring Java remains competitive for high-performance applications.

Housekeeping and Deprecations

JDK 9 includes significant housekeeping changes to streamline the platform. Simon highlighted the new version string format, adopting semantic versioning (major.minor.security.patch) for clearer identification. The directory structure has been flattened, eliminating the JRE subdirectory and tools.jar, with configuration files centralized in the conf directory. Deprecated APIs, such as the applet API and certain garbage collection options, have been removed to reduce maintenance overhead. These changes simplify the JDK’s structure, improving maintainability while requiring developers to test applications for compatibility.

Standards and Specialized Features

Simon also covered updates to standards and specialized features. The HTTP/2 client, introduced as an incubator module, allows developers to test and provide feedback before it becomes standard. Other standards updates include support for Unicode 8.0 and the deprecation of SHA-1 certificates for enhanced security. Specialized features, such as the annotations pipeline and parser API, improve the handling of complex annotations and programmatic interactions with the compiler. These updates ensure Java aligns with modern standards while offering flexibility for specialized use cases.

Links:

PostHeaderIcon [DevoxxFR2014] Building New IoT Services Easily with Open Hardware and Lhings: Simplifying Connectivity for Developers

Lecturers

Jose Antonio Lorenzo Fernandez, a PhD in physics turned software engineer, works at Lhings Technologies, specializing in Java EE and embedded programming. His transition from academia to industry reflects a passion for applying technical expertise to practical problems. Jose Pereda, a researcher at the University of Valladolid, Spain, focuses on embedded systems and IoT development, contributing to open-source projects that bridge hardware and software innovation.

Abstract

The Internet of Things (IoT) has revolutionized device connectivity, but developers often grapple with complex networking challenges, such as configuring routers, handling firewalls, and managing protocols. Presented at Devoxx France 2014, this lecture demonstrates how Lhings, a cloud-based platform, simplifies IoT development by abstracting connectivity issues, allowing developers to focus on device functionality. Through a live coding session, Jose Antonio Lorenzo Fernandez and Jose Pereda showcase how to connect Java-capable devices using open hardware and Lhings, eliminating boilerplate networking code. The talk explores Lhings’ core concepts—device management, secure communication, and web-based control panels—and highlights its scalability and reliability. By analyzing the platform’s architecture and practical applications, it provides a comprehensive guide for developers building IoT services, emphasizing rapid prototyping and real-world deployment.

The IoT Connectivity Challenge

The proliferation of affordable open hardware, such as Raspberry Pi and Arduino, has democratized IoT development, enabling rapid prototyping of smart devices. However, connectivity remains a significant hurdle. Residential routers, NAT configurations, and diverse protocols like MQTT or CoAP require extensive setup, diverting focus from core functionality. Lorenzo Fernandez explains that developers often spend disproportionate time on networking code, handling tasks like port forwarding or secure socket implementation, which can delay projects and introduce errors.

Lhings addresses this by providing a cloud-based platform that manages device communication, abstracting low-level details. Devices register with Lhings, which handles routing, security, and interoperability, allowing developers to focus on application logic. Pereda emphasizes that this approach mirrors the simplicity of web APIs, making IoT development accessible even to those without networking expertise.

Live Coding: Connecting Devices with Lhings

The speakers demonstrate Lhings through a live coding session, connecting a Java-capable Raspberry Pi to a sensor network. The setup involves minimal code, as Lhings’ SDK abstracts networking:

import com.lhings.client.LhingsDevice;

public class SensorDevice {
    public static void main(String[] args) {
        LhingsDevice device = new LhingsDevice("Sensor1", "API_KEY");
        device.connect();
        device.sendEvent("temperature", 25.5);
    }
}

This code registers a device named “Sensor1” with Lhings, connects to the cloud, and sends a temperature reading. No networking code—such as socket management or firewall configuration—is required. The platform uses encrypted WebSocket connections, ensuring security without developer intervention.

The demo extends to a web control panel, automatically generated by Lhings, where users can monitor and control devices. Pereda shows how adding a new device, such as a smart light, requires only a few lines of code, highlighting scalability. The panel supports real-time updates, allowing remote control via a browser, akin to a smart home dashboard.

Lhings’ Architecture and Features

Lhings operates as a cloud middleware, sitting between devices and end-users. Devices communicate via a lightweight SDK, available for Java, Python, and C++, supporting platforms like Raspberry Pi and Arduino. The platform handles message routing, ensuring devices behind NATs or firewalls remain accessible. Security is baked in, with all communications encrypted using TLS, addressing common IoT vulnerabilities.

Scalability is a key strength: adding devices involves registering them with unique API keys, with no upper limit on device count. The platform’s reliability stems from its distributed architecture, tested by thousands of users globally. Lorenzo Fernandez notes that Lhings supports bidirectional communication, enabling servers to push commands to devices, a feature critical for applications like home automation.

Practical Applications and Benefits

The talk showcases real-world use cases, such as a smart thermostat system where sensors report temperature and a server adjusts settings remotely. This eliminates the need for local network configuration, as devices connect to Lhings’ cloud over standard internet protocols. The web control panel provides instant access, making it ideal for rapid prototyping or production-grade systems.

Benefits include reduced development time, enhanced security, and ease of scaling. By abstracting networking, Lhings allows developers to focus on device logic—e.g., sensor algorithms or UI design—while the platform handles connectivity and management. The open-source SDK and GitHub-hosted examples further lower barriers, encouraging community contributions.

Challenges and Considerations

While powerful, Lhings requires an internet connection, limiting its use in offline scenarios. Pereda acknowledges that latency-sensitive applications, such as real-time robotics, may need local processing alongside Lhings’ cloud capabilities. The platform’s dependency on a proprietary service also raises questions about vendor lock-in, though its open SDK mitigates this by supporting custom integrations.

Conclusion: Empowering IoT Innovation

Lhings transforms IoT development by removing connectivity barriers, enabling developers to build robust services with minimal effort. The live demo at DevoxxFR2014 illustrates its practicality, from prototyping to deployment. As IoT adoption grows, platforms like Lhings will play a critical role in making smart devices accessible and secure, empowering developers to innovate without wrestling with networking complexities.

Links

PostHeaderIcon [DevoxxFR2014] Akka Made Our Day: Harnessing Scalability and Resilience in Legacy Systems

Lecturers

Daniel Deogun and Daniel Sawano are senior consultants at Omega Point, a Stockholm-based consultancy with offices in Malmö and New York. Both specialize in building scalable, fault-tolerant systems, with Deogun focusing on distributed architectures and Sawano on integrating modern frameworks like Akka into enterprise environments. Their combined expertise in Java and Scala, along with practical experience in high-stakes projects, positions them as authoritative voices on leveraging Akka for real-world challenges.

Abstract

Akka, a toolkit for building concurrent, distributed, and resilient applications using the actor model, is renowned for its ability to deliver high-performance systems. However, integrating Akka into legacy environments—where entrenched codebases and conservative practices dominate—presents unique challenges. Delivered at Devoxx France 2014, this lecture shares insights from Omega Point’s experience developing an international, government-approved system using Akka in Java, despite Scala’s closer alignment with Akka’s APIs. The speakers explore how domain-specific requirements shaped their design, common pitfalls encountered, and strategies for success in both greenfield and brownfield contexts. Through detailed code examples, performance metrics, and lessons learned, the talk demonstrates Akka’s transformative potential and why Java was a strategic choice for business success. It concludes with practical advice for developers aiming to modernize legacy systems while maintaining reliability and scalability.

The Actor Model: A Foundation for Resilience

Akka’s core strength lies in its implementation of the actor model, a paradigm where lightweight actors encapsulate state and behavior, communicating solely through asynchronous messages. This eliminates shared mutable state, a common source of concurrency bugs in traditional multithreaded systems. Daniel Sawano introduces the concept with a simple Java-based Akka actor:

import akka.actor.UntypedActor;

public class GreetingActor extends UntypedActor {
    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof String) {
            System.out.println("Hello, " + message);
            getSender().tell("Greetings received!", getSelf());
        } else {
            unhandled(message);
        }
    }
}

This actor receives a string message, processes it, and responds to the sender. Actors run in an ActorSystem, which manages their lifecycle and threading:

import akka.actor.ActorSystem;
import akka.actor.ActorRef;
import akka.actor.Props;

ActorSystem system = ActorSystem.create("MySystem");
ActorRef greeter = system.actorOf(Props.create(GreetingActor.class), "greeter");
greeter.tell("World", ActorRef.noSender());

This setup ensures isolation and fault tolerance, as actors operate independently and can be supervised to handle failures gracefully.

Designing with Domain Requirements

The project discussed was a government-approved system requiring high throughput, strict auditability, and fault tolerance to meet regulatory standards. Deogun explains that they modeled domain entities as actor hierarchies, with parent actors supervising children to recover from failures. For example, a transaction processing system used actors to represent accounts, with each actor handling a subset of operations, ensuring scalability through message-passing.

The choice of Java over Scala was driven by business needs. While Scala’s concise syntax aligns closely with Akka’s functional style, the team’s familiarity with Java reduced onboarding time and aligned with the organization’s existing skill set. Java’s Akka API, though more verbose, supports all core features, including clustering and persistence. Sawano notes that this decision accelerated adoption in a conservative environment, as developers could leverage existing Java libraries and tools.

Pitfalls and Solutions in Akka Implementations

Implementing Akka in a legacy context revealed several challenges. One common issue was message loss in high-throughput scenarios. To address this, the team implemented acknowledgment protocols, ensuring reliable delivery:

public class ReliableActor extends UntypedActor {
    @Override
    public void onReceive(Object message) throws Exception {
        if (message instanceof String) {
            // Process message
            getSender().tell("ACK", getSelf());
        } else {
            unhandled(message);
        }
    }
}

Deadlocks, another risk, were mitigated by avoiding blocking calls within actors. Instead, asynchronous futures were used for I/O operations:

import scala.concurrent.Future;
import static akka.pattern.Patterns.pipe;

Future<String> result = someAsyncOperation();
pipe(result, context().dispatcher()).to(getSender());

State management in distributed systems posed further challenges. Persistent actors ensured data durability by storing events to a journal:

import akka.persistence.UntypedPersistentActor;

public class PersistentCounter extends UntypedPersistentActor {
    private int count = 0;

    @Override
    public String persistenceId() {
        return "counter-id";
    }

    @Override
    public void onReceiveCommand(Object command) {
        if (command.equals("increment")) {
            persist(1, evt -> count += evt);
        }
    }

    @Override
    public void onReceiveRecover(Object event) {
        if (event instanceof Integer) {
            count += (Integer) event;
        }
    }
}

This approach allowed the system to recover state after crashes, critical for regulatory compliance.

Performance and Scalability Achievements

The system achieved impressive performance, handling 100,000 requests per second with 99.9% uptime. Akka’s location transparency enabled clustering across nodes, distributing workload efficiently. Deogun highlights that actors’ lightweight nature—thousands can run on a single JVM—allowed scaling without heavy resource overhead. Metrics showed consistent latency under 10ms for critical operations, even under peak load.

Integrating Akka with Legacy Systems

Legacy integration required wrapping existing services in actors to isolate faults. For instance, a monolithic database layer was accessed via actors, which managed connection pooling and retry logic. This approach minimized changes to legacy code while introducing Akka’s resilience benefits. Sawano emphasizes that incremental adoption—starting with a single actor-based module—eased the transition.

Lessons Learned and Broader Implications

The project underscored Akka’s versatility in both greenfield and brownfield contexts. Key lessons included the importance of clear message contracts to avoid runtime errors and the need for robust monitoring to track actor performance. Tools like Typesafe Console (now Lightbend Telemetry) provided insights into message throughput and bottlenecks.

For developers, the talk offers a blueprint for modernizing legacy systems: start small, leverage Java for familiarity, and use Akka’s supervision for reliability. For organizations, it highlights the business value of resilience and scalability, particularly in regulated industries.

Conclusion: Akka as a Game-Changer

Deogun and Sawano’s experience demonstrates that Akka can transform legacy environments by providing a robust framework for concurrency and fault tolerance. Choosing Java over Scala proved strategic, aligning with team skills and accelerating delivery. As distributed systems become the norm, Akka’s actor model offers a proven path to scalability, making it a vital tool for modern software engineering.

Links

PostHeaderIcon [DevoxxFR2014] 42 IntelliJ IDEA Tips and Tricks in 45 Minutes – A Thorough Examination of Productivity Boosters

Lecturer

Hadi Hariri has built a distinguished career as a Technical Evangelist at JetBrains, where he promotes IntelliJ IDEA and other development tools through presentations, podcasts, and community engagement. With extensive experience in software architecture and web development, he has authored numerous articles and books while contributing to open-source projects. Based in Spain, Hadi balances his professional life with family responsibilities, including raising three sons, and maintains interests in Tennis and technology evangelism.

Abstract

IntelliJ IDEA represents a pinnacle of integrated development environments, offering an extensive array of features designed to enhance developer productivity across the entire software lifecycle. This presentation delivers a fast-paced overview of 42 essential tips and tricks, though in reality incorporating over 100 individual techniques, each carefully selected to address specific challenges in code navigation, completion, refactoring, debugging, and version control. The article provides a detailed analysis of these features, explaining their implementation mechanics, practical applications, and impact on workflow efficiency. Through live demonstrations and step-by-step breakdowns, it shows how mastering these tools can transform daily development tasks from tedious obligations into streamlined processes, ultimately leading to higher quality code and faster delivery.

Navigation Mastery: Moving Through Code with Precision and Speed

Efficient navigation forms the foundation of productive development in IntelliJ IDEA, allowing users to traverse large codebases with minimal cognitive effort. The Recent Files dialog, accessed via Ctrl+E on Windows or Cmd+E on Mac, presents a chronological list of edited files, enabling quick context switching without manual searching. This feature proves particularly valuable in multi-module projects where related files span different directories, as it preserves mental flow during iterative development cycles.

The Navigate to Class command, triggered by Ctrl+N, allows instant location of any class by typing its name with support for camel-case abbreviation, such as “SC” for StringCalculator. This extends to symbols through Ctrl+Alt+Shift+N, encompassing methods, fields, and variables across the project. These capabilities rely on IntelliJ’s sophisticated indexing system, which builds comprehensive symbol tables upon project load, delivering sub-second search results even in repositories exceeding a million lines of code.

The Structure view, opened with Alt+7, offers a hierarchical outline of the current file’s elements, including methods, fields, and nested classes, with incremental search for rapid location. When combined with the File Structure Popup via Ctrl+F12, developers can navigate complex files without diverting attention from the editor window, maintaining focus during intensive coding sessions.

Code Completion and Generation: Intelligent Assistance for Faster Coding

IntelliJ’s completion system transcends basic auto-suggest by incorporating contextual awareness and type inference to propose relevant options. Basic completion, invoked with Ctrl+Space, suggests identifiers based on scope and visibility, while smart completion via Ctrl+Shift+Space filters to match expected types, preventing invalid assignments and reducing debugging time.

Postfix completion introduces a novel way to wrap expressions with common constructs; for instance, typing “.not” after a boolean generates negation logic, while “.for” creates an iteration loop over collections. This feature streamlines frequent patterns, such as null checks with “.nn” or type casting with “.cast”, integrating seamlessly with the editor’s flow.

Live templates automate repetitive structures; the built-in “sout” expands to System.out.println(), while custom templates can generate complete test methods with annotations and assertions. Hadi demonstrates creating a JUnit template that includes setup code, triggered by a user-defined abbreviation for instant productivity gains.

The generate-from-usage feature, activated with Alt+Enter on undefined elements, creates missing methods, fields, or classes on demand. This supports an intentional coding style where developers first express usage intent, then implement details, aligning perfectly with test-driven development methodologies.

Refactoring Tools: Safe Code Transformation at Scale

Refactoring in IntelliJ maintains program semantics while restructuring code for improved readability and maintainability. The rename refactoring, via Shift+F6, updates all references including comments and string literals when enabled, handling scope conflicts intelligently. Extract method (Ctrl+Alt+M) creates functions from selected code blocks, automatically determining parameters and return types based on usage analysis.

Inline refactoring (Ctrl+Alt+N) reverses extractions, useful for simplifying overly fragmented code while preserving behavior. Change signature (Ctrl+F6) modifies method parameters with propagation to callers, inserting default values for new parameters to avoid compilation errors.

Surround with (Ctrl+Alt+T) wraps selected code in control structures like try-catch or if-else, with template support for custom patterns. These tools collectively enable large-scale code reorganization without manual error-prone adjustments.

Debugging Capabilities: Deep Insight into Runtime Behavior

The debugger provides sophisticated inspection beyond basic stepping. Smart step into (Shift+F7) allows selective entry into chained method calls, focusing on relevant code paths. Evaluate expression (Alt+F8) executes arbitrary code in the current frame, supporting complex debugging scenarios like modifying variables mid-execution.

Drop frame rewinds the call stack, re-executing methods without full restart, ideal for iterative testing of logic branches. Conditional breakpoints pause only when expressions evaluate true, filtering irrelevant iterations in loops.

Lambda debugging treats expressions as methods with full variable inspection and stepping. Custom renderers format complex objects, like displaying collections as comma-separated lists.

Version Control Integration: Streamlined Collaboration

Git support includes visual diffs (Ctrl+D) for conflict resolution, branch management through intuitive dialogs, and cherry-picking from commit histories. The changes view lists modified files with diff previews; annotate shows per-line authorship and revisions.

Interactive rebase through the VCS menu simplifies history cleaning by squashing or reordering commits. Pull request workflows integrate with GitHub, displaying comments directly in the editor for contextual review.

Plugin Ecosystem: Extending Functionality

Plugins like Lombok automate boilerplate with annotations, while Key Promoter X teaches shortcuts through notifications. SonarLint integrates code quality checks, flagging issues in real-time.

Custom plugin development uses Java with SDK support for editor extensions and custom tools.

Advanced Configuration for Optimal Performance

Running on Java 8+ (edit info.plist) improves font rendering. The productivity guide tracks feature usage, helping discover underutilized tools.

Conclusion: IntelliJ as Productivity Multiplier

These techniques collectively transform IntelliJ into an indispensable tool that accelerates development while improving code quality. Consistent application leads to substantial time savings and better software outcomes.

Links:

PostHeaderIcon [DevoxxFR2014] Reactive Programming with RxJava: Building Responsive Applications

Lecturer

Ben Christensen works as a software engineer at Netflix. He leads the development of reactive libraries for the JVM. Ben serves as a core contributor to RxJava. He possesses extensive experience in constructing resilient, low-latency systems for streaming platforms. His expertise centers on applying functional reactive programming principles to microservices architectures.

Abstract

This article provides an in-depth exploration of RxJava, Netflix’s implementation of Reactive Extensions for the JVM. It analyzes the Observable pattern as a foundation for composing asynchronous and event-driven programs. The discussion covers essential operators for data transformation and composition, schedulers for concurrency management, and advanced error handling strategies. Through concrete Netflix use cases, the article demonstrates how RxJava enables non-blocking, resilient applications and contrasts this approach with traditional callback-based paradigms.

The Observable Pattern and Push vs. Pull Models

RxJava revolves around the Observable, which functions as a push-based, composable iterator. Unlike the traditional pull-based Iterable, Observables emit items asynchronously to subscribers. This fundamental duality enables uniform treatment of synchronous and asynchronous data sources:

Observable<String> greeting = Observable.just("Hello", "RxJava");
greeting.subscribe(System.out::println);

The Observer interface defines three callbacks: onNext for data emission, onError for exceptions, and onCompleted for stream termination. RxJava enforces strict contracts for backpressure—ensuring producers respect consumer consumption rates—and cancellation through unsubscribe operations.

Operator Composition and Declarative Programming

RxJava provides over 100 operators that transform, filter, and combine Observables in a declarative manner. These operators form a functional composition pipeline:

Observable.range(1, 10)
          .filter(n -> n % 2 == 0)
          .map(n -> n * n)
          .subscribe(square -> System.out.println("Square: " + square));

The flatMap operator proves particularly powerful for concurrent operations, such as parallel API calls:

Observable<User> users = getUserIds();
users.flatMap(userId -> userService.getDetails(userId), 5)
     .subscribe(user -> process(user));

This approach eliminates callback nesting (callback hell) while maintaining readability and composability. Marble diagrams visually represent operator behavior, illustrating timing, concurrency, and error propagation.

Concurrency Control with Schedulers

RxJava decouples computation from threading through Schedulers, which abstract thread pools:

Observable.just(1, 2, 3)
          .subscribeOn(Schedulers.io())
          .observeOn(Schedulers.computation())
          .map(this::cpuIntensiveTask)
          .subscribe(result -> display(result));

Common schedulers include:
Schedulers.io() for I/O-bound operations (network, disk).
Schedulers.computation() for CPU-bound tasks.
Schedulers.newThread() for fire-and-forget operations.

This abstraction enables non-blocking I/O without manual thread management or blocking queues.

Error Handling and Resilience Patterns

RxJava treats errors as first-class citizens in the data stream:

Observable risky = Observable.create(subscriber -> {
    subscriber.onNext(computeRiskyValue());
    subscriber.onError(new RuntimeException("Failed"));
});
risky.onErrorResumeNext(throwable -> Observable.just("Default"))
     .subscribe(value -> System.out.println(value));

Operators like retry, retryWhen, and onErrorReturn implement resilience patterns such as exponential backoff and circuit breakers—critical for microservices in failure-prone networks.

Netflix Production Use Cases

Netflix employs RxJava across its entire stack. The UI layer composes multiple backend API calls for personalized homepages:

Observable<Recommendation> recs = userIdObservable
    .flatMap(this::fetchUserProfile)
    .flatMap(profile -> Observable.zip(
        fetchTopMovies(profile),
        fetchSimilarUsers(profile),
        this::combineRecommendations));

The API gateway uses RxJava for timeout handling, fallbacks, and request collapsing. Backend services leverage it for event processing and data aggregation.

Broader Impact on Software Architecture

RxJava embodies the Reactive Manifesto principles: responsive, resilient, elastic, and message-driven. It eliminates common concurrency bugs like race conditions and deadlocks. For JVM developers, RxJava offers a functional, declarative alternative to imperative threading models, enabling cleaner, more maintainable asynchronous code.

Links:

PostHeaderIcon [DevoxxBE2013] Architecting Android Applications with Dagger

Jake Wharton, an Android engineering luminary at Square, champions Dagger, a compile-time dependency injector revolutionizing Java and Android modularity. Creator of Retrofit and Butter Knife, Jake elucidates Dagger’s divergence from reflection-heavy alternatives like Guice, emphasizing its speed and testability. His session overviews injection principles, Android-specific scoping, and advanced utilities like Lazy and Assisted Injection, arming developers with patterns for clean, verifiable code.

Dagger, Jake stresses, decouples class behaviors from dependencies, fostering reusable, injectable components. Through live examples, he builds a Twitter client, showcasing modules for API wrappers and HTTP clients, ensuring seamless integration.

Dependency Injection Fundamentals

Jake defines injection as externalizing object wiring, promoting loose coupling. He contrasts manual factories with Dagger’s annotation-driven graphs, where @Inject fields auto-resolve dependencies.

This pattern, Jake demonstrates, simplifies testing—mock modules swap implementations effortlessly, isolating units.

Dagger in Android Contexts

Android’s lifecycle demands scoping, Jake explains: @Singleton for app-wide instances, activity-bound for UI components. He constructs an app graph, injecting Twitter services into activities.

Fragments and services, he notes, inherit parent scopes, minimizing boilerplate while preserving encapsulation.

Advanced Features and Utilities

Dagger’s extras shine: @Lazy defers creation, @Assisted blends factories with injection for parameterized objects. Jake demos provider methods in modules, binding interfaces dynamically.

JSR-330 compliance, augmented by @Module, ensures portability, though Jake clarifies Dagger’s compile-time limits preclude Guice’s AOP dynamism.

Testing and Production Tips

Unit tests leverage Mockito for mocks, Jake illustrates, verifying injections without runtime costs. Production graphs, he advises, tier via subcomponents, optimizing memory.

Dagger’s reflection-free speed, Jake concludes, suits resource-constrained Android, with Square’s hiring call underscoring real-world impact.

Links: