DeleteGlobalRef

Hi,
I have a question. If I call DeleteGlobalRef to delete a
reference for the second time, will the JVM ignore the
second call or will it leak memory??

As the documentation doesn't say, I would imagine anything may happen - including nasal demons flying out your nose, or perhaps a nasty letter sent to your mother. Don't do it.
God bless,
-Toby Reyelts

Similar Messages

  • Does DeleteGlobalRef(saved reference) delete all global references?

    Hello,
    I have a question regarding global references, if you assign two global references to the same object by....
    static jbobject savedReference, sameSavedReference Object,
    savedReference = env->newGlobalRef(obj);
    sameSavedReference = env->newGlobalRef(obj);
    then you call
    env->DeleteGlobalRef(savedReference);
    savedReference = null;
    sameSavedReference = null;
    When does the java object with the pointer sameSavedReference get garbage collected?
    Does the env->newGlobalReference hold a reference onto the same object, even if we called deleteGlobal with savedReference?
    Do you need to call also?
    env->DeleteGlobalRef(sameSavedReference);
    I know that if you try to access sameSavedReference after
    env->DeleteGlobalRef(savedReference);
    savedReference = null;
    sameSavedReference is no longer valid, however that could just mean that the global reference got deleted, and you need to resign sameSavedReference to another global reference.
    Whew this is confusing :) Any help would be appreciated!
    Tom

    I'm taking a guess :-) but I think if the references are different then they should be deleted. If the references are different, even if to the same object, I would think the deleteGlobalRef tells the JVM to remove that reference. I hope someone wiser will confirm :-)

  • Problem with JNI for target armlinux

    Dear friends,
    We have compiled CVM for ARM Linux and it is working fine for java programs as well as C programs.
    But when I try to make shared library out of a sample hello world JNI program for arm linux it says 'jni.h: No such file or directory' and after that many lines 'syntax error' and 'parse error' etc.
    But the same program is running fine on x86 linux. Problem only while cross compiling for arm linux. It is not problem with arm-v5t-le-gcc because that is working fine. Problem is with what I need to include in makefiles.
    As I am new to this domain could anyone help me where I am missing?
    Regards
    Kishore

    I'm not exactly sure what you're talking about, but it sounds like you may need to look into global references. Look at NewGlobalRef() and DeleteGlobalRef() and see if those help you out.
    God bless,
    -Toby Reyelts
    For all your JNI woes, check out Jace - http://jace.reyelts.com/jace

  • Problem with jni references

    i have to implement a few standard APIs. As a part of the implementation I have to provide references to an object I create. Now my underlying code is C++ with JNI used to throw the Java APIs. Problem is JNI now returns different references for the same object and hence my prupose id defeated. Could anyone suggest how this problem can be overcome.

    I'm not exactly sure what you're talking about, but it sounds like you may need to look into global references. Look at NewGlobalRef() and DeleteGlobalRef() and see if those help you out.
    God bless,
    -Toby Reyelts
    For all your JNI woes, check out Jace - http://jace.reyelts.com/jace

  • 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.

  • Correct JNI_OnLoad JNI_OnUnLoad approach for cacheing jvm ref?

    Currently am successful in calling a C API from Java. What am basically trying to do here is catch an event in C program, and callback the Java instance, to handle it in my Java code (Similar to a event handling in Swing).
    I have implemented the event handling in Windows in C, and will be implementing it soon for Linux and Mac, but how do I cache jvm reference? As far as i searched in other forums, I realize the need for implementing JNI_OnLoad and JNI_OnUnLoad functions in C.
    But am a bit confused in the concept of global references.
    JavaVM *cached_jvm;
    JNIEXPORT jint JNICALL myJavaClassCallback() {
    jclass Class_myclass;
    jmethodID MID_myclass_mymethod;
    #ifdef JNI_VERSION_1_2
    res = (*cached_jvm)->AttachCurrentThread(cached_jvm, (void**)&env, NULL);
    #else
    res = (*cached_jvm)->AttachCurrentThread(cached_jvm, &env, NULL);
    #endif
    if (res < 0) {
    printf("Attach failed\n");
    return;
    Class_myclass = (*env)->FindClass(env, "mypackage.MyClass");
    if (Class_myclass == NULL) {
    goto detach;
    MID_myclass_mymethod = (*env)->GetStaticMethodID(env, Class_myclass, "myMethod", "(Z)V");
    if (MID_myclass_mymethod == NULL) {
    goto detach;
    jboolean jbool = JNI_FALSE;
    (*env)->CallStaticVoidMethod(env, cls, MID_myclass_mymethod, jbool);//Correct?
    detach:
    if ((*env)->ExceptionOccurred(env)) {
    (*env)->ExceptionDescribe(env);
    (*jvm)->DetachCurrentThread(jvm);
    JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM jvm, void reserved) {
    JNIEnv *env;
    cached_jvm = jvm; /* cache the JavaVM pointer */
    if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_2)) {
    return JNI_ERR; /* JNI version not supported */
    return JNI_VERSION_1_2;
    JNIEXPORT void JNICALL JNI_OnUnload(JavaVM jvm, void reserved) {
    //Should i implement some delete reference here???
    I have two questions here.
    One, should i call some delete reference (or some function like deleteallrefereces (??)[if available]) on JNI_OnUnload?
    And two is my passing of jboolean argument correct?
    Thanks,
    Sreram

    <quote>
    You're not using global references. Your question?
    </quote>
    Oops! I realize now am not using global references. But i have two questions regarding global and local references.
    One, If we create a global reference, and use it in our program, how and when do we delete the reference? When, the answer might be after the reference is no longer in use, but if the reference is used all over the c code, should we delete it manually using DeleteGlobalRef in Unload function? Should DeleteLocalRef be called in every method, where the reference might be used?
    And two, why the code
    <quote>
    static jclass stringClass = NULL;
    jmethodID cid;
    jcharArray elemArr;
    jstring result;
    if (stringClass == NULL) {
    stringClass = (*env)->FindClass(env,"java/lang/String");
    if (stringClass == NULL) {
    return NULL; /* exception thrown */
    /* It is wrong to use the cached stringClass here, because it may be invalid. */
    cid = (*env)->GetMethodID(env, stringClass, "<init>", "([C)V");
    </quote>
    is wrong? I understand the above code is wrong as the stringClass variable here may become invalid and Garbage collector might have removed the variable from memory, but what i don't understand is how will it become invalid when the variable is still used in the same method?
    <quote>No.</quote>
    I understand i mustn't delete any references as i haven't used any global references, but my question was regarding the local and global references i stated above.
    <quote>Yes, but you don't actually need the variable, just pass JNI_FALSE directly as the argument.</quote>
    I knew it. But just wanted to confirm as in my actual code, i will be passing boolean argument based on the condition i determine, at runtime.
    <quote>Yes, if there is such a thing. Yes.</quote>
    The reason i asked this question is, I am using 1.6 version, but am giving 1.2 .. Is it like it will compare with version 1.2 and return true if version is 1.2 or higher?

  • Scope of GlobalRef

    I was wondering what the scope of a Global reference to an object in JNI. I have read two different references and they seemed to contradict each other.
    In the example below would jmanager be visible outside this JNI function??
    static jobject jmanager;
    JNIEXPORT void JNICALL Java_stuff(JNIEnv *env, jobject obj, jobject jmanager) {
    if (jmanager == 0) {
        jclass jlocalRef = env->GetObjectClass(manager)     ;
        if (jlocalRef == 0 ) {
             return -5; //Could not get object.
        }//end if
      jmanager= env->NewGlobalRef(jlocalRef);
      if (jmanager == NULL) {
            return -1; //out of memory;
      }//end if
      }//end if
    return 1;
    JNIEXPORT void JNICALL Java_useStuff(JNIEnv *env, jobject obj) {
       //Initialize Java object
    //**WILL THIS WORK jmanager
      jclass cls = env->GetObjectClass(jmanager);
      //Get and call setNumPoints (JAVA)
      jmethodID mid = env->GetMethodID(cls, "setNumPoints", "(I)V");
      if (mid == NULL) {
         printf("Could not find setNumPoints method");
                         return -1;
       }//end if
       env->CallVoidMethod(routeMgr, mid, pntCount);

    Have you tried it out? That code looks ready to run.
    Not sure what you mean by "scope" and "visible". In C/C++ language terms, yes that static variable will be in scope and visible from both functions, assuming all are in the same translation unit (file). There's nothing specific to JNI about that.
    Of if you are really asking "what is the lifespan of the Java object associated with the jmanager reference variable, after creating the reference via NewGlobalRef?" then the answer is that the object remains alive and ineligible for garbage collection until you later call DeleteGlobalRef on the reference. Hopefully you don't have any documentation indicating otherwise -- it's kinda important!
    -slj-

  • Do I need to delete JavaVM or JNIEnv pointers?

    In JNI do I need to either delete the pointers or call DeleteGlobalRef for them?
    JavaVM* theVM;
    jint JNI_Onload(JavaVM *vm, void *reserved)
          theVM = vm;
          return JNI_VERSION_1_4;
    //When done in native function, should I do either:
          //delete theVM;
          //delete env;
    //or this:
          //env->DeleteGlobalRef( theVM );

    The Sun VM will not exit a process space once started.
    So cleaning up the resources associated to the VM instance itself is pointless.
    And it might cause the application to fail.

  • JNI freeing local references

    We're using JNI to receive data from a native callback function. The native side creates local references, but does not use the DeleteLocalRef function. This works fine with the SUN JRE.
    However, the IBM JRE gets a stack overflow exception.
    According to IBM, we should delete the local references, but this requires a total rewrite of our program.
    Unfortunately, the JNI documentation is not very clear on this topic. In our understanding, the local references are being released automatically once they are out of scope.
    Is it really necessary to delete the local references or is there a bug in the IBM JRE ?
    Sample program :
    ==============
    // JNITest.java
    interface INativeNotification
    public void nativeCallBack();
    class JNITest implements INativeNotification
    private long counter;
    public native void nativeInitialize(INativeNotification callbackNotification);
    static {
    System.loadLibrary("JNITest");
    public void nativeCallBack() {
    System.out.println("JNITest CallBack " + counter++);
    public void run() {
    nativeInitialize(this);
    counter = 0;
    while(true)
    try {
    Thread.sleep(1000);
    } catch(Exception e) {
    public static void main(String[] args) {
    JNITest jnitest = new JNITest();
    jnitest.run();
    // JNITest.cpp : Defines the entry point for the DLL application.
    #include "stdafx.h"
    #include "JNITest.h"
    static DWORD dwThreadId;
    static HANDLE hThread;
    static HANDLE volatile hInitCompleteEvent;
    static bool volatile bLoop = true;
    static JavaVM *jvm = NULL;
    static jobject nativeNotification;
    BOOL APIENTRY DllMain( HANDLE hModule,
    DWORD ul_reason_for_call,
    LPVOID lpReserved )
    return TRUE;
    bool DoNativeCall(JNIEnv *env)
    jclass cls = env->GetObjectClass(nativeNotification);
    jmethodID callbackMethod = env->GetMethodID(cls, "nativeCallBack", "()V");
    env->CallVoidMethod(nativeNotification, callbackMethod);
    if ( env->ExceptionOccurred() )
    env->ExceptionDescribe();
    env->ExceptionClear();
    printf("Native code got exception calling nativeCallBack\n");
    return(false);
    return(true);
    DWORD WINAPI JNIThread( LPVOID lpParam )
    JNIEnv *env = NULL;
    jvm->AttachCurrentThread((void**)&env,NULL);
    SetEvent(hInitCompleteEvent);
    while (bLoop)
    if (!DoNativeCall(env))
    bLoop = false;
    Sleep(1);
    env->DeleteGlobalRef(nativeNotification);
    jvm->DetachCurrentThread();
    return 0;
    * Class: JNITest
    * Method: nativeInitialize
    * Signature: ()V
    JNIEXPORT void JNICALL Java_JNITest_nativeInitialize(JNIEnv *env, jobject object, jobject _nativeNotification)
    DWORD dwThrdParam = 0;
    env->GetJavaVM(&jvm);
    nativeNotification = env->NewGlobalRef(_nativeNotification);
    hInitCompleteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    hThread = CreateThread( NULL, 0, JNIThread, &dwThrdParam, 0, &dwThreadId );
    if (hThread == NULL)
    env->DeleteGlobalRef(nativeNotification);
    return;
    WaitForSingleObject(hInitCompleteEvent, INFINITE);

    Hi,
    First of all, thank you for your time and interest.
    Let me first recapitulate the history of this problem :
    We have a C interface for controlling our HW boards. A few years ago, we wrote a java interface for one of our customers. This JNI wrapper was certified for the SUN JRE and has been used for several years now without a problem. There are several java and native callback functions in this wrapper and our development team took some design decisions (e.g. no DeleteLocalRef's, re-fetching the jclass and methodID in the callback functions, ...).
    Recently, one customer asked us to use this wrapper with the IBM JRE. At first, there seemed to be no porting issues. However, after running for a very long time, we had a stack overflow.
    Our customer reported this problem to IBM and finally, after sending a sample program (see my first post), IBM confirmed that there was a problem in their JVM. They provided a fix, but this fix only deleted local references which were created in a GetObjectClass call. After providing a few other fixes which did not provide a proper solution either, they suddenly changed their strategy and claimed that we have to delete all the local references which are created in a thread, otherwise we're not JNI compliant.
    However, when we look in the IBM JVM diagnostics guide (Chapter 6 : Understanding the Java Native Interface, see http://www-106.ibm.com/developerworks/java/jdk/diagnosis/), they provide the following code as a sample for loosing local references, resulting in the underlying object being garbage collected.
    jobject myJNIfunc1 ()
    return env->NewObject ();
    void myJNIfunc2 ()
    jobject obj;
    obj = myJNIfunc1 ();
    .. -> no local reference to obj exists, and the garbage collector can collect it
    Are we interpreting the IBM JVM diagnostics guide wrong or is there a problem in the IBM JVM ?
    The SUN JVM deletes the local references properly.

  • How to maintain reference across native calls?

    I'm using JNI to interface with an underlying C++ communications library. I am having trouble keeping my connection valid across native calls.
    For example, in one method I connect and save the connection in a global variable, then return. After I connect I would like to call a "send message" method, but when I do I doesn't recognize the saved connection.
    My question is do saved references persist across JNI calls when using the same object, or will all global vars be new ones? If not, does anyone know a way to get around this?
    Thanks for your help

    All JNI references that you create (through calls to NewObject, GetObjectArrayElement, GetObjectField, ...) or that are passed to your native code as parameters are local. That means that they are only valid for the duration of that native call and only on the thread from which that native call was invoked.
    You can create global references from local references using NewGlobalRef. A global reference is valid across all threads and does not have a limited lifetime. You must make sure to release your global references once you are done using them by calling DeleteGlobalRef.
    God bless,
    -Toby Reyelts
    Check out Jace, http://jace.reyelts.com/jace

  • Really Stupid VM Crash

    I'm at the end of my tether with this very simple piece of JNI code.
    All I want to do is set a field's value in a return object, but when I call env->GetFieldID(), the whole VM crashes out. If I comment out the line, it runs fine (exception and error checks removed for brevity):
    C++
    jclass DVNoteDAO_class = env->FindClass("com/foldingrain/av/capture/DVNoteDAO");  // Works perfectly
    // Comment out this line, and the VM runs fine.  Leave it in and it crashes...
    jfieldID timecodeFieldId = env->GetFieldID(DVNoteDAO_class, "timecode", "Ljava/lang/String;");Java
    package com.foldingrain.av.capture;
    class DVNoteDAO {
        public String timecode;
    }Any ideas?

    exception and error checks removed for brevityInclude them, as what you've posted seems fine.
    Usually the pattern I follow is:jclass class_foo_bar_data_Hierarchic = NULL;
    jclass get_IDs_foo_bar_data_Hierarchic(JNIEnv *aJNIEnv) {
      if (!class_foo_bar_data_Hierarchic) {
        // get the class ID
        jclass    classID = aJNIEnv->FindClass("foo/bar/data/Hierarchic");
        if (!classID) return 0;
        // store the class globally
        class_foo_bar_data_Hierarchic=(jclass)(aJNIEnv->NewGlobalRef(classID));
        if (!class_foo_bar_data_Hierarchic) return 0;
        // get the member data field IDs
        field_foo_bar_data_Hierarchic_name =
          aJNIEnv->GetFieldID(class_foo_bar_data_Hierarchic, "name", "Ljava/lang/String;");
        if (!field_foo_bar_data_Hierarchic_name) {
          aJNIEnv->DeleteGlobalRef(class_foo_bar_data_Hierarchic);
          class_foo_bar_data_Hierarchic=NULL;
          return 0;
    ... So the bulk of the code is in the exceptions and error checks.
    Pete

  • Lifetime of JNI objects between calls.

    Is it possible to store/cache non-class JNI objects between calls?
    I know I can 'lock' jclass object to *env however I need to be able to do more than this.
    Implementation :
    C++ code for which I am not responsible for NOR will I ever get access to the source code needs to be built into a Java Application.
    Everything that I need to do works fine except when I need to have jobject's and, in particular, the JNIEnv reference to be cached in the dll between JNI calls.
    Raison d'etre : I want to implement a Callback using a Java object (Observer/Observable) so that the status of the C legacy app can be monitored via a callback implemented as part of the dll.
    Java object is called via the C callback, sets status via a status method called via JNI, Java App is notifoed of the change.
    Problem, as long as the first call the the jobject occurs within the actual JNI call that creates the Java object all is well, as soon as I try and store the jobject and JNIEnv references so that the C callback can call it as well then things break.
    Is it possible to have JNI objects whose lifetime spans JNI calls at all?

    In the meantime I have found out exactly how to achieve callbacks via native/Java. Having studied Sheng Liang's book (an absolute must buy and read) things became a lot clearer.
    This is what I discovered...
    The main issues with implementing callbacks within a JNI framework are the following..
    Lifetime of the JNIEnv and other classes/objects involved on the native side of the process.
    Threading issues on the native side, especially when interacting with Objects created in a different thread.
    The first issue is dealt with, in part, by being able to obtain a valid JNIEnv at arbitrary points in the native code. If you obtain a valid JNIEnv in an arbitrary native thread that JNIEnv is valid in it so this also helps problems with the second issue.
    The key to obtaining a valid JNIEnv is in having a reference to the calling VM.
    The function..
    JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
    allows you to cache a reference to the calling JVM. It is called when the dll is loaded before any other functions in the native code are called. The JavaVM reference is valid throughout the lifetime of the dll's instance.
    you can then do this to obtain a valid JNIEnv anytime you like..
    JNIEnv *env;
    vm->GetEnv((void **)&env, JNI_VERSION_1_2);
    Ok, thats dealt with problem of obtaining valid JNIEnv's when we need them.
    In order to extend the lifetime of objects and, in particular, classes from which those objects are instantiated you need to create global ref's to them. I did mine this way..
    In the calling Java code, I instantiate a callback object and pass that to a native method whose native code does the following..
    gets the object's class as a local reference, creates a NewGlobalRef of the passed object and its class. These jobject and jclass global references are stored as global vars in the DLL. You can also, at this point, create jmethodID's for all the methods you may need to call as part of the callback process however callbacks should finish as quickly as possible so restrict your calls to the minimum. Caching the method ID does not require a global ref, nor is is thread 'sensitive'. GetMethodID can be used to store a local jmethodID reference in a global jmethodID var, this saves you some time and performance hits in the native callback functions.
    The above description deals with the lifetime of objects between JNI calls. What about the threading issues?
    We have seen how to get a valid JNIEnv when we want one. This JNIEnv is valid for the NATIVE thread in which we call vm->GetEnv((void **)&env, JNI_VERSION_1_2);
    There is another way of getting valid JNIEnv's when we want them but this seems only to work when we are using the invocation interface (having the native side create an embedded JVM). This is the jvm->AttachCurrentThread function. I have tried both, only GetEnv seems to work as expected in the native DLL code, AttachCurrentThread when the JVM is invoked from inside a native application.
    To successfully perform the native/Java callback, assuming you have cached a JavaVM reference and the callback object/class correctly, is to get a valid JNIEnv as shown above, use this JNIEnv for the method calls you need to perform on the callback object, cleanup if needed.
    Note, you MUST DeleteGlobalRef's before the DLL is unloaded. If you don't you may find your Java VM crashing on exit (a horrible bug to have to track down).
    Either explicitly create a cleanup native method that you have to call and/or use the JNI_OnUnload function that is called just before the DLL is unloaded (usually when the JVM is being stopped).
    Things you can do to make your callback efficient :
    Make the calls return as soon as possible. I use the Observable/Observer pattern so that further Java objects (the observers) can handle the changes made to the callback object. If, like me, you are reflecting state changes in the native system component via callbacks and displaying them in a GUI environment then your Observer can wake up a thread to do the GUI updates, the observable callback need only notifyObservers in order to start things off and return.
    Hope this clears things up for you, if you have further questions please mail me, I believe my email address is available, if not post here and I will get to you.

Maybe you are looking for

  • CS4 Premiere Pro Clips Won't Play in Source Monitor/Program Monitor

    I can't get clips to play in source monitor/program monitor/preview pane in Pr Pro.  I have spent hours looking through the forums to try and find a fix and I have troubleshot the following..... 1. Codecs are not broken... or seem to be working accor

  • Procurement of non stock items without using material master?

    Hi Experts My company follows third party scenerio with non stock items . The procurement process starts from creating a PR thru network by entering a material master and other purchasing information in component overview. I have come to know from so

  • DAQ USB6215 でのアナログデータRead

    LabVIEW Ver8.0.1.DAQ USB6215を使用して.データの収集を行っていますが. スタートしてから2秒間程.データが読み取れません. プログラム手順 1.「DAQmx Create Task.vi」(自動クリア=TRUE)にて.タスクを作成. 2.「DAQmx Create Task.vi」(自動クリア=FALSE)にて.出力されたタスクを使用し. 「DAQmx Create Channel (AI-Voltage-Basic).vi」にてチャンネルを作成. 3.「DAQmx

  • How to create this fade effect

    I'm trying to create this fade effect in Dreamweaver 2004 and would appreciate any assistance. http://smallbusiness.smh.com.au/ It's the blue and light orange fade half-box surrounding the "Management or Sales & Marketing or Show me information on:"

  • Why wont my USB ports work?

    Hello, this is my first post and i am after a little help. i am having problems with my usb ports, i have a k8neo platinum mobo. i have usb ports on that, i have two front usb ports and i have a 4 four in a pci slot. a few weeks back they work workin