通过 JNA 调用本机库时的并发问题

发布于 2024-11-28 14:16:01 字数 409 浏览 1 评论 0原文

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

应用程序在多个并发线程中调用我的插件,因此共享库由这些并发线程调用,自然地,它会由于并发而产生许多错误(例如:已打开的文件被阻止打开等)

我正在访问共享库通过 JNA。我什至有这个共享库的源代码,但转换为线程安全库将非常耗时,而且目前是不可能的。 还有其他建议的方法来解决这个问题吗?

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陈甜 2024-12-05 14:16:01

是的,使用同步将是一个有效的解决方案。

如果您这样做并且仍然看到并发访问,那么有(至少)两个可能的原因:

  • 您并不总是在同一个对象上同步(例如您的方法是同步的,但它是非静态的,并且在不同的对象上调用)或
  • 加载具有本机调用的类的多个实例(实际上这是第一个实例的子类型)。

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).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文