Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI DeleteLocalRef Clarification

Question 1:

jstring jstrKey;
for(int i=1;i<=1000;++i) {
    LPWSTR strKey = L"string";
    jstrKey = env->NewString((jchar *)strKey, wcslen(strKey));
}
env->DeleteLocalRef(jstrKey);

Question 2:

for(int i=1;i<=1000++i) {
    LPWSTR strKey = L"string";
    jstring jstrKey = env->NewString((jchar *)strKey, wcslen(strKey));
    env->DeleteLocalRef(jstrKey);
}

Am i using DeleteLocalRef properly in both questions?

Especially in Question 1, I am deleting local ref after the loop. I think that is correct, and need not call deletelocalref inside the loop since I am not creating any new local ref.

So no issues with respect to usage of DeleteLocalRef right?

like image 585
Praveen Kumar Avatar asked Jun 18 '14 15:06

Praveen Kumar


2 Answers

In both cases you should call DeleteLocalRef() inside the loop because each NewString() crerates a new local ref.

Local references will be discarded by JNI on return from a native method, but this process has nothing to do with Java garbage collection. Usually, we don't need to worry about local references. But the local ref table is usually quite small, therefore we must discard unused references which are created on a significantly long loop.

like image 114
Alex Cohn Avatar answered Oct 13 '22 19:10

Alex Cohn


The first loop is certainly not correct, but the incorrectness may be benign. It isn't the same thing.

like image 22
user207421 Avatar answered Oct 13 '22 18:10

user207421