Praveen Kumar
Praveen Kumar

Reputation: 1016

How to synchronize on java object in c++ passed from java to c++?

Am passing a java object to cpp. I want to synchronize on that java object in cpp. (I want to synchronize on the same object in java side also, but no problem with this since this can be easily achieved thru synchronized block).

Goal is:

cpp will put keep on appending some data in Arraylist object (which it received from java) And simultaneously java will keep on consuming (removing) that data in java code. So i want to synchronize the operation in both java and cpp code.

Just syntax to do that in cpp will be sufficient for me

Upvotes: 1

Views: 112

Answers (1)

Radiodef
Radiodef

Reputation: 37875

You can use the JNI functions for Monitor Operations:

jint MonitorEnter(JNIEnv *env, jobject obj);
jint MonitorExit(JNIEnv *env, jobject obj);

Of course this is C++ so you probably want to put it in a class (RAII):

class MonitorLock {
    JNIEnv *env;
    jobject obj;

public:
    MonitorLock(JNIEnv *in_env, jobject in_obj)
            : env(in_env), obj(in_obj) {
        if (env->MonitorEnter(obj)) {
            // there was an unusual problem,
            // you'll need to decide what to do with it
        }
    }

    ~MonitorLock() {
        if (env->MonitorExit(obj)) {
            // there was an unusual problem,
            // you'll need to decide what to do with it
        }
    }
};
{
    MonitorLock lock(env, obj);
    /*
     * synchronized
     *
     */
}

Or, you know, just use the functions by themselves. RAII makes the code nicer to read and guarantees that MonitorExit always gets called.

Upvotes: 3

Related Questions