Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

1. Introduction

In this quick tutorial, we’ll explore different causes and solutions for the UnsatisfiedLinkError. It’s a common and frustrating error encountered when working with native libraries. Resolving this error requires thoroughly understanding its causes and appropriate corrective measures.

We’ll discuss scenarios such as incorrect library and method names, missing library directory specifications, conflicts with classloaders, incompatible architectures, and the role of the Java Security Policy.

2. Scenario and Setup

We’ll create a simple class illustrating possible errors when loading external libraries. Considering we’re on Linux, let’s load a simple library called “libtest.so” and invoke its test() method:

public class JniUnsatisfiedLink {

    public static final String LIB_NAME = "test";

    public static void main(String[] args) {
        System.loadLibrary(LIB_NAME);
        new JniUnsatisfiedLink().test();
    }

    public native String test();

    public native String nonexistentDllMethod();
}

Usually, we’d want to load our library in a static block to ensure it’s only loaded once. But, to better simulate errors, we’re loading it in our main() method. In this case, our lib contains only one valid method, test(), which returns a String. We’re also declaring a nonexistentDllMethod() to see how our application behaves.

3. Library Directory Not Specified

The most straightforward reason for the UnsatisfiedLinkError is that our library isn’t in any directory that Java expects libraries to be in. That could be in a system variable, like LD_LIBRARY_PATH on Unix or Linux, or PATH on Windows. It’s also possible to use the full path of our library with System.load() instead of loadLibrary():

System.load("/full/path/to/libtest.so");

But, to avoid system-specific solutions, we can set the java.library.path VM property. This property receives one or many directory paths containing the library or libraries we need to load:

-Djava.library.path=/any/library/dir

The directory separator will depend on our OS. It’s a colon for Unix or Linux, and a semicolon for Windows.

4. Incorrect Library Name or Permissions

Probably the most common reason to get an UnsatisfiedLinkError is using an incorrect library name. That’s because Java, to keep code as platform-agnostic as possible, assumes a few things about the library name:

  • For Windows, it assumes the library file name ends in “.dll.”
  • For most Unix-like systems, it assumes a “lib” prefix and a “.so” extension.
  • Finally, specifically for Mac, it assumes a “lib” prefix and a “.dylib” (formerly “.jnilib”) extension.

So, if we include any of these prefixes or suffixes, we’ll get an error:

@Test
public void whenIncorrectLibName_thenLibNotFound() {
    String libName = "lib" + LIB_NAME + ".so";

    Error error = assertThrows(UnsatisfiedLinkError.class, () -> System.loadLibrary(libName));

    assertEquals(
      String.format("no %s in java.library.path", libName), 
      error.getMessage()
    );
}

Incidentally, this makes it impossible for us to try and load a library built for a platform different from the one we’re running our application on. In this case, if we want our application to be multi-platform, we’d have to provide binaries for all platforms. And if we only have a “test.dll” in our library directory in our Linux environment, a System.loadLibrary(“test”) will result in the same error.

Similarly, we’ll get an error if we include a path separator with loadLibrary():

@Test
public void whenLoadLibraryContainsPathSeparator_thenErrorThrown() {
    String libName = "/" + LIB_NAME;

    Error error = assertThrows(UnsatisfiedLinkError.class, () -> System.loadLibrary(libName));

    assertEquals(
      String.format("Directory separator should not appear in library name: %s", libName), 
      error.getMessage()
    );
}

Finally, having insufficient permissions on our library directory will result in the same error. For instance, we need at least the “execute” permission in Linux. On the other hand, if our file doesn’t have at least the “read” permission, we’ll get a message similar to this:

java.lang.UnsatisfiedLinkError: /path/to/libtest.so: cannot open shared object file: Permission denied

5. Incorrect Method Name/Usage

If we declare a native method that doesn’t match any of the declared methods in our native source code, we’ll also get the error, but only when we try to call the nonexistent method:

@Test
public void whenUnlinkedMethod_thenErrorThrown() {
    System.loadLibrary(LIB_NAME);

    Error error = assertThrows(UnsatisfiedLinkError.class, () -> new JniUnsatisfiedLink().nonexistentDllMethod());

    assertTrue(error.getMessage()
      .contains("JniUnsatisfiedLink.nonexistentDllMethod"));
}

Notice no exception is thrown in loadLibrary().

6. Library Already Loaded by Another Classloader

This will most likely happen if we’re loading the same library in different web apps in the same web app server (like Tomcat). Then, we’ll get the error:

Native Library libtest.so already loaded in another classloader

Or, if it’s in the middle of the loading process, we’ll get:

Native Library libtest.so is being loaded in another classloader

The simplest way to resolve this is to put the code for loading our library in a JAR in a shared directory in our web app server. For instance, that’d be “<tomcat home>/lib” in Tomcat.

7. Incompatible Architecture

This one is most likely when using old libraries. We can’t load a library compiled for a different architecture than the one on which we’re running our application — for instance, if we try to load a 32-bit library on a 64-bit system:

@Test
public void whenIncompatibleArchitecture_thenErrorThrown() {
    Error error = assertThrows(UnsatisfiedLinkError.class, () -> System.loadLibrary(LIB_NAME + "32"));

    assertTrue(error.getMessage()
      .contains("wrong ELF class: ELFCLASS32"));
}

In the example above, we linked our library with the 32-bit flag for testing purposes. A couple of side notes:

  • A similar error can happen if we try to load a DLL in a different platform by renaming the file. Then, our error will contain the “invalid ELF header” message.
  • If we try to load our library on an incompatible platform, the library just won’t be found.

8. Corrupted Files

A corrupted file will always result in an UnsatisfiedLinkError when attempting to load it. To illustrate this, let’s see what happens when we try to load an empty file (note that this test is simplified for a single library path and considers a Linux environment):

@Test
public void whenCorruptedFile_thenErrorThrown() {
    String libPath = System.getProperty("java.library.path");

    String dummyLib = LIB_NAME + "-dummy";
    assertTrue(new File(libPath, "lib" + dummyLib + ".so").isFile());
    Error error = assertThrows(UnsatisfiedLinkError.class, () -> System.loadLibrary(dummyLib));

    assertTrue(error.getMessage().contains("file too short"));
}

To avoid this, it’s common to distribute MD5 checksums along with binaries so we can check for integrity.

9. Java Security Policy

If we’re using a Java Policy file, we need to grant a RuntimePermission for loadLibrary() and our library name:

grant {
    permission java.lang.RuntimePermission "loadLibrary.test";
};

Otherwise, we’ll get an error similar to this when trying to load our library:

java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "loadLibrary.test")

Note that for a custom policies file to take effect, we need to specify that we want to use a security manager:

-Djava.security.manager

10. Conclusion

In this article, we explored solutions to address the UnsatisfiedLinkError in Java applications. We discussed common causes for this error and provided insights into resolving them effectively. By implementing these insights and tailoring them to the specific needs of our application, we can effectively resolve UnsatisfiedLinkError occurrences.

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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

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)