Search code examples
javadlljna

Is there a limit in loading dynamic libraries in JAVA using JNA?


Good morning,

We are executing the following code and we are reaching an error message when loading a certain number of dlls:

File file = new File("C:\\Users\\jevora\\Downloads\\dng_tests\\dllsCopies");
    file.mkdirs();
    for (int i = 1; i < 10000; i++) {
        String filename = "heatedTankCvode" + i + ".dll";
        Files.copy(new File("C:\\Users\\jevora\\Downloads\\dng_tests\\heatedTankCvode.dll").toPath(),
                new File(file, filename).toPath(), StandardCopyOption.REPLACE_EXISTING);
        NativeLibrary.getInstance(new File(file, filename).getAbsolutePath());
        System.out.println("Loaded: " + filename);
    }

As you can see here, we want to load 10,000 dlls using JNA. However,in the following log, the process stops at loading the instance 1,051:

Loaded: heatedTankCvode1048.dll
Loaded: heatedTankCvode1049.dll
Loaded: heatedTankCvode1050.dll
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'C:\Users\jevora\Downloads\dng_tests\dllsCopies\heatedTankCvode1051.dll': Native library (win32-x86-64/C:\Users\jevora\Downloads\dng_tests\dllsCopies\heatedTankCvode1051.dll)

About the code, first we copy the dll in a new location with a different name and, then, we try to load it. We wonder if there is a limitation to the amount of dlls that can be loaded. Is there a limitation? can we overcome it?

Thanks in advance

EDIT: I've tried with several memory configurations and it always stop in the 1051 instance


Solution

  • I think that the cause might be explained by this old Microsoft Forum post:

    It appears that each DLL that you are loading is consuming a TLS (thread local storage) slot. There is a per process limit of 1088 on the number of TLS slots. From all that I have read, the limit is hard ... and there is no way to increase it.

    From what I have read, a DLL doesn't have to use TLS, so you should investigate if you can change the way that your DLLs are created so that they don't do this.