通过JNA调用本机库时出现并发问题 [英] Concurrency issue while calling a native library via JNA

查看:478
本文介绍了通过JNA调用本机库时出现并发问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于现有的Java应用程序(我没有源代码),我正在开发一个称为共享库的插件. 不幸的是,这个共享库(用C 编写)不是线程安全的.

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)

我正在通过JNA 访问共享库.我什至拥有该共享库的源代码,但是转换为线程安全的库将非常耗时,并且目前无法实现. 还有其他建议的方法可以解决此问题吗?

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?

只能从一个Java方法访问所有本机函数,因此我认为使此方法同步是解决方案.你同意吗?

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?

我已经尝试过了,但是不幸的是这个问题没有解决.在日志文件中,我仍然看到并发调用Java方法,因此我自己解决该问题的努力失败了.

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.

推荐答案

是的,使用同步将是对此的有效解决方案.

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

如果您这样做并且 still 看到并发访问,则有(至少)两种可能的原因:

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

  • 您不一定总是在同一个对象上进行同步(例如,您的方法是synchronized,但是它是非静态的,并且在不同的对象上被调用)或
  • 已加载带有本机调用的类的多个实例(实际上,这是第一个实例的子类型).
  • 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).

这篇关于通过JNA调用本机库时出现并发问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