Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Java JNIEXPORT memory management

I have a question abour memory management of java port of OpenCV.

JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__III
          (JNIEnv* env, jclass, jint rows, jint cols, jint type)
        {
            try {
                LOGD("Mat::n_1Mat__III()");

                Mat* _retval_ = new Mat( rows, cols, type );

                return (jlong) _retval_;
            } catch(cv::Exception e) {
                LOGD("Mat::n_1Mat__III() catched cv::Exception: %s", e.what());
                jclass je = env->FindClass("org/opencv/core/CvException");
                if(!je) je = env->FindClass("java/lang/Exception");
                env->ThrowNew(je, e.what());
                return 0;
            } catch (...) {
                LOGD("Mat::n_1Mat__III() catched unknown exception (...)");
                jclass je = env->FindClass("java/lang/Exception");
                env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__III()}");
                return 0;
            }
        }

This code block is taken from '..\OpenCV-2.4.5\modules\java\generator\src\cpp\Mat.cpp'. My question is about following part:

Mat* _retval_ = new Mat( rows, cols, type );
return (jlong) _retval_;

It returns mat objects address by casting it to jlong and does not delete the object. So, how does the memory management is done? Does java runs Garbage Collector? Or are there any other code in C++ side that clears the memory somehow?

like image 853
guneykayim Avatar asked Mar 27 '26 16:03

guneykayim


1 Answers

There is no memory manage done here.

The function really returns a pointer to a heap-allocated object without caring about the memory management.

Actually this method correspond to the Java class org.opencv.core.Mat which has a long attribute named nativeObj. So this java class is managing a pointer and it is always passed to the underlying C++ implementation.

On the Java Mat object, you have to call the release method, which in turn call the JNI function Java_org_opencv_core_Mat_n_release.

The finalize method also call n_delete which free the memory.

You can see the Java code here.

like image 103
Geoffroy Avatar answered Mar 29 '26 10:03

Geoffroy