eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this tutorial, we’ll learn something interesting that could help us know our system. Whenever we think about checking CPU usage, memory status, or disk space in Java, we might ask ourselves, Do I need to call system commands or use JNI? Nope! That’s where OSHI (Operating System and Hardware Information) comes in.

OSHI is a pure Java library that helps us fetch system-level details without any native dependencies. It acts as a bridge between our Java application and system APIs, pulling useful information about the OS, hardware, and network in a cross-platform manner.

2. Why Use OSHI for System Monitoring?

We might wonder, “Why not just use Runtime.exec() or System.getProperty()?” Well, those approaches are limited. System.getProperty() can only fetch the OS name and version, while Runtime.exec() requires OS-specific commands.

OSHI, on the other hand, works with the most popular operating systems (Windows, macOS, Linux). It provides deep system insights about CPU, RAM, disks, sensors, and networks. It doesn’t require native code since it is fully Java-based, and last but not least, it’s lightweight and easy to use – we just need to add a dependency.

3. Key Features and Advantages

With OSHI, we can:

  • Get OS details: name, version, architecture, and uptime
  • Monitor CPU usage, core details, and processor speed
  • Fetch memory statistics: total RAM, available memory, swap usage
  • Retrieve disk storage information: partitions, read/write speed
  • Track network interfaces, IP addresses, and bandwidth usage
  • Access sensor data like CPU temperature, fan speeds, and voltages (if supported)

Now, let’s move further and see how we can implement these features.

4. Setting up OSHI in a Java Project

Before we dive into the fun stuff, let’s get OSHI into our project.

If we’re using Maven, we need to add the oshi-core dependency to our pom.xml:

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>6.4.2</version>
</dependency>

Once added, OSHI will be ready to roll out!

5. Retrieving Basic System Information

Now that OSHI is set up, let’s start with the basics: fetching OS details and checking system uptime.

5.1. Fetching Operating System Details

Think of our OS as the brain of the machine. Wouldn’t it be nice to know what OS we’re running on, which version, and whether it’s 32-bit or 64-bit?

Let’s see how easily we can do that with OSHI:

@Test
void givenSystem_whenUsingOSHI_thenExtractOSDetails() {
    SystemInfo si = new SystemInfo();
    OperatingSystem os = si.getOperatingSystem();

    assertNotNull(os, "Operating System object should not be null");
    assertNotNull(os.getFamily(), "OS Family should not be null");
    assertNotNull(os.getVersionInfo(), "OS Version info should not be null");
    assertTrue(os.getBitness() == 32 || os.getBitness() == 64, "OS Bitness should be 32 or 64");
}

The code creates a SystemInfo object from the OSHI library to access system-related details. It then retrieves the OperatingSystem instance, which provides information like the OS family, version, and bitness.

5.2. Checking System Uptime

Ever wondered how long our system has been running without a reboot? System uptime tells us just that:

@Test
void givenSystem_whenUsingOSHI_thenExtractSystemUptime() {
    SystemInfo si = new SystemInfo();
    OperatingSystem os = si.getOperatingSystem();

    long uptime = os.getSystemUptime();
    assertTrue(uptime >= 0, "System uptime should be non-negative");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        fail("Test interrupted");
    }
    long newUptime = os.getSystemUptime();
    assertTrue(newUptime >= uptime, "Uptime should increase over time");
}

Here, we retrieve the system uptime using OSHI by creating a SystemInfo object and accessing the OperatingSystem instance. The test first checks that the system uptime is non-negative, ensuring a valid value. Then, it pauses for two seconds using Thread.sleep(2000), handling interruptions. After the delay, it fetches the system uptime again, which can be used to verify that the uptime increases over time.

If we see something like 3600 seconds, our machine has been up for an hour.

6. CPU Monitoring with OSHI

The CPU (Central Processing Unit) is the heart of any system. Monitoring its usage, load, and core count is essential for performance tuning.

6.1. Getting Processor Details

OSHI makes it easy to fetch our processor’s name, core count, and clock speed using Java:
@Test
void givenSystem_whenUsingOSHI_thenExtractCPUDetails() {
    SystemInfo si = new SystemInfo();
    CentralProcessor processor = si.getHardware().getProcessor();

    assertNotNull(processor, "Processor object should not be null");
    assertTrue(processor.getPhysicalProcessorCount() > 0, "CPU must have at least one physical core");
    assertTrue(processor.getLogicalProcessorCount() >= processor.getPhysicalProcessorCount(),
      "Logical cores should be greater than or equal to physical cores");
}
This test initializes a SystemInfo object from OSHI and retrieves the CentralProcessor instance from the system’s hardware. The CentralProcessor provides details about the CPU, such as the number of cores, processor identifiers, and load metrics, though no assertions or validations are present in this snippet.

The method processor.getPhysicalProcessorCount() returns the number of physical CPU cores in the system. It ensures the system has at least one physical core, and processor.getLogicalProcessorCount() returns the number of logical processors, including hyper-threaded cores.

6.2. Measuring CPU Load Dynamically

If we want to check how busy our CPU is at a given moment, we can easily do so:

@Test
void givenSystem_whenUsingOSHI_thenExtractCPULoad() throws InterruptedException {
    SystemInfo si = new SystemInfo();
    CentralProcessor processor = si.getHardware().getProcessor();

    long[] prevTicks = processor.getSystemCpuLoadTicks();
    TimeUnit.SECONDS.sleep(1);
    double cpuLoad = processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100;

    assertTrue(cpuLoad >= 0 && cpuLoad <= 100, "CPU load should be between 0% and 100%");
}

The code captures the system’s CPU load ticks (prevTicks), waits for one second, and calculates the CPU load percentage between the recorded ticks using getSystemCpuLoadBetweenTicks(prevTicks) * 100. Finally, it asserts that the CPU load falls within the valid range of 0% to 100%, ensuring the correctness of the OSHI-reported CPU utilization.

A lower percentage means our CPU is idle, while a higher percentage indicates a high workload.

7. Memory Monitoring

Our system’s RAM (Random Access Memory) determines how many applications can run simultaneously.

7.1. Retrieving Total and Available RAM

Let’s see how we can retrieve the total and available RAM for our system:

@Test
void givenSystem_whenUsingOSHI_thenExtractMemoryDetails() {
    SystemInfo si = new SystemInfo();
    GlobalMemory memory = si.getHardware().getMemory();

    assertTrue(memory.getTotal() > 0, "Total memory should be positive");
    assertTrue(memory.getAvailable() >= 0, "Available memory should not be negative");
    assertTrue(memory.getAvailable() <= memory.getTotal(), "Available memory should not exceed total memory");
}

The code initializes a SystemInfo object and obtains the GlobalMemory instance, which provides memory-related information. It asserts that the total memory is positive, ensuring the system has valid RAM. It also checks that the available memory is non-negative and doesn’t exceed the total memory, validating OSHI’s memory reporting.

7.2. Storage and Disk Information

@Test
void givenSystem_whenUsingOSHI_thenExtractDiskDetails() {
    SystemInfo si = new SystemInfo();
    List<HWDiskStore> diskStores = si.getHardware().getDiskStores();

    assertFalse(diskStores.isEmpty(), "There should be at least one disk");

    for (HWDiskStore disk : diskStores) {
        assertNotNull(disk.getModel(), "Disk model should not be null");
        assertTrue(disk.getSize() >= 0, "Disk size should be non-negative");
    }
}
The code retrieves disk storage details using OSHI. It fetches the list of HWDiskStore instances, representing system disks. It ensures that at least one disk is present, then iterates through each disk, verifying that the model name isn’t null and the disk size is non-negative. This ensures OSHI correctly detects and reports disk information.

8. Limitations of OSHI

While OSHI is feature-rich, it does have some limitations:

  • Sensor data availability depends on hardware support: Not all machines expose temperature or voltage readings
  • Limited low-level control: OSHI provides read-only system insights; it doesn’t allow system modifications
  • Dependency on system APIs: Some information may vary slightly between operating systems

9. Conclusion

In this article, we saw that OSHI is a powerful yet lightweight Java library for retrieving system and hardware information. It eliminates the hassle of dealing with native system commands, JNI, or platform-specific dependencies, making it a great choice for developers who need cross-platform system monitoring.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments