Category: Proxy usage
Q
Can I explicitly use Java synchronization from C++?
A
In Java, you can use the synchronized keyword to create a critical section in which one thread has exclusive access to a Java object. In JNI, you can use the MonitorEnter() and MonitorExit() functions for the same purpose. While we can't give you the synchronized keyword in C++, we can do something that is almost as good.
The runtime library provides you with the xmog_lock_holder utility type for the purpose of providing synchronization on a Java object. Here's how you might use it in your code:
MyProxyType mpt = MyProxyType::getInstance();
// this is the scope to which the synchronization applies { // the constructor attempts to grab the lock on the // passed in object, blocking if held by another thread xmog_lock_holder monitor( mpt ); ... } // the 'monitor' object goes out of scope and
// its destructor releases the lock
You can synchronize on a type, i.e. the static members of a Java class, by using the xmog_java_class instance associated with a proxy type as illustrated in the following snippet:
xmog_java_class * clazz = MyProxyType::get_class();
// this is the scope to which the synchronization applies { // the constructor attempts to grab the lock on the // passed in object, in this case, a type object xmog_lock_holder monitor( *clazz ); ... } // the 'monitor' object goes out of scope and
// its destructor releases the lock
