Java: Load the same dynamic library into two threads (both threads in the same JVM)

I am using a library (written in C) that is not reentrant (i.e. no function in the library exists). Suppose I loaded the library through System.load to get the descriptor "v". I cannot use v in two threads due to reload problems (verified but meaningless results). I could use locks, but that defeats any parallelism I could get.

What I would like to do is start two threads, and in each thread load the library to get two different handles (there are two copies of the loaded library).

Is this possible in Java? Regards Saptarshi

+4
source share
3 answers

Any DLL can only be loaded once by a process, so I don’t think you can achieve what you want. Could you trick and rename a DLL under a different name?

Do your threads spend so much time in a DLL that there is no other parallelism that will have?

+2
source

It's impossible. This would be equivalent to using POSIX dlopen , etc. To dynamically load multiple copies of the C / C ++ library into a C / C ++ program, and this will not work either.

Your main options:

  • modify the C library to make it thread safe

  • transcode it in (thread safe) Java

  • Transfer it as an application and run multiple copies as separate processes.

  • wrap it as a service and start several copies by talking to it using Sockets or the corresponding higher-level RPC engine.

+2
source

This is not possible. The System.loadLibrary method does not contain any arguments or documentation that would indicate that you could load the library depending on the stream or load the same library twice.

If you have a certain number of threads, you can create several libraries with slightly different naming schemes. Otherwise, you probably should just implement locks.

+1
source

All Articles