Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about multithreading using JNI.

 
Aji Prasetyo
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

I don't know if this has been asked before, but I wonder if it is possible to run two (or maybe more) native-method concurrently?

If it is possible, how to do that? How is it different from the java tutorial of concurrent programming?

Thank you.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can run as many native methods as you like concurrently. There is nothing special about native methods that would prevent this.

If your native methods access shared native data or resources, then you must ensure that appropriate synchronisation is in place to make this thread-safe. You can take several approaches to this: -

  • Make the native methods themselves thread-safe, using native threading facilities (e.g. Posix thread library)
  • Make the native methods thread-safe, but use the JNI threading facilities. JNI lets you lock and unlock the monitors of Java objects, for instance.
  • Make the native methods as thread-unsafe, but make them private. Wrap them in Java code that uses Java threading facilities to provide a thread-safe Java public API.
  • Document the native methods as thread-unsafe and leave it up to client code to put appropriate synchronisation in place. Actually, this is often the best way, as it gives maximum flexibility - but you must be careful to document exactly what the client code needs to do.


  • You can also have your native code fire up native threads, which run outside the visibility of Java. Or you can attach them to the JVM, using JNI functions.
     
    Aji Prasetyo
    Ranch Hand
    Posts: 65
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks a lot for the reply.

    In that case, I think I am gonna let the Java side program do all the multithreading since I am not familiar with Native code (C++) multithreading.

    Thank you.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic