Recent Posts
Archives

Posts Tagged ‘JVM’

PostHeaderIcon [DevoxxBE2012] Putting Kotlin to the Test

During DevoxxBE2012, Hadi Hariri, a developer and technical evangelist at JetBrains, presented an in-depth evaluation of Kotlin, a then-emerging programming language designed by his company. Hadi, with his background in software architecture and web development, aimed to assess whether Kotlin could address common pitfalls in existing languages while serving as a versatile tool for various development needs. He began by providing context on Kotlin’s origins, noting its static typing, object-oriented nature, and targets for JVM bytecode and JavaScript compilation. Licensed under Apache 2.0, it was at milestone M3, with expectations for further releases leading to beta.

Hadi explained the motivation behind Kotlin: after years of building IDEs in Java, JetBrains sought a more efficient alternative without the complexities of languages like Scala. He highlighted Kotlin’s focus on practicality, aiming to reduce boilerplate and enhance productivity. Through live coding, Hadi demonstrated building a real-world application, showcasing how Kotlin simplifies syntax and integrates seamlessly with Java.

One key aspect was Kotlin’s concise class definitions, where properties and constructors merge into a single line, eliminating redundant getters and setters. Hadi illustrated this with examples, contrasting it with verbose Java equivalents. He also touched on null safety, where the language enforces checks to prevent null pointer exceptions, a frequent issue in other systems.

As the session progressed, Hadi explored functional programming elements, such as higher-order functions and lambdas, which allow for expressive code without excessive ceremony. He built components of an application, like data models and services, to test interoperability and performance.

Syntax Innovations and Productivity Gains

Hadi delved into Kotlin’s syntax, emphasizing features like extension functions that add methods to existing classes without inheritance. This promotes cleaner code and reusability. He showed how to extend standard library classes, making operations more intuitive.

Data classes were another highlight, automatically providing equals, hashCode, and toString methods, ideal for immutable objects. Hadi used these in his demo app to handle entities efficiently.

Pattern matching via ‘when’ expressions offered a more powerful alternative to switch statements, supporting complex conditions. Hadi integrated this into control flows, demonstrating reduced branching logic.

Smart casts automatically handle type checks, minimizing explicit casts. In his application, this streamlined interactions with mixed-type collections.

Interoperability and Platform Targets

A core strength, as Hadi pointed out, is Kotlin’s full compatibility with Java. Code can call Java libraries directly, and vice versa, facilitating gradual adoption. He compiled mixed projects, showing no performance overhead.

Targeting JavaScript, Kotlin compiles to efficient code for web fronts, sharing logic between server and client. Hadi previewed this, noting potential for unified development stacks.

He addressed modules and versioning, still in progress, but promising better organization than Java packages.

Functional and Advanced Constructs

Hadi introduced traits, similar to interfaces but with implementations, enabling mixin-like behavior. He used them to compose behaviors in his app.

Delegated properties handled lazy initialization and observables, useful for UI bindings or caching.

Coroutines, though nascent, hinted at simplified asynchronous programming.

In Q&A, Hadi clarified comparisons to Ceylon and Scala, noting Kotlin’s balance of comprehensibility and power. He discussed potential .NET targeting, driven by demand.

Real-World Application Demo

Throughout, Hadi built a sample app, testing features in context. He covered error handling, collections, and concurrency, proving Kotlin’s robustness.

He encouraged trying Kotlin via IntelliJ’s community edition, which supports it natively.

Hadi’s presentation positioned Kotlin as a promising contender, fixing expensive language flaws while maintaining industrial applicability.

Links:

PostHeaderIcon [DevoxxFR2012] Optimizing Resource Utilization: A Deep Dive into JVM, OS, and Hardware Interactions

Lecturers

Ben Evans and Martijn Verburg are titans of the Java performance community. Ben, co-author of The Well-Grounded Java Developer and a Java Champion, has spent over a decade dissecting JVM internals, GC algorithms, and hardware interactions. Martijn, known as the “Diabolical Developer,” co-leads the London Java User Group, serves on the JCP Executive Committee, and advocates for developer productivity and open-source tooling. Together, they have shaped modern Java performance practices through books, tools, and conference talks that bridge the gap between application code and silicon.

Abstract

This exhaustive exploration revisits Ben Evans and Martijn Verburg’s seminal 2012 DevoxxFR presentation on JVM resource utilization, expanding it with a decade of subsequent advancements. The core thesis remains unchanged: Java’s “write once, run anywhere” philosophy comes at the cost of opacity—developers deploy applications across diverse hardware without understanding how efficiently they consume CPU, memory, power, or I/O. This article dissects the three-layer stackJVM, Operating System, and Hardware—to reveal how Java applications interact with modern CPUs, memory hierarchies, and power management systems. Through diagnostic tools (jHiccup, SIGAR, JFR), tuning strategies (NUMA awareness, huge pages, GC selection), and cloud-era considerations (vCPU abstraction, noisy neighbors), it provides a comprehensive playbook for achieving 90%+ CPU utilization and minimal power waste. Updated for 2025, this piece incorporates ZGC’s generational mode, Project Loom’s virtual threads, ARM Graviton processors, and green computing initiatives, offering a forward-looking vision for sustainable, high-performance Java in the cloud.

