title: How to safelly call a C++ function by JNA from multiple threads?
body: <p>I use JNA to call a function in a dynamic library written in C++. I noticed that a segmentation fault occurs when the C++ function in the library is called from multiple threads.</p>
  
  <p>My question is how to call a C++ function <strong>in parallel</strong> via JNA without segmentation fault. In my C++ code, nothing of outside data is referenced, so I believe executing the C++ function in parallel is possible.</p>
  
  <p>I'm sure that multi-threading is the cause of the segmentation fault because making the method synchronized suppressed the problem. In other words. In other words, I know that adding a <code>synchronize</code> or using <code>Native.synchronizedLibrary()</code> resolve the segmentation fault by executing the C function in serial way. However, I hope to run the C++ function in parallel due to performance issue.</p>
  
  <pre><code>public static interface MyCLibrary extends Library{
     ...
  }
  
  public static class RunnerClass implements Runnable{
  
    public void run(){
      callCfunc()
    }
  
    // Making this method synchronized suppress the error
    public void callCfunc(){
      MyCLibrary INSTANCE =  (MyCLibrary)Native.loadLibrary(MyCLibrary.JNA_LIBRARY_NAME, MyCLibrary.class);
      INSTANCE.cFunc()
    }
  }
  
  public static class MainClass {
    public static void main(){
        // When numThread = 1, the error does NOT occurr
        int numThread = 2;
        ExecutorService es = Executors.newFixedThreadPool(numThread);
        for (int i = 0; i &lt; numThread; i++) {
            es.execute(new RunnerClass()));
        }
        es.shutdown();
        try {
            es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
  
    }
  }
  </code></pre>