This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

COS 461 Fall 1997 Network Objects u first good implementation: DEC SRC Network Objects for Modula-3 u recent implementation: Java RMI (Remote Method Invocation)
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Written by: Dr. JJ Shepherd
1 1 Lecture 14 Java Virtual Machine Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Java Native Interface Modified from CS587x Lecture Department of Computer Science Iowa State University.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
JETT 2003 Java.compareTo(C++). JAVA Java Platform consists of 4 parts: –Java Language –Java API –Java class format –Java Virtual Machine.
Introduction to Kernel
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Review of C++ Programming Part II Sheng-Fang Huang.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Ch 4. Memory Management Timothy Budd Oregon State University.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Java and C++, The Difference An introduction Unit - 00.
Java Native Interface CS587x Lecture Department of Computer Science Iowa State University.
What is Android NDK ● A toolset that lets you embed in you app native source code ● C, C++(recently supported December 2010) and assembly(?) ● It is supported.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Java Introduction to JNI Prepared by Humaira Siddiqui.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
The Structure of Processes (Chap 6 in the book “The Design of the UNIX Operating System”)
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Android JNI and JAR Library JNI Library 1. JNI *.c sources file must include jni header file jni.h #include 2. In Make file CFLAGS must add -I $(NDK_INC)/
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Copyright Curt Hill Variables What are they? Why do we need them?
Java Thread and Memory Model
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
RealTimeSystems Lab Jong-Koo, Lim
JNI: Java Native Interface(1/32) Real Time Systems LAB. JNI: Java Native Interface October 31, 2001 Kyung-Yim, Kim.
Introduction to Kernel
JAVA MULTIPLE CHOICE QUESTION.
Lesson One – Creating a thread
Java Primer 1: Types, Classes and Operators
Java Programming Language
Threads and Cooperation
null, true, and false are also reserved.
System Structure and Process Model
Threading And Parallel Programming Constructs
Thread Implementation Issues
Threads Chapter 4.
Object Oriented Programming in java
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. Lecture 6 - NDK Integration (JNI)

Laura Gheorghe, Petre Eftime Arrays  Java arrays - reference type in JNI  JNI treats primitive arrays and object arrays differently  Primitive arrays contain primitives  Object arrays contain class instances or other arrays  Object[] and int[][] are object arrays  jarray and subtypes ( jintArray, jobjectArray ) 2

Laura Gheorghe, Petre Eftime New Array 3  New Array where Type is Int, Char, Boolean, etc.  In case of memory overflow  Function returns NULL  Exception is thrown in the VM  Native code should be stopped jintArray javaArray = env->NewIntArray(10);

Laura Gheorghe, Petre Eftime Accessing Array Elements using a Copy 4  Copy Java array into C array or obtain a direct pointer to the array elements  Copy Java array into C array  Get ArrayRegion  Make changes on the array elements  Copy C array back into Java array  Set ArrayRegion  Performance problem for big array size jint nativeArray[10]; env->GetIntArrayRegion(javaArray, 0, 10, nativeArray); env->SetIntArrayRegion(javaArray, 0, 10, nativeArray);

Laura Gheorghe, Petre Eftime Operating on Direct Pointer 5  Obtain a direct pointer to the array elements when possible  Get ArrayElements  isCopy - the C array points to a copy or a pinned array in heap  Returns NULL if operation fails jint* nativeDirectArray; jboolean isCopy; nativeDirectArray = env->GetIntArrayElements(javaArray, &isCopy);

Laura Gheorghe, Petre Eftime Releasing a Direct Pointer 6  Release array returned by Get ArrayElements  Release ArrayElements  Last parameter - release mode  0 - copy back content, free native array  JNI COMMIT - copy back content, do not free native array (update Java array)  JNI ABORT - do not copy back content, free native array  GetArrayLength  Get/ReleasePrimitiveArrayCritical env->ReleaseIntArrayElements(javaArray, nativeDirectArray, 0);

Laura Gheorghe, Petre Eftime Object Array 7  Create new object array  NewObjectArray  Params: length, class and initialization value  Obtain an element from an object array  GetObjectArrayElement  Cannot obtain all object elements  Update an element in an object array  SetObjectArrayElement jobjectArray arr = env->NewObjectArray(size, javaClass, NULL); jstring js = (jstring)env-> GetObjectArrayElement(arr, i); env->SetObjectArrayElement(arr, i, js);

Laura Gheorghe, Petre Eftime NIO Operations 8  Native I/O - buffer management, scalable network and file I/O  Better performance - deliver data between native and Java app  Create a direct byte buffer to be used in the Java app  NewDirectByteBuffer  Based on a native byte array  Obtain native byte array from Java byte buffer  GetDirectBufferAddress  The direct byte buffer can also be created in the Java app unsigned char* buffer = (unsigned char*) malloc(1024); jobject directBuffer; directBuffer = env->NewDirectByteBuffer(buffer, 1024); unsigned char* buffer; buffer = (unsigned char*) env->GetDirectBufferAddress (directBuffer);

Laura Gheorghe, Petre Eftime Field Types 9  In Java: static fields and instance fields  Each instance has its own copy of the instance fields  All instances share the same static fields  JNI functions for both types of fields private String instanceField = "Instance Field"; private static String staticField = "Static Field";

Laura Gheorghe, Petre Eftime Get Field ID 10  Obtain class object from instance  GetObjectClass  Obtain field ID of an instance field  GetFieldID  Last parameter - field descriptor  Obtain field ID of static field  GetStaticFieldID jclass cl = env->GetObjectClass(instance); jfieldID instanceFieldId; instanceFieldId = env->GetFieldID(cl,"instanceField", "Ljava/lang/String;"); jfieldID staticFieldId; staticFieldId = env->GetStaticFieldID(cl,"staticField", "Ljava/lang/String;");

Laura Gheorghe, Petre Eftime Get Fields 11  Obtain an instance field  Get Field  Obtain a static field  GetStatic Field  Type = Object, Primitive type  Return NULL in case of memory overflow  Performance overhead  Recommended to pass parameters to native methods jstring instanceField; instanceField = env->GetObjectField(instance, instanceFieldId); jstring staticField; staticField = env->GetStaticObjectField(cl, staticFieldId);

Laura Gheorghe, Petre Eftime Types of Methods 12  In Java: instance and static methods  Instance method  Static method  JNI functions to access both types private String instanceMethod() { return "Instance Method"; } private static String staticMethod() { return "Static Method"; }

Laura Gheorghe, Petre Eftime Get Method ID 13  Obtain method ID of an instance method  GetMethodID  Last parameter - method descriptor (signature)  Obtain method ID of a static method  GetStaticMethodID jmethodID instanceMethodId; instanceMethodId = env->GetMethodID(cl, "instanceMethod", "()Ljava/lang/String;"); jmethodID staticMethodId; staticMethodId = env->GetStaticMethodID(cl, "staticMethod", "()Ljava/lang/String;");

Laura Gheorghe, Petre Eftime Get Methods 14  Call instance method  Call Method  Call static method  CallStatic Field  Type = Void, Object, Primitive type  Specify method arguments after method ID  Return NULL in case of memory overflow  Performance overhead  Minimize transitions between Java and native code jstring instanceMethodResult; instanceMethodResult = env->CallObjectMethod (instance, instanceMethodId); jstring staticMethodResult; staticMethodResult = env->CallStaticObjectMethod(cl, staticMethodId);

Laura Gheorghe, Petre Eftime Field & Method Descriptors 15 Java TypeSignature BooleanZ ByteB CharC ShortS IntI LongJ FloatF DoubleD fully-qualified-classLfully-qualified-class type[][type method type(arg-type)ret-type Use javap to obtain descriptors associated to a Java class

Laura Gheorghe, Petre Eftime Catch Exceptions 16  Handling exceptions is important in Java  VM catches exception, clears exception and executes handling block  In native code developers must implement exception handling flow  Catch an exception generated while calling a Java method  ExceptionOccurred env->CallVoidMethod(instance, methodID); jthrowable ex = env->ExceptionOccurred(); if (ex != NULL) { env->ExceptionClear(); /* Handle exception here */ }

Laura Gheorghe, Petre Eftime Throw Exceptions 17  Native code can throw Java exceptions  First obtain exception class  Throw exception  ThrowNew  Does not automatically stop native method and transfer control to exception handler  Should free resources and return jclass cl = env->FindClass ("java/lang/NullPointerException"); if (cl != NULL) { env->ThrowNew(cl, "Message"); }

Laura Gheorghe, Petre Eftime References 18  The VM tracks object references and garbage collects the ones that are not referenced  JNI allows native code to manage object references and lifetimes  3 types of references: local, global and weak global

Laura Gheorghe, Petre Eftime Local References 19  Most JNI functions return local references  Cannot be cached and reused in subsequent invocations  Lifetime limited to the native method - freed when method returns  Minimum 16 local references for the native code in the VM  Free local references while making memory-intensive operations  Manually free local reference  DeleteLocalRef jclass cl = env->FindClass("java/lang/String"); env->DeleteLocalRef(cl);

Laura Gheorghe, Petre Eftime Global References 20  Valid during subsequent invocations of the native method  Until explicitly freed  Create new global reference  NewGlobalRef  Delete global reference when no longer used  DeleteGlobalRef  Can be used by other native methods or native threads jclass localCl = env->FindClass("java/lang/String"); jclass globalCl = env->NewGlobalRef(localCl); env->DeleteLocalRef(localCl); env->DeleteGlobalRef(globalCl);

Laura Gheorghe, Petre Eftime Weak Global References 21  Valid during subsequent invocations of the native method  The object can be garbage collected  Create new weak global reference  NewWeakGlobalRef jclass weakGlobalCl; weakGlobalCl = env->NewWeakGlobalRef(localCl);

Laura Gheorghe, Petre Eftime Weak Global References 22  Verify if the reference is still pointing to an instance  IsSameObject  Delete weak global reference  DeleteWeakGlobalRef if (env->IsSameObject(weakGlobalCl, NULL) == JNI_FALSE){ /* Object is still live */ } else { /* Object is garbage collected */ } env->DeleteWeakGlobalRef(weakGlobalCl);

Laura Gheorghe, Petre Eftime Threads 23  Multithreaded environment  Threads vs. references  Local references valid only in the thread context executing the native method  Local references cannot be shared between multiple threads  Global references can be shared between multiple threads  Threads vs. JNIEnv  Interface pointer valid only in the thread executing the native method  Cannot be cached and used by other threads

Laura Gheorghe, Petre Eftime Native Threads 24  Use threads for running tasks in parallel  Linux threads, scheduled by the kernel  Started from managed code with Thread.start  Can also be started with pthread_create  Native threads not known by the VM until they are attached  No JNIEnv  Cannot make JNI calls

Laura Gheorghe, Petre Eftime Native Threads 25  First attach native thread to the VM  AttachCurrentThread  Obtain a JNIEnv interface pointer for the current thread  java.lang.Thread object added to main ThreadGroup  Last argument: JavaVMAttachArgs structure - can specify other thread group  AttachCurrentThreadAsDaemon  After communication with the Java app, detach from VM  DetachCurrentThread JavaVM* cachedJvm; JNIEnv* env; cachedJvm->AttachCurrentThread(&env, NULL); cachedJvm->DetachCurrentThread();

Laura Gheorghe, Petre Eftime Synchronization 26  Synchronization using monitors based on Java objects  Only one thread can hold a monitor at a time  Acquire a monitor  MonitorEnter  obj is a Java object  If another thread owns the monitor, waits until it’s released  If no other thread owns the monitor, becomes owner, entry counter = 1  If the current thread owns the monitor, increments the entry counter env->MonitorEnter(obj);

Laura Gheorghe, Petre Eftime Synchronization 27  Release monitor  MonitorExit  The current thread must be the owner of the monitor  Entry counter is decremented  When counter = 0, the current thread releases the monitor env->MonitorExit(obj);

Laura Gheorghe, Petre Eftime Standard JNI vs. Android JNI 28  All JNI 1.6 features are supported by Android JNI  Exception: DefineClass not implemented  No Java bytecodes or class files in Android  Not useful  JNI does not include proper error checks  Android includes CheckJNI mode  Performs series of checks before the actual JNI function is called  Enable CheckJNI from adb shell  Enabled by default on emulator

Laura Gheorghe, Petre Eftime CheckJNI 29  Attempt to allocate negative-sized arrays  Passing a bad pointer( jobject, jclass, jarray, jstring ) to a JNI call  Passing a NULL pointer to a JNI call when argument should not be NULL  Passing a class name not correctly specified to a JNI call  Making a JNI call in a critical region  Passing invalid arguments to NewDirectByteBuffer  Making a JNI call while an exception is pending

Laura Gheorghe, Petre Eftime CheckJNI 30  Using JNIEnv* in the wrong thread  Using NULL, wrong type field ID, static/instance mismatch  Using invalid method ID, incorrect return type, static/instance mismatch, invalid instance/class  Using DeleteGlobal/LocalRef on the wrong reference  Passing a bad release mode, other than 0, JNI_COMMIT, JNI_ABORT  Returning incompatible type from native method  Passing invalid UTF-8 sequence to a JNI call

Laura Gheorghe, Petre Eftime Bibliography 31  f  ni/spec/jniTOC.html  /spec/functions.html  jni.html  Onur Cinar, Pro Android C++ with the NDK, Chapter 3  Sylvain Ratabouil, Android NDK, Beginner’s Guide, Chapter 3

Laura Gheorghe, Petre Eftime Keywords 32  Primitive array  Object array  Direct pointer  Native I/O  Static/instance fields  Static/instance methods  Field/method ID  Field/method descriptor  Catch/throw exception  Local/global/weak global references  Native threads  Monitor  CheckJNI