The Abstraction Tax: Why Java Hides Hardware Reality

Java’s portability is its greatest strength and its most significant performance liability. The JVM abstracts away CPU architecture, memory layout, and power states to ensure identical behavior across x86, ARM, and PowerPC. But this abstraction hides critical utilization metrics:
– A Java thread may appear busy but spend 80% of its time in GC pause or context switching.
– A 64-core server running 100 Java processes might achieve only 10% aggregate CPU utilization due to lock contention and GC thrashing.
– Power consumption in data centers—8% of U.S. electricity in 2012, projected at 13% by 2030—is driven by underutilized hardware.

Ben and Martijn argue that visibility is the prerequisite for optimization. Without knowing how resources are used, tuning is guesswork.

Layer 1: The JVM – Where Java Meets the Machine

The HotSpot JVM is a marvel of adaptive optimization, but its default settings prioritize predictability over peak efficiency.

Garbage Collection: The Silent CPU Thief

GC is the largest source of CPU waste in Java applications. Even “low-pause” collectors like CMS introduce stop-the-world phases that halt all application threads.

// Example: CMS GC log
[GC (CMS Initial Mark) 1024K->768K(2048K), 0.0123456 secs]
[Full GC (Allocation Failure) 1800K->1200K(2048K), 0.0987654 secs]

Martijn demonstrates how a 10ms pause every 100ms reduces effective CPU capacity by 10%. In 2025, ZGC and Shenandoah achieve sub-millisecond pauses even at 1TB heaps:

-XX:+UseZGC -XX:ZCollectionInterval=100

JIT Compilation and Code Cache

The JIT compiler generates machine code on-the-fly, but code cache eviction under memory pressure forces recompilation:

-XX:ReservedCodeCacheSize=512m -XX:+PrintCodeCache

Ben recommends tiered compilation (-XX:+TieredCompilation) to balance warmup and peak performance.

Threading and Virtual Threads (2025 Update)

Traditional Java threads map 1:1 to OS threads, incurring 1MB stack overhead and context switch costs. Project Loom introduces virtual threads in Java 21:

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 100_000).forEach(i -> 
        executor.submit(() -> blockingIO()));
}

This enables millions of concurrent tasks with minimal OS overhead, saturating CPU without thread explosion.

Layer 2: The Operating System – Scheduler, Memory, and Power

The OS mediates between JVM and hardware, introducing scheduling, caching, and power management policies.

CPU Scheduling and Affinity

Linux’s CFS scheduler fairly distributes CPU time, but noisy neighbors in multi-tenant environments cause jitter. CPU affinity pins JVMs to cores:

taskset -c 0-7 java -jar app.jar

In NUMA systems, memory locality is critical:

// JNA call to sched_setaffinity

Memory Management: RSS vs. USS

Resident Set Size (RSS) includes shared libraries, inflating perceived usage. Unique Set Size (USS) is more accurate:

smem -t -k -p <pid>

Huge pages reduce TLB misses:

-XX:+UseLargePages -XX:LargePageSizeInBytes=2m

Power Management: P-States and C-States

CPUs dynamically adjust frequency (P-states) and enter sleep (C-states). Java has no direct control, but busy spinning prevents deep sleep:

-XX:+AlwaysPreTouch -XX:+UseNUMA

Layer 3: The Hardware – Cores, Caches, and Power

Modern CPUs are complex hierarchies of cores, caches, and interconnects.

Cache Coherence and False Sharing

Adjacent fields in objects can reside on the same cache line, causing false sharing:

class Counters {
    volatile long c1; // cache line 1
    volatile long c2; // same cache line!
}

Padding or @Contended (Java 8+) resolves this:

@Contended
public class PaddedLong { public volatile long value; }

NUMA and Memory Bandwidth

Non-Uniform Memory Access means local memory is 2–3x faster than remote. JVMs should bind threads to NUMA nodes:

numactl --cpunodebind=0 --membind=0 java -jar app.jar

Diagnostics: Making the Invisible Visible

jHiccup: Measuring Pause Times

java -jar jHiccup.jar -i 1000 -w 5000

Generates histograms of application pauses, revealing GC and OS scheduling hiccups.

Java Flight Recorder (JFR)

-XX:StartFlightRecording=duration=60s,filename=app.jfr

Captures CPU, GC, I/O, and lock contention with <1% overhead.

async-profiler and Flame Graphs

./profiler.sh -e cpu -d 60 -f flame.svg <pid>

Visualizes hot methods and inlining decisions.

Cloud and Green Computing: The Ultimate Utilization Challenge

In cloud environments, vCPUs are abstractions—often half-cores with hyper-threading. Noisy neighbors cause 50%+ variance in performance.

Green Computing Initiatives

  • Facebook’s Open Compute Project: 38% more efficient servers.
  • Google’s Borg: 90%+ cluster utilization via bin packing.
  • ARM Graviton3: 20% better perf/watt than x86.

Spot Markets for Compute (2025 Vision)

Ben and Martijn foresee a commodity market for compute cycles, enabled by:
Live migration via CRIU.
Standardized pricing (e.g., $0.001 per CPU-second).
Java’s portability as the ideal runtime.

Conclusion: Toward a Sustainable Java Future

Evans and Verburg’s central message endures: Utilization is a systems problem. Achieving 90%+ CPU efficiency requires coordination across JVM tuning, OS configuration, and hardware awareness. In 2025, tools like ZGC, Loom, and JFR have made this more achievable than ever, but the principles remain:
Measure everything (JFR, async-profiler).
Tune aggressively (GC, NUMA, huge pages).
Design for the cloud (elastic scaling, spot instances).

By making the invisible visible, Java developers can build faster, cheaper, and greener applications—ensuring Java’s dominance in the cloud-native era.

Links

PostHeaderIcon [DevoxxFR2012] 55 Lesser-Known Features of Java 7: Unveiling Hidden Enhancements Across the Platform

Lecturer

David Delabassee serves as a Director of Developer Relations in the Java Platform Group at Oracle, where he champions Java technologies worldwide through presentations, technical articles, and open-source engagements. Previously at Sun Microsystems for a decade, he focused on end-to-end Java implementations, from smart cards to high-end servers. A member of the Devoxx Belgium steering committee, David co-hosts the Inside Java Podcast and maintains a blog at delabassee.com. He holds Belgian nationality and has spoken at numerous conferences and Java User Groups.

Abstract

This article investigates David Delabassee’s rapid-fire presentation on 55 underappreciated features of Java 7, released in 2011, extending beyond well-known additions like Project Coin, Fork/Join, NIO.2, and invokedynamic. It categorizes enhancements across core libraries, security, internationalization, graphics, and more, analyzing their practical utilities and implementation details. Positioned as a post-Sun acquisition milestone under Oracle, the discussion evaluates how these refinements bolster platform stability, performance, and developer productivity. Through code demonstrations and comparisons to prior versions, it assesses implications for migration, legacy code maintenance, and modern application design, emphasizing Java 7’s role in bridging to future iterations like Java 8.

Core Language and Library Improvements

Java 7 introduced subtle yet impactful tweaks to foundational elements, addressing longstanding pain points. David highlights enhanced exception handling: multi-catch clauses consolidate try-catch blocks for related exceptions, reducing redundancy:

try {
    // Code
} catch (IOException | SQLException e) {
    // Handle
}

String switches leverage interned strings for efficient comparisons, useful in parsing:

switch (input) {
    case "start": // Action
        break;
    // ...
}

Underscores in numeric literals improve readability for large numbers: long creditCard = 1234_5678_9012_3456L;.

Library updates include Objects class utilities like requireNonNull() for null checks, and BitSet enhancements with valueOf() for byte/long array conversions. These foster cleaner, more maintainable code, mitigating common errors in enterprise applications.

Security and Cryptography Advancements

Security received substantial bolstering, crucial amid rising threats. David details elliptic curve cryptography integration, offering stronger keys with smaller sizes for SSL/TLS. Algorithm disabling via jdk.security.provider.disabledAlgorithms property enhances compliance.

SChannel provider on Windows improves native integration, while JSSE updates support SNI for virtual hosting. These fortify networked applications, essential for cloud and web services, reducing vulnerability exposure without external libraries.

Internationalization and Locale Refinements

Java 7 refined locale handling for global apps. Unicode 6.0 support adds scripts like Batak, enhancing text processing. Locale enhancements include script, variant, and extension keys:

Locale loc = new Locale.Builder().setLanguage("fr").setRegion("FR").setScript("Latn").build();

Currency updates reflect ISO 4217 changes, with getAvailableCurrencies() listing supported ones. NumberFormat improvements allow custom symbols, aiding financial software. These ensure accurate, culturally sensitive representations, vital for international markets.

Graphics and UI Toolkit Upgrades

Swing and AWT saw usability boosts. Translucent/shaped windows via GraphicsDevice enable modern UIs:

window.setOpacity(0.5f);

Nimbus look-and-feel, now default in some contexts, provides scalable, themeable components. JLayer adds decoration layers for effects like blurring. These empower richer desktop apps, aligning Java with contemporary design trends.

Performance and JVM Optimizations

JVM internals evolved for efficiency. Tiered compilation combines client/server compilers for faster startups and peak performance. G1 garbage collector, experimental in Java 7, targets low-pause collections for large heaps.

Compressed oops extend 32-bit addressing to 64-bit, reducing memory footprint. These optimizations benefit server-side applications, improving throughput and responsiveness in high-load scenarios.

Migration Considerations and Ecosystem Impact

Adopting Java 7 involves assessing compatibility, given end-of-life for Java 6. David notes seamless transitions for most code, but highlights needs like updating deprecated APIs. Tools like javac -Xlint warn of issues.

Ecosystem-wise, Java 7 paved for Java 8’s lambdas, solidifying Java’s enterprise dominance. Implications include smoother upgrades, enhanced security postures, and broader internationalization, encouraging developers to leverage these for robust, future-proof systems.

Links: