简体   繁体   English

多个Java线程使用Java Native Access进行多个方法调用

[英]Multiple method calls using Java Native Access by multiple Java threads

I am calling for eg getServer() method implemented in C++ library using JNA which takes input parameter and connects to server and return the server object. 我正在调用使用JNA在C ++库中实现的getServer()方法,该方法接受输入参数并连接到服务器并返回服务器对象。 I am calling above native method using different Java threads. 我正在使用不同的Java线程调用上述本机方法。 And this native method uses some global variables where native method is implemented. 并且此本机方法使用一些实现本机方法的全局变量。

I have declared native method in Native.h file as extern "C" and implementing native method in Native.cpp file. 我在Native.h文件中将本机方法声明为extern“ C”,并在Native.cpp文件中实现了本机方法。 This method is standalone method ie not part of any class or structure. 此方法是独立方法,即不属于任何类或结构的一部分。

So my query here is, if there are some global variables present in Native.cpp, are their value being changed from different Java threads which calls same native method? 因此,我的查询是,如果Native.cpp中存在一些全局变量,它们的值是否从调用相同本机方法的不同Java线程更改?

Are their value being changed from different Java threads which calls same native method? 它们的值是否从调用相同本机方法的不同Java线程更改?

Sure, the global variables will be shared by all virtual machine then by threads as well, let's write a very simple example to proof that: 当然,全局变量将由所有虚拟机然后由线程共享,让我们写一个非常简单的示例来证明:

counter.c 计数器

#include<stdio.h>

int counter = 0;
int incrementAndGet(){
    counter++;
    return counter;
}

Calling it in java using JNA 使用JNA在Java中调用

final ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 20; i++) {
    executorService.submit(() -> {
        try {
            TimeUnit.MILLISECONDS.sleep((long) (Math.random() * 1000));
        } catch (InterruptedException e) {}
        System.out.printf("thread=%s, counter=%d%n", Thread.currentThread().getName(), CounterLib.INSTANCE.incrementAndGet());
    });
}
executorService.awaitTermination(10, TimeUnit.SECONDS);
executorService.shutdown();

output 输出

thread=pool-1-thread-2, counter=1
thread=pool-1-thread-4, counter=2
thread=pool-1-thread-1, counter=3
thread=pool-1-thread-5, counter=4
thread=pool-1-thread-2, counter=5
thread=pool-1-thread-3, counter=6
thread=pool-1-thread-2, counter=7
thread=pool-1-thread-4, counter=8
thread=pool-1-thread-1, counter=9
thread=pool-1-thread-2, counter=10
thread=pool-1-thread-5, counter=11
thread=pool-1-thread-3, counter=12
thread=pool-1-thread-5, counter=13
....

You also must worry about concurrency at this global variables, or at java or at c, in the two is not necessary, then if you are just reading values from the global variables then you must not worry about concurrency. 您还必须担心在此全局变量,在java或c处并发是没有必要的,因此,如果您只是从全局变量中读取值,则不必担心并发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM