Friday, July 17, 2015

JNI Error: Local reference table overflow


If you are working on JNI, you may have faced issue:

"Local reference table overflow 512 entries"

Say you have following code, you will immediately get this issue.

void methodOne()
{
for(int i = 0 ; i < 1000 ; i++)
{
jobject localReferenceOne = ...;
methodTwo(localReferenceOne);
}
}

void methodTwo(jobject parameter)
{
jobejct localReferenceTwo = ...;
}

First You should delete all local reference once you are done with that.

void methodOne()
{
for(int i = 0 ; i < 1000 ; i++)
{
jobject localReferenceOne = ...;
methodTwo(localReferenceOne);
env->DeleteLocalRef(localReferenceOne);
}
}

void methodTwo(jobject parameter)
{
jobejct localReferenceTwo = ...;
...
env->DeleteLocalRef(localReferenceOne);
}

But you will still faces the issue. This is because parameter also local reference. You cannot delete the parameter using DeleteLocalRef. To delete parameter local reference you need to call PushLocalFrame and PopLocalFrame before and after method call.

void methodOne()
{
for(int i = 0 ; i < 1000 ; i++)
{
env->PushLocalFrame(0);
jobject localReferenceOne = ...;
methodTwo(localReferenceOne);
env->DeleteLocalRef(localReferenceOne);
env->PopLocalFrame(0);
}
}

void methodTwo(jobject parameter)
{
jobejct localReferenceTwo = ...;
...
env->DeleteLocalRef(localReferenceOne);
}