JNI w/ Threads = Crashes

Hi,
I am creating a Java app using JNI to call C++ libraries a vendor has provided for us. I used a pointer upon instantiation of the C++ object, store it in the Java side, and when I need to call a method in C, would de-reference that pointer to make function call.
This works well in a standalone Java application. However, when I use a thread to call this object, or a servlet, it will get as far as letting me make one function call in C, but other calls afterwards will cause a core dump.
Anyone experience this before? Please share any insight you might have. Thanks in advance.
-Justin
Here's the code:
=======================================
#include <jni.h>
#include <iostream.h>
#include "com_jni_JNIDSM_0005fServer.h"
#include "DSMC_Server.h"
//Java side: public static int cObjectID
static jobject cls = 0;
static jfieldID fid;
* Class: JNIDSM_0005fServer
* Method: DSM_Server
* Signature: ()I
* Create an instance of this object and return a reference handler (pointer).
* REQUIRED: Need to call this method first before DSM_Server object can be used.
JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_DSM_1Server
(JNIEnv* p_env, jobject p_obj)
DSMC_Server* server;
server = new DSMC_Server();
cout << "ServerPtr Created = " << (jint)server << endl;
Java_com_jni_JNIDSM_1Server_setCID(p_env, p_obj, (jint) server);
return ((jint) server);
* Class: JNIDSM_0005fServer
* Method: connect
* Signature: (Ljava/lang/String;ILjava/lang/String;I)I
* Create connection from the DSM Client to the Server. Pass in host & port of Server and
* name assigned to the module of the DSM Client.
JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_connect
(JNIEnv* p_env, jobject p_obj, jstring p_host, jint p_port, jstring p_serverModuleName)
// Obtain pointer reference to corresponding DSM objects
DSMC_Server* serverPtr = (DSMC_Server*)
Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
// Convert the Java String to a Char pointer for use
cout << "ServerPtr in JNI_connect() begin = " << (jint) serverPtr << endl;
jboolean isModCopy, isHostCopy;
const char* host = p_env->GetStringUTFChars(p_host, &isHostCopy);
const char* serverModuleName = p_env->GetStringUTFChars(p_serverModuleName, &isModCopy);
// Call the DSM_Server object's Connect() function
jint status = (*serverPtr).Connect (host, p_port, serverModuleName);
// Clean up object allocation for string copy after method is done
if (isHostCopy == JNI_TRUE)
p_env->ReleaseStringUTFChars(p_host, host);
if (isModCopy == JNI_TRUE)
p_env->ReleaseStringUTFChars(p_serverModuleName, serverModuleName);
cout << "ServerPtr in JNI_connect() after = " << (jint) serverPtr << endl;
return status;
* Class: JNIDSM_0005fServer
* Method: disconnect
* Signature: (I)V
* Disconnect from the Server.
JNIEXPORT void JNICALL Java_com_jni_JNIDSM_1Server_disconnect
(JNIEnv* p_env, jobject p_obj)
// Obtain pointer reference to corresponding DSM objects
DSMC_Server* serverPtr = (DSMC_Server*)
Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
cout << "ServerPtr in disconnect = " << (jint) serverPtr << endl;
// Call the DSM_Server object's Disconnect() function
(*serverPtr).Disconnect();
* Class: JNIDSM_0005fServer
* Method: doHeartbeat
* Signature: (I)I
* Check the status of the Server. Return status code that tells the caller Server' status.
JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_doHeartbeat
(JNIEnv* p_env, jobject p_obj, jint p_serverPtr)
// Obtain pointer reference to corresponding DSM objects
DSMC_Server* serverPtr = (DSMC_Server*)
Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
// Call the DSM_Server object's DoHeartbeat() function
jint status = (*serverPtr).DoHeartbeat();
return status;
* Class: JNIDSM_0005fServer
* Method: getMaxPacketSize
* Signature: (I)I
* Return the packet size that are being sent through this network connection.
JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_getMaxPacketSize
(JNIEnv* p_env, jclass p_class)
// Obtain pointer reference to corresponding DSM objects
DSMC_Server* serverPtr = (DSMC_Server*)
Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
// Call the DSM_Server object's GetMaxPacketSize() function
jint packetSize = (*serverPtr).GetMaxPacketSize();
return packetSize;
* Class: com_jni_JNIDSM_0005fServer
* Method: getCID
* Signature: ()J
JNIEXPORT jlong JNICALL Java_com_jni_JNIDSM_1Server_getCID
(JNIEnv* p_env, jobject p_obj)
jclass clazz;
clazz = p_env->GetObjectClass(cls);
fid = p_env->GetStaticFieldID(clazz, "cObjectID", "J");
jint id = p_env->GetStaticLongField(clazz, fid);
cout << "ServerPtr retrieved w/ getCID = " << id << endl;
return id;
* Class: com_jni_JNIDSM_0005fServer
* Method: setCID
* Signature: (J)V
JNIEXPORT void JNICALL Java_com_jni_JNIDSM_1Server_setCID
(JNIEnv* p_env, jobject p_obj, jint p_hndlr)
jclass clazz;
//create global reference
if (cls == 0) {
clazz = p_env->GetObjectClass(p_obj);
if (clazz == 0) {
cout << "Error occurred while getting class ref..."<< endl;
cls = p_env->NewGlobalRef(p_obj);
if (cls == 0) {
cout << "Error occurred trying to create Global ref..."<< endl;
fid = p_env->GetStaticFieldID(clazz, "cObjectID", "J");
} else
clazz = p_env->GetObjectClass(cls);
p_env->SetStaticLongField(clazz, fid, p_hndlr);
cout << "ServerPtr saved in setCID = " << p_hndlr << endl;
}

I have experience from the "other side" of JNI - calling into java from c - that may be relevant.
If a particular C thread uses JNI calls to create java objects, and another C thread accesses these java objects (or causes thier destruction), then a crash will ensue.
We use JNI extensively, and are now religious about making sure that only the thread that created an objects access it.

Similar Messages

  • JNI and Threads Crashes

    Hi,
    I am creating a Java app using JNI to call C++ libraries a vendor has provided for us. I used a pointer upon instantiation of the C++ object, store it in the Java side, and when I need to call a method in C, would de-reference that pointer to make function call.
    This works well in a standalone Java application. However, when I use a thread to call this object, or a servlet, it will get as far as letting me make one function call in C, but other calls afterwards will cause a core dump.
    Anyone experience this before? Please share any insight you might have. Thanks in advance.
    -Justin
    Here's the code:
    =======================================
    #include <jni.h>
    #include <iostream.h>
    #include "com_jni_JNIDSM_0005fServer.h"
    #include "DSMC_Server.h"
    //Java side: public static int cObjectID
    static jobject cls = 0;
    static jfieldID fid;
    * Class: JNIDSM_0005fServer
    * Method: DSM_Server
    * Signature: ()I
    * Create an instance of this object and return a reference handler (pointer).
    * REQUIRED: Need to call this method first before DSM_Server object can be used.
    JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_DSM_1Server
    (JNIEnv* p_env, jobject p_obj)
    DSMC_Server* server;
    server = new DSMC_Server();
    cout << "ServerPtr Created = " << (jint)server << endl;
    Java_com_jni_JNIDSM_1Server_setCID(p_env, p_obj, (jint) server);
    return ((jint) server);
    * Class: JNIDSM_0005fServer
    * Method: connect
    * Signature: (Ljava/lang/String;ILjava/lang/String;I)I
    * Create connection from the DSM Client to the Server. Pass in host & port of Server and
    * name assigned to the module of the DSM Client.
    JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_connect
    (JNIEnv* p_env, jobject p_obj, jstring p_host, jint p_port, jstring p_serverModuleName)
    // Obtain pointer reference to corresponding DSM objects
    DSMC_Server* serverPtr = (DSMC_Server*)
    Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
    // Convert the Java String to a Char pointer for use
    cout << "ServerPtr in JNI_connect() begin = " << (jint) serverPtr << endl;
    jboolean isModCopy, isHostCopy;
    const char* host = p_env->GetStringUTFChars(p_host, &isHostCopy);
    const char* serverModuleName = p_env->GetStringUTFChars(p_serverModuleName, &isModCopy);
    // Call the DSM_Server object's Connect() function
    jint status = (*serverPtr).Connect (host, p_port, serverModuleName);
    // Clean up object allocation for string copy after method is done
    if (isHostCopy == JNI_TRUE)
    p_env->ReleaseStringUTFChars(p_host, host);
    if (isModCopy == JNI_TRUE)
    p_env->ReleaseStringUTFChars(p_serverModuleName, serverModuleName);
    cout << "ServerPtr in JNI_connect() after = " << (jint) serverPtr << endl;
    return status;
    * Class: JNIDSM_0005fServer
    * Method: disconnect
    * Signature: (I)V
    * Disconnect from the Server.
    JNIEXPORT void JNICALL Java_com_jni_JNIDSM_1Server_disconnect
    (JNIEnv* p_env, jobject p_obj)
    // Obtain pointer reference to corresponding DSM objects
    DSMC_Server* serverPtr = (DSMC_Server*)
    Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
    cout << "ServerPtr in disconnect = " << (jint) serverPtr << endl;
    // Call the DSM_Server object's Disconnect() function
    (*serverPtr).Disconnect();
    * Class: JNIDSM_0005fServer
    * Method: doHeartbeat
    * Signature: (I)I
    * Check the status of the Server. Return status code that tells the caller Server' status.
    JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_doHeartbeat
    (JNIEnv* p_env, jobject p_obj, jint p_serverPtr)
    // Obtain pointer reference to corresponding DSM objects
    DSMC_Server* serverPtr = (DSMC_Server*)
    Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
    // Call the DSM_Server object's DoHeartbeat() function
    jint status = (*serverPtr).DoHeartbeat();
    return status;
    * Class: JNIDSM_0005fServer
    * Method: getMaxPacketSize
    * Signature: (I)I
    * Return the packet size that are being sent through this network connection.
    JNIEXPORT jint JNICALL Java_com_jni_JNIDSM_1Server_getMaxPacketSize
    (JNIEnv* p_env, jclass p_class)
    // Obtain pointer reference to corresponding DSM objects
    DSMC_Server* serverPtr = (DSMC_Server*)
    Java_com_jni_JNIDSM_1Server_getCID (p_env, p_obj);
    // Call the DSM_Server object's GetMaxPacketSize() function
    jint packetSize = (*serverPtr).GetMaxPacketSize();
    return packetSize;
    * Class: com_jni_JNIDSM_0005fServer
    * Method: getCID
    * Signature: ()J
    JNIEXPORT jlong JNICALL Java_com_jni_JNIDSM_1Server_getCID
    (JNIEnv* p_env, jobject p_obj)
         jclass clazz;
         clazz = p_env->GetObjectClass(cls);
         fid = p_env->GetStaticFieldID(clazz, "cObjectID", "J");
    jint id = p_env->GetStaticLongField(clazz, fid);
    cout << "ServerPtr retrieved w/ getCID = " << id << endl;
    return id;
    * Class: com_jni_JNIDSM_0005fServer
    * Method: setCID
    * Signature: (J)V
    JNIEXPORT void JNICALL Java_com_jni_JNIDSM_1Server_setCID
    (JNIEnv* p_env, jobject p_obj, jint p_hndlr)
         jclass clazz;
         //create global reference
         if (cls == 0) {
              clazz = p_env->GetObjectClass(p_obj);
              if (clazz == 0) {
    cout << "Error occurred while getting class ref..."<< endl;
              cls = p_env->NewGlobalRef(p_obj);
              if (cls == 0) {
    cout << "Error occurred trying to create Global ref..."<< endl;
              fid = p_env->GetStaticFieldID(clazz, "cObjectID", "J");
         } else
              clazz = p_env->GetObjectClass(cls);
    p_env->SetStaticLongField(clazz, fid, p_hndlr);
    cout << "ServerPtr saved in setCID = " << p_hndlr << endl;
    }

    Thanks Tom for your help.
    After further debugging and trying new ideas, it turns out to be something really weird within the actual C++ object. I did a very basic execution to just connect and disconnect from the server all within one function. Even with one function call, it would crash. I'm going back to the vendor to let them figure it out.
    I've done my own examples of allocating dynamic arrays, setting & getting values, then deallocating it. There were no problems with threads then.
    I know I'm not going wacky, hopefully not, but who knows. Thanks again.
    Here's the simple code that crashed within a Java thread:
    void SomeJNIFunction(<params>) {
    jboolean isModCopy, isHostCopy, isAppCopy;
    const char* host = p_env->GetStringUTFChars(p_sHost, &isHostCopy);
    const char* sModuleName = p_env->GetStringUTFChars(p_sModName, &isModCopy);
    const char* sAppName = p_env->GetStringUTFChars(p_sAppName, &isAppCopy);
    jint status = 0;
    DSMC_Server serverPtr;
    DSMC_Event eventPtr;
    cout << "In JNI, ready to connect. Host=" << host << "|ModName=" << sModuleName
    << "|AppName=" << sAppName << endl;
    // connection attempt
    status = serverPtr.Connect (host, p_iPort, sModuleName);
    cout << "(JNI) Connected ..." << endl;
    //*************crash!!!!!!!********
              serverPtr.Disconnect();
    }

  • How to cope with the case that a thread crash ?

    if a thread crash, how to notify other threads? Is there standard method to follow?

    Sounds like a job for Observer pattern. You'll have to handle the crash on your own though. Catch any exceptions and notify the observers.

  • JNI memory/thread issue

    Guys,
    Here's the problem I'ce seen with JNI and using the JVM in C++.
    I create AWT frames through a call to the constructor and access the window thro' call to the object.
    before a call to DeleteGlobalRef, I call a Java method from C++ that calls dispose on the Frame.
    I noticed that with time a lot of threads are not terminated and after a couple of creations and disposing of frames, the VM crashes.
    Any thoughts....
    Thanks.

    You have a problem in your code.
    If when you say "few" it means like 3-100, then the most likely explaination is you have buffer problem (over/under writing a buffer.) A problem like that does not cause problems until latter, sometimes much later, in the code.

  • Abstract class causes JNI GetByteArrayElements to crash

    I'm having a problem with a subclass of an abstract class that is accessing a JNI function. I'm using Java 1.4.2.
    I started out with a single class that reads data from a serial port (via a JNI call) and then parses the data. When I test this class, the read/parse works correctly.
    Since I have to create multiple parsing protocols, I decided to create an abstract class that contained the reading functionality and a subclass that parses the data. When I did this, the 1st call to GetByteArrayElement never returns (nor do I get a stack dump trace).
    I also tried making the super-class non-abstract and over-writing the prase method(s). I got a similar failure.
    I can't imagine what the issue might be - why would splitting the original object into two (superclass/subclass) cause such a problem?
    I've include relevent snippits of code.
    Thanks for the help!
    ===== JNI Code =====
    extern JNIEXPORT jint JNICALL Java_vp_jni_Serial_read (JNIEnv *env,
         jclass class, jint fd, jbyteArray buf, jint cnt, jint offset)
         jboolean     iscopy = JNI_FALSE;
         // FAILS ON CALL; NEVER RETURNS!!!!
         const jbyte *data = GetByteArrayElements (env, buf, &iscopy);
         const uchar     *b;
         int               num,
                        rc;
         b = (uchar *) &data[offset];
         num = cnt;
         do
              rc = read (fd, (char *) b, num);
              if (handleReadException (env, rc) != 0)
                   (*env)->ReleaseByteArrayElements (env, buf, (jbyte *) data, 0);
                   return rc;
              num -= rc;
              b += rc;
         } while (num > 0);
         (*env)->ReleaseByteArrayElements (env, buf, (jbyte *) data, 0);
         return cnt;
    }==== Java Native Calls ====
    public class Serial
         public int read (byte[] data, int length, int offset)
              throws IOException
              return read (fd, data, length, offset);
         private static native int read (int fd, byte[] buf, int cnt, int offset)
              throws IOException;
    }==== Abstract super-class ====
    package vp.parse;
    import java.io.IOException;
    import java.io.InterruptedIOException;
    import java.io.SyncFailedException;
    import vp.jni.Serial;
    import vp.jni.Exec;
    import vp.data.ControlData;
    public abstract class Parse extends Thread
         protected static final int     ERROR = -1;
         private static final int     LOC_TIMEOUT = 3000;
         private Serial          link;
         private int               port;
         private boolean          running = false;
         private int               baud = Serial.B9600;
         protected abstract void reset ();
         protected abstract void parse ();
         public Parse (int port, String id, int baud)
              this.port = port;
              this.baud = baud;
              start ();
              synchronized (this)
                   try
                        wait (5000);
                   } catch (Exception e)
                        System.out.println (id + " Thread failed to synchronize");
              System.out.println ("Done");
         public void run ()
              link = new Serial(port);
              try
                   link.open();
                   link.setBaud (baud);
                   link.setTimeout (LOC_TIMEOUT);
              catch (Exception e )
                   link = null;
                   return;
              running = true;
              synchronized (this)
                   notify ();
              while (running)
                   parse ();
         protected int read (byte[] buf, int packetSize, int offset)
              if (offset >= packetSize)
                   offset = 0;
              if (offset > 0)
                   for (int i=0; i<packetSize - offset; i++)
                        buf[i] = buf[offset+i];
                   offset = packetSize - offset;
              try
                   int cnt = link.read (buf, packetSize - offset, offset);
                   offset = 0;          // all data is good
              // ready to 'close down' executable
              catch (Exception exp)
                   running = false;
                   return ERROR;
              return offset;
    }==== Sub-class to handle parsing ====
    package vp.parse;
    public class Eis extends Parse
         private static final int     PACKET_SIZE = 3 + 69 + 1;     // hdr, data, csum
         private byte[]          buffer = new byte[PACKET_SIZE];
         private int               offset = 0;
         public Eis (int port)
              super (port, "GR EIS", Serial.B9600);
         protected void reset ()
              offset = 0;
         protected void parse ()
              do
                   offset = read (buffer, PACKET_SIZE, offset);
                   if (offset == ERROR)
                        offset = 0;
                        return;
                   // parse code here
              } while (parse failed);
         public static void main (String[] argv)
              Eis e = new Eis (3);
              try { Thread.sleep (10000); } catch (Exception x) {}
    }

    The issue was the following:
    I had declared a buffer in the sub-class;
    private byte[] buffer = new byte[PACKET_SIZE];
    And the assumption would be that by the time it got used, it would be initialized. But that's not the case. Why?
    The sub-class called the super class constructor. At this point in time, buffer[] is not valid.
    The super class constructor spawns the child thread and waits for the spawned thread to finish initialization.
    The spawned thread creates the serial port, informs the constructor it's 'done' and starts to parse incoming data.
    The parse() code is the sub-class passes the uninitialized buffer to the JNI code and GetByteArrayElements crashes because id doesn't like a null pointer.
    Since the parent thread doesn't regain control to finish the construction, buffer[] never gets initialized.
    So much for synchronized thread spawning in a constructor...

  • JNI + Timer, weird crash

    Hello people.
    First of all, I'd like to apologize beforehand for the long post. Also, I hope I'm posting on the right forum section.
    Here's the story:
    I'm working on an academic project, which involves a Java application calling C++ code, via JNI. I'm currently facing an issue, the exact cause of which I cannot track down, at least given my current grasp of Java, JNI, JVM etc.
    Before I get straight to the point, here's some background on the project, which I think may help in clarifying any possible subtleties of the problem. You can probably skip this paragraph safely though, and jump to the picture that is provided on the link below it, without missing too much. Basically, I'm working on implementing an AI (specifically Reinforcement Learning) experiment domain which is based on an open-source game, written in C++. A Java application (which can be thought of, as a platform for deploying AI experiments) is responsible for the control of the experiment execution, which is conducted on a step-by-step basis. The game is compiled as a dynamically loadable shared library, so that it can be loaded by a specific JNI component of the Java AI platform. Let me state at this point, that the Java application, as well as the JNI dynamic library loader that it features, were not implemented by myself. As a consequence, I'm not aware of the details concerning the JNI part of the implementation (I've peeked at the pure Java part though, and it seems pretty OK to me). My work lies on modifying the game code (C++), so that it can be integrated with the Java AI platform. The application features 2 modes of executing experiment steps. In the "manual" mode, a step is executed when a specific JButton is hit (I will henceforth refer to this execution mode, as JButton mode). On the other hand, there is a "batch" mode, where step execution is scheduled to happen on a fixed time interval, using the scheduleAtFixedRate method of the java.util.Timer class (Timer mode, henceforth). To make matters even more clear, here's a a sketch of the architecture of the system:
    [Sketch of the problem|http://users.auth.gr/~idaroglo/pub/fsitu.png]
    The problem is, that while the JButton mode works OK, the Timer mode doesn't. In that case, things crash on the native side (specifically on the OpenGL library, which is used to render the graphics of the game). This is quite weird I think, as the only difference between these 2 execution modes, is the way they call the native step function (I tried to illustrate in the picture linked above). So, a wild guess could be that something gets messed up, when the Timer gets involved in orchestrating the execution. I cannot put blame on the native shared library, as it functions properly in the case of the JButton mode. Having no other hint or indication of what causes this situation, I can only blame it on the Timer involvement (hence the thread title). I will post a sample JVM Hotspot crash log, as a reply to this one.
    Here are some things I've tried so far, to resolve this issue:
    1) Debugging with gdb. I tracked down which function of the OpenGL library causes the crash (btw, segmentation fault - SISEGV). I've been told by a fellow though, that this specific function cannot produce a segmentation fault and that the crash probably happens due to memory corruption. In case this speculation holds, a wild guess could be that the use of a timer, could be introducing memory corruption.
    2) I've skimmed through the JVM Troubleshooting guide, in the hope that I'll find some advice on how I should troubleshoot this situation. I'm bound to revisit this, hopefully after some feedback from the community.
    3) I've considered using valgrind to verify that memory corruption, but I'm not sure if that would make sense in the case of Java/JNI.
    4) I've tried setting the Timer's fixed time interval to a 20 seconds (20000ms), to make absolutely sure that the native method returns, before it is invoked by the timer for a consecutive time. Still things crash.
    5) I've tested the Java AI platform with a considerably simpler dynamic library (in terms of implementation), and both modes functioned OK. This probably indicates that I cannot blame it all, on the Timer alone.
    So, I would really appreciate some feedback on the following matters:
    1) Does any of the speculations above, concerning the cause of the problem, make sense to you?
    2) How should I proceed troubleshooting? Are there any recommended tools that might prove helpful in tracking down the cause of the problem?
    3) Should one employ extra care when using Timers in combination with JNI & native methods?
    4) How can one track down and troubleshoot memory corruption issues in the mixed mode scenario (JAVA+JNI)?
    That's all. Thanks for the time you spent reading this. Once more, I sincerely apologize for the long post.
    I really hope that collective experience and wisdom, will help me squash this issue.
    Thanks again.

    Hello again!
    Sorry to revive this thread after a long time, but this post might be helpful to anyone that might encounter a similar problem in the future.
    I am obliged to Paul Pluzhnikov, for identifying the cause of the problem. Wouldn't it be for his invaluable help, I would still have been stuck with this one.
    I quote part of his response, a while ago:
    Paul Pluzhnikov wrote:
    ....JVM log has register dump as well, and
    RAX=0x0000000000000000 in it. So your program tried to jump through a
    NULL pointer, and crashed with SIGSEGV since zero page of memory is
    not mapped into the process space on Linux.
    The more interesting question is "why is RAX NULL?"
    RAX was loaded in the previous instruction from the FS (thread-local
    storage on x86_64) segment register.
    Given all of the above, I will guess that the difference between the
    "JButton" and "Timer" execution is that in the "JButton" case you
    execute the call to JNI/game_step in the event dispatch thread, while
    in the "Timer" case you are not.
    The following (buggy) program demonstrates what I believe is
    essentially the same crash:
    // compile with "gcc -g main.c /usr/lib/libGL.so.1 -pthread"
    #include <pthread.h>
    #include <stdio.h>
    void *fn(void *p)
    printf("calling glHint on other thread\n");
    return glHint();
    int main(int argc, char *argv[])
    pthread_t tid;
    if (argc > 1) {
    printf("calling glHint on main thread\n");
    return glHint();
    pthread_create(&tid, 0, fn, 0);
    pthread_join(tid, 0);
    return 0;
    }Here is what I see on my system:
    gdb -q ./a.out
    (gdb) run
    [Thread debugging using libthread_db enabled]
    Using host libthread_db library "/lib/libthread_db.so.1".
    [New Thread 0x7ffff7ed4720 (LWP 19872)]
    [New Thread 0x40802950 (LWP 19875)]
    calling glHint on other thread
    Program received signal SIGSEGV, Segmentation fault.
    [Switching to Thread 0x40802950 (LWP 19875)]
    0x00007ffff7db62c9 in glHint () from /usr/lib/libGL.so.1
    (gdb) x/i $pc
    0x7ffff7db62c9 <glHint+9>:     jmpq *0x378(%rax)
    (gdb) p $rax
    $1 = 0 Notice the same instruction crash, and the same RAX == NULL (gdb) run 1
    [Thread debugging using libthread_db enabled]
    [New Thread 0x7ffff7ed4720 (LWP 19877)]
    calling glHint on main thread
    Program exited normally.
    (gdb) quitSo how do you fix this? The following may be helpful:
    [http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html] A few days later, I got some further input from Paul. I quote part of it as well, as I think it might also prove to be helpful for someone:
    Paul Pluzhnikov wrote:
    You probably don't actually have to jump through hoops to get the
    "game" executing on the event dispatch thread.
    What I think must happen is that the dlopen() of the "game" must
    be done in the same thread that the "step" will be done in.
    Alternatively, you may be able to force libGL to initialize its
    TLS storage for arbitrary thread, by using glXMakeCurrent.
    Here is some additional info which may be helpful:
    [http://www.equalizergraphics.com/documentation/parallelOpenGLFAQ.html]
    [http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/glx/xmakecurrent.html]
    I'd like to thank all of you, who provided any sort of input on this. Most of all, I'd like to thank Paul Pluzhnikov once more, for figuring the problem out.
    Hope this post will be helpful to someone in the future!
    Cheers!

  • JNI native thread priority

    Hi,
    I have some JNI code that spawns a win32 thread using CreateThread and then sets it priority using SetThreadPriority.
    If i set priority higher than ABOVE_NORMAL ( i would prefer time critical), it seems the JVM crashes on exit.
    I've commented everything out in the thread method itself except to let it do a while(true){Sleep(1);}.
    If i remove the SetThreadPriority or set it to ABOVE_NORMAL or less the JVM doesnt crash when the java code calls System.exit but otherwise it does.
    Any ideas concerning this?

    Hmm..
    I was using System.runFinalizersOnExit(true), when i removed that from the java side the problem disappeared. I dont really need to make that call anyway, but i dont like when errors disappears and i dont understand why, so i would like to know how that call in conjunction with a high priority native thread can cause a jvm crash?

  • JNI native threads causing JRE to fail to shut down?

    Hello,
    I am using JNI to communicate with a COM object. I am reasonably certain at this point that my JNI code is handling this properly and the third party COM library is releasing the object in question. We allocate and release hundreds of these objects and we aren't observing any memory leaks. Likewise in our handling of events we receive from the COM object. We attach the thread to Java, deliver the event, and then detach the thread from Java, with very careful error handling around the event delivery to ensure that whatever else happens the detach gets called. This code is very robust and stable in operation and has been working at load in the field for over a year now without any customer problems in the JNI area.
    However, since day one, when I go to shut down the application, the JNI isn't winding down properly. As it happens, since the JRE is running a Tomcat, driven by a wrapper service, the wrapper eventually gives up waiting and shoots the JRE in the head, but the user experience of stopping the wrapper service is ugly and we'd like to clean that up. The JNI code, of course, runs as shared code in the Tomcat.
    It is possible that the third-party library, which does network communications, is keeping a thread pool for use with any of the COM objects even after all COM objects are released. This would be experienced as a one-time hit when the first object is allocated and not as a continual leak, so we'd be unlikely to notice it otherwise.
    Will native non-Java threads running in the JRE but not allocated by the JRE itself cause the JRE to hang on until they've spontaneously decided to clean themselves up? Threads that have never been attached to the JVM? How about threads that were briefly attached to the JVM but then detached? Any worse?
    Ralph

    Hi Ralph,
    I will need some more information regarding this issue.
    1. What platform are you on?
    2. Which JRockit version are you running?
    3. If you remove the wrapper service, does JRockit freeze without exiting properly?
    As a general recommendation I would try to upgrade to the latest JRockit version. It can be downloaded from the OTN http://www.oracle.com/technology/software/products/jrockit/index.html
    You may also try some verbose printouts to debug the issue a little further. Try
    -Xverbose:thread=debug,jni=debug
    This might give us some more insight in what is going on.
    Also when JRockit freezes you can output a Java stack trace using our 'jrcmd' tool which you can find in the same folder as the java executable. Run this tool without any parameters and it will output identifiers (numbers) for every running JRockit instance on your machine. Run the same tool again, this time append the identifier you believe is the one running the Tomcat and add the command 'print_threads', ie
    jrcmd <some_id_here> print_threads
    This may show what JRockit is waiting for.
    Cheers,
    /Henrik

  • JNI+Linux+threads+Invocation=BUG?

    I have a very simple java program from Rob Gordon's JNI book. All the program does is create a thread that prints a text message periodically. However, the thread never starts if try to invoke the program from a C++ program using JNI. It will just hang forever.
    The program works fine if I invoke it with javac on Linux. It also works fine if I use JNI to invoke it from a C++ program on
    Windows 2K.
    Is this a JNI bug on Linux? Is there a workaround to it? Has anyone successfully created threads from a java program that was invoked from a C++ program on Linux?
    I've tried jdk1.3.0, 1.3.0, and 1.4.0 using various combinations of
    classic/libjvm.so, client/libjvm.so, and server/libjvm.so (whatever the difference may be) with no success.
    Below is the source:
    // InvokeWithThread.java
    import java.lang.Exception
    public class InvokeWithThread {
        public static void main(String[] args) {
            System.out.println("Hello from InvokeWithThread");
            SleepyThread s = new SleepyThread();
            s.start();
    class SleepyThread extends Thread {
        public void run() {
            int cnt = 0;
            try {
                while (cnt < 10 {
                    sleep(1000,0);
                    System.out.println("sleepy running...");
                    cnt++;
            } catch (Exception e) []
    }Any information on this topic is greatly appreciated.

    I too have same problem, but only on dual processor linux system.
    It works fine for single processor. I am using C++ for jni code.

  • Causing the JNI code to crash "properly"

    Hi,
    I have some code written in C and liked to Java using JNI.
    When I run it (even from the Visual C++ environment) and the code gets an exception in C, the JVM catches it and closes up nicely with an error.
    What can I do to remove this behavior and let it crash - this will cause Visual C++ debugger to catch it and show me where the crash is.
    Thanks,
    Tsahi

    Hi,
    I've got 2 problems with this:
    1. I'm writiing code in pure ANSI C - so try/catch doesn't work for me in the long run - just as a way of debugging a specific problem.
    2. I need something that will crash - not something that will get over it, but something that will be able to show me the exact problem, along with a backtrace, values of variables, and the ability to use a debugger to check the memory while I'm at it.
    I will try it though, so thanks a lot

  • Mail - why does this thread crash when accessing a gmail imap account

    Thread 13 Crashed:
    0 libSystem.B.dylib 0x91ed8b9e __kill + 10
    1 libSystem.B.dylib 0x91f4fec2 raise + 26
    2 libSystem.B.dylib 0x91f5f47f abort + 73
    3 com.apple.MessageFramework 0x0047552e sqlite3_traceCallback + 0
    4 com.apple.MessageFramework 0x00368e6d +[Library insertOrUpdateMessages:withMailbox:fetchBodies:isInitialImport:oldMessagesByNew Message:remoteIDs:newDocumentIDs:setFlags:clearFlags:messageFlagsForMessages:cop yFiles:progressDelegate:updateRowIDs:] + 2332
    5 com.apple.MessageFramework 0x00368548 +[Library addMessages:withMailbox:fetchBodies:isInitialImport:oldMessagesByNewMessage:rem oteIDs:setFlags:clearFlags:messageFlagsForMessages:copyFiles:] + 146
    6 com.apple.MessageFramework 0x003684ae +[Library addMessages:withMailbox:fetchBodies:isInitialImport:oldMessagesByNewMessage:] + 127
    7 com.apple.MessageFramework 0x00368428 +[Library addMessages:withMailbox:fetchBodies:oldMessagesByNewMessage:] + 75
    8 com.apple.MessageFramework 0x00367e27 -[LibraryThread _runThread] + 1412
    9 com.apple.CoreFoundation 0x94f5da7d _invoking__ + 29
    10 com.apple.CoreFoundation 0x94f5d468 -[NSInvocation invoke] + 136
    11 com.apple.MessageFramework 0x003d74c8 -[MonitoredInvocation invoke] + 409
    12 com.apple.MessageFramework 0x003d838a +[WorkerThread _execute:] + 144
    13 com.apple.Foundation 0x949a8bad -[NSThread main] + 45
    14 com.apple.Foundation 0x949a8754 _NSThread__main_ + 308
    15 libSystem.B.dylib 0x91e9b6f5 pthreadstart + 321
    16 libSystem.B.dylib 0x91e9b5b2 thread_start + 34

    No idea.  Are you using any mail plugins of any sort?  MailTags or Letter Opener or Attachment Tamer anything else?

  • Just another 'ATI KMS' thread - crash by console or X shutdown

    Hi!
    I'm one of those who is trying to get my Radeon HD 3200 working with early KMS and Arch x64 on my HP touchsmart tx2.
    While the last versions worked either not at all or a little bit so X could start the current one seems to be a bit more stable. But nevertheless I experience a very strange behaviour: When trying to switch to a console (CTRL + ALT + F[1..6]) the screen just gets blank and the whole systems seems to crash. When trying to shutdown and X is closed the same happens and the shutdown doesn't occur. Unfortunately accelleration doesn't work as well. Might there be a mistake I made? I don't understand the line of the Xorg log marked with '(*)' by me at all. What's that about?
    Package versiosn I am using that might be interesting:
    kernel26 2.6.32.2-2
    xf86-video-ati 6.12.4-3
    xorg-server 1.7.3.902-1
    dri2proto 2.1-1
    lib32-mesa 7.7-1
    mesa 7.7-1
    lib32-libdrm 2.4.17-2
    libdrm 2.4.17-2
    libgl 7.7-1
    xf86driproto 2.1.0-1
    Currently I neither use the radeon module nor hook nor the firmware hook for the initial ramdisk.
    glxgears (from which I know it isn't a benchmark at all) runs with about 415 fps.
    Output of compiz-check:
    Gathering information about your system...
    Distribution: Arch Linux
    Desktop environment: GNOME
    Graphics chip: ATI Technologies Inc RS780M/RS780MN [Radeon HD 3200 Graphics]
    Driver in use: radeon
    Rendering method: AIGLX
    Checking if it's possible to run Compiz on your system...
    Checking for texture_from_pixmap... [ OK ]
    Checking for non power of two support... [ OK ]
    Checking for composite extension... [ OK ]
    Checking for FBConfig... [ OK ]
    Checking for hardware/setup problems... [FAIL]
    There has been (at least) one error detected with your setup:
    Error: Software Rasterizer in use
    'Radeon' part of the X log:
    (II) RADEON(0): vgaHWGetIOBase: hwp->IOBase is 0x03d0, hwp->PIOOffset is 0x0000
    (==) RADEON(0): RGB weight 888
    (II) RADEON(0): Using 8 bits per RGB (8 bit DAC)
    (--) RADEON(0): Chipset: "ATI Radeon HD 3200 Graphics" (ChipID = 0x9612)
    (--) RADEON(0): Linear framebuffer at 0x00000000c0000000
    (II) RADEON(0): PCI card detected
    (II) Loading sub module "int10"
    (II) LoadModule: "int10"
    (II) Loading /usr/lib/xorg/modules/libint10.so
    (II) Module int10: vendor="X.Org Foundation"
    compiled for 1.7.3.902, module version = 1.0.0
    ABI class: X.Org Video Driver, version 6.0
    (II) RADEON(0): initializing int10
    (II) RADEON(0): Primary V_BIOS segment is: 0xc000
    (II) RADEON(0): ATOM BIOS detected
    (II) RADEON(0): ATOM BIOS Rom:
    SubsystemVendorID: 0x103c SubsystemID: 0x3045
    IOBaseAddress: 0x5000
    Filename: BR31147.bin
    BIOS Bootup Message:
    HP_Soyuz30 RS780M DDR2 200e/500m
    (II) RADEON(0): Framebuffer space used by Firmware (kb): 20
    (II) RADEON(0): Start of VRAM area used by Firmware: 0x13ffb000
    (II) RADEON(0): AtomBIOS requests 20kB of VRAM scratch space
    (II) RADEON(0): AtomBIOS VRAM scratch base: 0x13ffb000
    (II) RADEON(0): Cannot get VRAM scratch space. Allocating in main memory instead
    (II) RADEON(0): Default Engine Clock: 500000
    (II) RADEON(0): Default Memory Clock: 400000
    (II) RADEON(0): Maximum Pixel ClockPLL Frequency Output: 1200000
    (II) RADEON(0): Minimum Pixel ClockPLL Frequency Output: 0
    (II) RADEON(0): Maximum Pixel ClockPLL Frequency Input: 13500
    (II) RADEON(0): Minimum Pixel ClockPLL Frequency Input: 1000
    (II) RADEON(0): Maximum Pixel Clock: 400000
    (II) RADEON(0): Reference Clock: 14320
    drmOpenDevice: node name is /dev/dri/card0
    drmOpenByBusid: Searching for BusID pci:0000:01:05.0
    drmOpenDevice: node name is /dev/dri/card0
    drmOpenDevice: open result is 10, (OK)
    drmOpenByBusid: drmOpenMinor returns 10
    drmOpenByBusid: drmGetBusid reports pci:0000:01:05.0
    (EE) RADEON(0): [dri] RADEONDRIGetVersion failed because of a version mismatch.
    [dri] radeon kernel module version is 2.0.0 but version 1.17.0 or newer is needed.(*)
    [dri] Disabling DRI.
    (II) RADEON(0): using shadow framebuffer
    (II) Loading sub module "shadow"
    (II) LoadModule: "shadow"
    (II) Loading /usr/lib/xorg/modules/libshadow.so
    (II) Module shadow: vendor="X.Org Foundation"
    compiled for 1.7.3.902, module version = 1.1.0
    ABI class: X.Org ANSI C Emulation, version 0.4
    (II) RADEON(0): Detected total video RAM=327680K, accessible=262144K (PCI BAR=262144K)
    (--) RADEON(0): Mapped VideoRAM: 262144 kByte (128 bit DDR SDRAM)
    (II) RADEON(0): Color tiling disabled
    (II) RADEON(0): ref_freq: 1432, min_out_pll: 64800, max_out_pll: 120000, min_in_pll: 100, max_in_pll: 1350, xclk: 40000, sclk: 500.000000, mclk: 400.000000
    (II) RADEON(0): PLL parameters: rf=1432 rd=12 min=64800 max=120000; xclk=40000
    (II) Loading sub module "fb"
    (II) LoadModule: "fb"
    (II) Loading /usr/lib/xorg/modules/libfb.so
    (II) Module fb: vendor="X.Org Foundation"
    compiled for 1.7.3.902, module version = 1.0.0
    ABI class: X.Org ANSI C Emulation, version 0.4
    (II) RADEON(0): Memory manager initialized to (0,0) (2048,8191)
    (II) RADEON(0): Reserved area from (0,2048) to (2048,2050)
    (II) RADEON(0): Largest offscreen area available: 2048 x 6141
    (II) RADEON(0): RADEONRestoreMemMapRegisters() :
    (II) RADEON(0): MC_FB_LOCATION : 0x00cf00c0 0x00cf00c0
    (II) RADEON(0): MC_AGP_LOCATION : 0x003f0000
    (==) RADEON(0): Backing store disabled
    (WW) RADEON(0): Direct rendering disabled
    (EE) RADEON(0): Acceleration initialization failed
    (II) RADEON(0): Acceleration disabled
    (==) RADEON(0): DPMS enabled
    (==) RADEON(0): Silken mouse enabled
    (II) RADEON(0): Will use 32 kb for hardware cursor 0 at offset 0x01004000
    (II) RADEON(0): Will use 32 kb for hardware cursor 1 at offset 0x01008000
    (II) RADEON(0): Largest offscreen area available: 2048 x 6137
    (II) RADEON(0): Textured video requires CP on R5xx/R6xx/R7xx/IGP
    Do you have any idea what the problem(s) might be?
    Thank you in advance!

    KMS is still enabled in the kernel, it's just libdrm that needs to be recompiled. And then mesa and xf86-video-ati need to be recompiled against that. In other words it's a huge pain. The package versions I'm using now that get decent radeon kms framerates are:
    kernel26-2.6.31.6
    libdrm-2.4.16
    xf86-video-ati-git-20091008
    mesa-7.6
    xorg-server-1.6.3.901
    And I refuse to upgrade until I can upgrade and still have KMS. Thanks to a combination of "Arch doesn't want to support KMS" and "Dave Airlie despite his best intentions makes the driver more prone to crash on my system with every git push" my IgnorePkg list is now a page long.

  • JNI & thread problem

    Folks,
    I am using JNI to access WIA (Windows Image Acquisition) functionality under MS Windows XP. WIA consists of a bunch of COM interfaces. I have several native functions in a single dll, with a limited number of static variables stored in the dll between calls. This all works fine as long as long as the calls occur from the same java thread, but not if a new thread is created for some of the calls. I.e., this works:
    final WIACtrl ctrler=new WIACtrl();
    ctrler.initializeWIA();
    ctrler.transferJPGNative("0001\\Root\\IMG_0087","c:\\test.jpg");
    but this does not:
    final WIACtrl ctrler=new WIACtrl();
    ctrler.initializeWIA();
    (new Thread() {
    public void run() {               
    ctrler.transferJPGNative("0001\\Root\\IMG_0087","c:\\test.jpg");
    }).start();
    Here, initializeWIA() and transferJPGNative() are the native methods. What happens in the second case is that transferJPGNative fails in one of the COM methods (not the first COM method it calls). The COM method returns an HRESULT indicating an error (509) which I can't find using any of the usual MS error look-up mechanisms. (Admittedly I am not the world's greatest Windows programmer...)
    Anyway, any suggestions would be much appreciated. I have found some issues regarding JNI and threads in this forum's archives, but none of them seem to apply to quite this situation.

    As a guess this is just a windows threading problem.
    And with COM you have to do things differently (I believe) if there is more than one thread. You might not even be allowed to do it with for that particular API.
    It could also be that you are initializing things more than once. Or you need to initialize twice (two handles.)
    At any rate you could always fix it by making the java code only allow calls for a single thread.

  • JNI calls only work if sent from main thread?!?

    Hi,
    I searched through the forum for a couple of hours now, and found that a lot of developers seem to have problems with JNI and threads. However, I couldn't find a solution to my problem so far...hope you can help!
    We need to send requests to a DDE Server from our Java application. For that reason, we implemented a very small DLL using Delphi, which calls the DDE Server and returns the result as a string. Using JNI, we call this DLL from Java.
    Everything works fine, as long as we call the DDE Server (via JNI and the DLL) from the main thread of the Java application. But everytime we call it from another Java thread, our DDL reports that it can't get a connection to the DDE Server. This is especially awkward if you want to make calls as a reaction to GUI events, since then the call is sent by the Event Dispatch Thread of the Java runtime.
    This does not seem to be a multi-threading problem, since we do never send multiple requests at the same time. It simply depends on the thread, from which the call is sent.
    Any hints are appreciated very much.
    Thanks!
    Thilo

    We are a step further now...thus the problem to be solved changed a little bit.
    The former assumption, that connecting to the DDE server does only work from the main thread was false. It only seemed like that, because we called System.loadLibrary() to in the main thread to load the DLL . In fact, the connection to the DDE server works from any thread - you just have to make sure that System.loadLibrary() is invoked in this same thread.
    This means: if System.loadLibrary() is invoked in the Event Dispatch Thread, we can call the DDE Server from this thread, which is what we primarily wanted to do. So our problem is solved.
    Anyway, I made some more tests to find out, what happens if I start multiple threads, with each of them calling System.loadLibrary(). The result was, that only the first thread is successful. This means: the first thread, which loads the DLL is the only thread that is able to connect to the DDE server. All other threads won't get a connection.
    What could be the reason for that?

  • Can not locate Java class using JNI within C++ DLL

    I am using trying to use JNI to call a Java class from C++. The Java class uses JMS to send messages to a JMS message queue. At first I coded the C++ in a console application that created the JavaVM and used JNI to access the Java class. All worked fine. Then I called the Java class using JNI from threads and ran into the problem of the Java class not able to locate the JMS related classes. This was solved by placing the following line in the constructor of the Java class.
    Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
    Then I moved the JNI code from a console application to a DLL in specific an extension DLL that is called by SQL Server or Oracle server. The DLL will use JNI to call the Java class and send messages to a JMS message queue.
    The problem I am having now when the DLL code is called by SQL Server the call to
    JNI_CreateJavaVM
    appears to work correctly but the call to find the Java class using
    jvmEnv->FindClass(pName)
    fails. It appears the is a class loading problem which occurs due to the fact JNI is called from a DLL. When the VM is created I pass the class path information using the statement
    -Djava.class.path=
    And as I stated before it all works when running from a console application. I am new to JNI and really need help in the form of some sample code that will solve this problem. I believe I need to somehow load the classpath information from the DLL but I can not find examples on how to do this using JNI. I have tried several ways using URLClassLoader and getSystemClassLoader from JNI and either it does not work or it crashes very badly.
    I used the following code to determine what the existing class path is and the string returns empty.
    jcls = jvmEnv->FindClass("java/lang/System");
    jmid = jvmEnv->GetStaticMethodID(jcls, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
    jstrClassPath = jvmEnv->NewStringUTF("java.class.path");
    jstr = (jstring)jvmEnv->CallStaticObjectMethod(jcls, jmid, jstrClassPath);
    m_jstr = (jstring)jvmEnv->NewGlobalRef(jstr);
    pstr = jvmEnv->GetStringUTFChars(m_jstr, 0);
    Can anyone please help with example code that will solve this problem. Thanks in advance for any help.
    Charles�

    I have determined the problem occurs when the application/component is compiled using VC 6.0. The test application was compiled using VC 7.1 and works correctly by locating the class path information. If the test application is compiled using VC 6.0 it has the same problem.
    The jvm.dll I am using is version 1.4.2.80. Currently this is not an option to compile all the applications that use JNI using VC 7.1 so can someone please tell me how to solve this problem.

Maybe you are looking for

  • GR w/o PO

    Gurus, When can mvmt type 501 used?What happens & what is the FI impact?

  • No Optimized web browser support on basic phones after 8/30/13?

    Over the weekend I received a very disturbing message on my web browser. of my Samsung Gusto 2. It said that there would be no Optimized  web browser support on basic phones after 8/30/13 and that if I wanted a good web browsing experience that I wou

  • Unable to see the discussion

    Hello, I am unable to see my discussion posted today with the following subject; "How to restrict MIGO (GR) and Reservation (MB21-221 Q) if WBS element is technically closed" Please help in finding the reason / solution. thanks

  • Recover a non-botable V440 server

    All, I have a SunFire V440, I was trying to compile a apache module mod_auth_mysql as root. Since then I am experiencing "Runtime Linker Failure". The message I got is "cannot execute /usr/lib/ld.so.1, Killed", when I was doing a "ls". Not for too lo

  • Fonts behave different in Photoshop in comparison with Illustrator

    I have a problem: it seems that some fonts behave different in Photoshop CS than in Illustrator CS on my Windows XP. Where Illustrator opens a vector (Ill) EPS file correct Photoshop shows me wrong characters sometimes: for example: an é becomes a wr