Sun Microsystems 2 Wireless Office Headset User Manual


 
Chapter 2 Multitasking Safety 17
For the sake of simplicity, ignore the situation where another cooking operation
might already be in progress, and ignore the logic for block and unblocking the
calling thread.
Note also the use of a technique for allocating a native context object and storing its
pointer in a Java object field. All data used in this native method is relative to the
Java object on which it’s called. This automatically provides multitask safety. An
object belongs exclusively to a single task, so operations that are interleaved or that
occur simultaneously in different tasks cannot interfere with each other.
CODE EXAMPLE 2-9 Implementing the Native n_cook() Method
/* microwave.c */
KNIEXPORT KNI_RETURNTYPE_INT
Java_javax_microwave_oven_Microwave_n_cook(void)
{
int nsecs;
int power;
MWSTATUS *statusp;
int retval;
jfieldID nsecsFieldID;
jfieldID powerFieldID;
jfieldID nativePtrFieldID;
KNI_StartHandles(2);
KNI_DeclareHandle(thisObj);
KNI_DeclareHandle(microwaveClass);
KNI_GetThisPointer(thisObj);
KNI_GetObjectClass(thisObj, microwaveClass);
nsecsFieldID = KNI_GetFieldID(microwaveClass, "nsecs", "I");
powerFieldID = KNI_GetFieldID(microwaveClass, "power", "I");
nativePtrFieldID =
KNI_GetFieldID(microwaveClass, "nativePtr", "I");
if (/* this is the first invocation */) {
statusp = (MWSTATUS *)malloc(sizeof(MWSTATUS));
nsecs = KNI_GetIntField(thisObj, nsecsFieldID);
power = KNI_GetIntField(thisObj, powerFieldID);
KNI_SetIntField(thisObj, nativePtrFieldID, (jint)statusp);
mw_settime(nsecs);
mw_setpower(power);
mw_cook(callback, statusp);
SNI_BlockThread();
retval = -1; /* return value ignored if caller is blocked */