Concurrency issue while calling a native library v

2019-07-05 15:53发布

问题:

For an existing java application (which I do not have the source code) I am developing a plug-in which is calls a shared library. Unfortunately this shared library (written in C) is not thread safe.

The application is calling my plugin within several concurrent threads hence the shared library is called by these concurrent threads and naturally it gives many errors due to concurrency ( e.g: already open files are prevented from being opened etc)

I am accessing the shared library via JNA. I even have the source code of this shared library but converting to a thread-safe library will be time consuming and is currently not possible. Are there other suggested ways to overcome this issue?

All native functions are accessed from only one Java method so I think that making this method synchronized could be the solution. Would you agree?

I have tried this, but unfortunately the issue is not solved. In the log file I still see that the Java method is called concurrently and hence my own efforts to solve this have failed.

回答1:

Yes, using synchronization would be a valid solution to this.

If you do that and still see concurrent access then there are (at least) two possible causes:

  • you don't always synchronize on the same object (for example your method is synchronized, but it is non-static and called on different objects) or
  • multiple instances of the class with the native call are loaded (actually this is a sub-type of the first one).