CSPP51036 Java Programming Instructor: Andrew Siegel
Slide 2
Syllabus, discussion group, etc. Everything is posted on course
website http://masters.cs.uchicago.edu/~asiegel/courses/cspp51036
Please pay particular attention to grading policy/homework
submission First homework already posted. Please be sure to sign up
for discussion group asap!
Slide 3
Grading Bi-weekly homework assignment 5 total 3 day automatic
extension for 10% Serious emergency = not graded Submit
electronically, receive confirmation. 24 hours to deal with any
problems. Typically, functionality only will be graded. Wrong
answer = no credit. Design will be graded only when problems
specify design requirements. Final In-class, conceptual,
purposeful.
Slide 4
Who is this class for? There is no assumption that you know any
Java or other OO programming language. If you do, you may find the
first few weeks boring. You must have programming experience. We
will not spend very much time on syntax, procedural constructs,
operators, etc. It is assumed that you can pick this up.
Slide 5
Getting Help TAs The class will be split into a number of
subgroups, each of which is assigned to one of the TAs. The TAs
will organize office hours/review sessions according to the needs
of their group. Quickest way to answer small questions is with
email to course list. Everyone is encouraged to answer will be
factored into grade. Very good way to learn. Try not to spend too
much class time discussing homeworks tas will handle this.
Slide 6
Course Format All lecture Will follow book closely! Feel free
to ask questions any time Probably wont call on you unsolicited
Probably will make fun of you Attendance is optional but
recommended Might use overhead projector, might not. Will post
notes each week in any case
Slide 7
Software/hardware requirements Command-line tools best when
first learning. Suns Java Software Development Kit (SDK) Already
installed on Linux cluster May choose to install on your own
machine free and easy, download manageable (book CD has copy). See
beginning of chapter 2 for installation instructions. Some IDE
(Forte, Visual Age, Visual Caf, etc.) not recommended. May use but
are responsible for exporting in a manner understandable by jdk.
Your favorite text editor emacs is recommended. Textpad is pretty
good for Java.
Slide 8
History of Java First version released in 1995 Four major
versions released since then 1.02 (1996) JDBC, Distributed Objects
1.1 (1997) New Event Model 1.2 (1998) Swing 1.3 (2000) Cleanup 1.4
(2002)
Slide 9
Programming with Java
Slide 10
What is/isnt Java? Read chapter 1 of Core Java Discussion is
very balanced Basically, compared to C Java is a relatively high-
level language with many built-in features for portably doing
useful things such as: Multithreading Writing distributed programs
Writing GUI clients Error handling Extending Web servers Embedding
programs in Web browsers Connecting to commercial databases
Slide 11
Compiling/running first java program Create source code file
(call it for example MyFirstProgram.java). To compile: prompt
>> javac MyFirstProgram.java This produces byte code file
named MyFirstProgram.class To run: prompt >> java
MyFirstProgram
Slide 12
Observations .class file is not machine code. It is
intermediate form called Java Byte code. Can run on any platform as
long as platform has a Java Virtual Machine (JVM). The second step
on previous slide invokes the JVM to interpret the byte code on the
given platform. In theory, byte code can be moved to another
platform and be run there without recompiling this is the magic of
applets. Leave off the.class part when invoking the JVM.
Slide 13
Observations This is an old-fashioned command-line program.
Java also supports GUI applications and web-browser hosted programs
called applets. After the first couple of weeks we will use
graphical rather than scripting front-ends.
Slide 14
Writing first program To keep things simple our first few
programs will all be written as just a single main program. In
java, the file in which your program resides must contain a.java
extension (e.g. MyFirstProgram.java).
Slide 15
Writing first program Then, the program must be wrapped in a
class definition which is the same as the file basename
(MyFirstProgram). Careful, Java is case-sensitive. class
MyFirstProgram { } Finally, main is defined similar to C, but with
a few more modifiers: public static void main(String[] args){ }
These are all required. No shortcuts.
Slide 16
Writing first program Just as in C, main(..) is the principle
entry point into the program. When you say java Program Java looks
in Program for a procedure named main. This is where the program
starts. To print to stdout in java use: System.out.println( );
MyFirstProgram. MyFirstProgram.
Slide 17
Basic Programming Constructs What you should learn on your
own
Slide 18
Breakdown of a java program Strategy to start is write
evertything in a single main program and very quickly review the
basics of java syntax (very little time here). Then we break into
procedures. Then class/packages.
Slide 19
Single-threaded program For a single thread of execution, each
line of code is executed sequentially (as in C). Each statement is
terminated with a semicolon. Unlike C, declarations can occur
anywhere within a program. Basic operators, control statements
almost exactly like C. A few minor differences. Best to just look
at some examples.
Slide 20
Java Data Types Sizes fully specified by Java standard. Java is
a very strongly typed language Integer types int (4 bytes signed)
short (2 bytes signed) long (8 bytes signed) use suffix L (eg
1000000000L) byte (1 byte signed) Floating-point types float (4
bytes) use suffix F (eg 1.28F) double( 8 bytes)
Slide 21
Additional Data Types char Two-byte unicode Assignment with
e.g. char c = h; boolean true or false e.g. boolean x = true; if
(x){};
Slide 22
Operators/Control Flow Almost exactly like regular ANSI C. +,
*, -, /, %, ++, --, +=, etc. ==, !=, >, > Student s1 = new
Student(Smith, Jim, 3.13); >> Student s2 = s1">
Clone method Recall that the = operator simply copies Object
references. e.g., >> Student s1 = new Student(Smith, Jim,
3.13); >> Student s2 = s1; >> s1.setGPA(3.2); >>
System.out.println(s2.getGPA()); 3.2 What if we want to actually
make a copy of an Object? Most elegant way is to use the clone()
method inherited from Object. Student s2 = (Student)
s1.clone();
Slide 217
Subtleties of clone() method First, note that the clone method
is protected in the Object class. This means that it is protected
for subclasses as well. Hence, it cannot be called from within an
Object of another class and package. To use the clone method, you
must override in your subclass and upgrade visibility to
public.
Slide 218
More subtleties of clone Also, any class that uses clone must
implement the Cloneable interface. This is a bit different from
other interfaces that weve seen. There are no methods; rather, it
is used just as a marker of your intent. The method that needs to
be implemented is inherited from Object.
Slide 219
More clone() issues Finally, clone throws a
CloneNotSupportedException. This is thrown if your class is not
marked Cloneable. This is all a little odd but you must handle this
in subclass.
Slide 220
Steps for cloning To reiterate, if you would like objects of
class C to support cloning, do the following: implement the
Cloneable interface override the clone method with public access
privileges call super.clone() Handle CloneNotSupported Exception.
This will get you default cloning, but more subtleties still
lurk.
Slide 221
Shallow Copies We havent yet said what the default clone()
method does. By default, clone makes a shallow copy of all ivs in a
class. Shallow copy means that all native datatype ivs are copied
in regular way, but ivs that are objects are not recursed upon that
is, references are copied. This is not what you typically want.
Must override clone explicitly clone object ivs!
Slide 222
Immutable Objects A special class of Objects are called
immutable because their state cannot be changed once set. Common
examples are String, Integer, etc. Immutable object simplify
programming in certain instances, such as when writing thread safe
code. They also simplify cloning, since an object that cannot be
changed doesnt really need to be deep- copied. See
ShallowCopy2.java in course examples
Slide 223
Deep Copies For deep copies that recurse through the object
ivs, you have to do some more work. super.clone() is first called
to clone the first level of ivs. Returned cloned objects object
fields are then accessed one by one and clone method is called for
each. See DeepClone.java example
Slide 224
Additional clone() properties Note that the following are
typical, but not strictly required: x.clone() != x;
x.clone().getClass() == x.getClass(); x.clone().equals(x); Finally,
though no one really cares, Object does not support clone();
Slide 225
toString() method The Object method String toString(); is
intended to return a readable textual representation of the object
upon which it is called. This is great for debugging! Best way to
think of this is using a print statement. If we execute:
System.out.println(someObject); we would like to see some
meaningful info about someObject, such as values of ivs, etc.
Slide 226
default toString() By default toString() prints total garbage
that no one is interested in getClass().getName() + '@' +
Integer.toHexString(hashCode()) By convention, print simple
formatted list of field names and values (or some important
subset). The intent is not to overformat. Typically used for
debugging. Always override toString()!
Slide 227
equals() method Recall that boolean == method compares when
applied to object compares references. That is, two object are the
same if the point to the same memory. Since java does not support
operator overloading, you cannot change this operator. However, the
equals method of the Object class gives you a chance to more
meaningful compare objects of a given class.
Slide 228
equals method, cont By default, equals(Object o) does exactly
what the == operator does compare object references. To override,
simply override method with version that does more meaningful test,
ie compares ivs and returns true if equal, false otherwise. See
Equals.java example in course notes.
Slide 229
equals subtleties As with any method that you override, to do
so properly you must obey contracts that go beyond interface
matching. With equals, the extra conditions that must be met are
discussed on the next slide:
Slide 230
equals contract It is reflexive: for any reference value x,
x.equals(x) should return true. It is symmetric: for any reference
values x and y, x.equals(y) should return true if and only if
y.equals(x) returns true. It is transitive: for any reference
values x, y, and z, if x.equals(y) returns true and y.equals(z)
returns true, then x.equals(z) should return true. It is
consistent: for any reference values x and y, multiple invocations
of x.equals(y) consistently return true or consistently return
false, provided no information used in equals comparisons on the
object is modified. For any non-null reference value x,
x.equals(null) should return false.
Slide 231
hashcode() method Java provides all objects with the ability to
generate a hash code. By default, the hashing algorithm is
typically based on an integer representation of the java address.
This method is supported for use with java.util.Hashtable Will
discuss Hashtable in detail during Collections discussion.
Slide 232
Rules for overriding hashcode Whenever invoked on the same
object more than once, the hashCode method must return the same
integer, provided no information used in equals comparisons on the
object is modified. If two objects are equal according to the
equals(Object) method, then calling the hashCode method on each of
the two objects must produce the same integer result. It is not
required that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode method
on each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hashtables. equals(java.lang.Object)
Slide 233
finalize() method Called as final step when Object is no longer
used, just before garbage collection Object version does nothing
Since java has automatic garbage collection, finalize() does not
need to be overridden reclaim memory. Can be used to reclaim other
resources close streams, database connections, threads. However, it
is strongly recommended not to rely on this for scarce resources.
Be explicit and create own dispose method.
Slide 234
A little more Swing MVC Pattern
Slide 235
More graphics
Slide 236
Graphics See course examples applets/BrownianMotionApplet.java
shows how to do a simple animation with some basic drawing in the
start() method graphics/Mandelbrot.java shows how to create an
image from raw data and draw to an applet by overriding
paintComponent. graphics/Shapes.java A great example of how to
architect a simple GUI that seems more complex when poorly
designed. graphics/Painter.java Classic example of how to paint on
a Panel graphics/Bounce.java Classic example of why one needs
threads.
Slide 237
Miscellaneous
Slide 238
Some how-to snippets See the following codes in the course
examples GetProperties.java How to query various system properties
ProcessTest.java An example spawning an OS executable
NumberFormat.java An example formatting a double TimeTest.java An
example using simple System timers.
Slide 239
What is the Collections framework? Collections framework
provides two things: implementations of common high-level data
structures: e.g. Maps, Sets, Lists, etc. An organized class
hierarchy with rules/formality for adding new implementations The
latter point is the sense in which Collections are a framework.
Note the difference between providing a framework + implementation
and just implementation. Some other differences: code reuse clarity
unit testing?
Slide 240
History Pre Java SDK1.2, Java provided a handful of data
structures: Hashtable Vector Bitset These were for the most part
good and easy to use, but they were not organized into a more
general framework. SDK1.2 added the larger skeleton which organizes
a much more general set of data structures. Legacy datastructures
retrofitted to new model.
Slide 241
General comments about data structures Containers for storing
data. Different data structures provide different abstractions for
getting/setting elements of data. linked lists hastables vectors
arrays Same data structures can even be implemented in different
ways for performance/memory: queue over linked list queue over
arrays
Slide 242
More on data structures Everyone should take a basic class in
building data structures I recommend the book Mastering Algorthims
with C by Kyle Loudon In Java, one does not usually build data
structures, but rather uses the provided one Using Javas data
structures requires a little understanding of the Collections
framework Adding your own requires a deeper understanding.
Slide 243
Learning to use data structures Dual purposes for us to study
Collections: Be able to choose, properly use built-in data
structures. Another study in OO class design Thus, we start by
study the Collections class design. Then, we provide many examples
of how to use the built-in types in real programming.
Slide 244
Collections-related Interface hierarchy Collection ListSet
SortedSet Map SortedMap Iterator ListIterator The Collection
inteface stores groups of Objects, with duplicates allowed The Set
interface extends Collection but forbids duplicates The List
interface extends Collection, allows duplicates, and introduces
positional indexing. Map is a separate hierarchy
Slide 245
Collection implementations Note that Java does not provide any
direct implementations of Collection. Rather, concrete
implementations are based on other interfaces which extend
Collection, such as Set, List, etc. Still, the most general code
will be written using Collection to type variables.
Comments on Collection methods Note the iterator() method,
which returns an Object which implements the Iterator interface.
Iterator objects are used to traverse elements of the collection in
their natural order. Iterator has the following methods: boolean
hasNext(); // are there any more elements? Object next(); // return
the next element void remove(); // remove the next element
Slide 248
AbstractCollection Class java.util.AbstractCollection Abstract
class which is partial implementation of of Collection interface
Implements all methods except iterator() and size() Makes it much
less work to implement Collections Interface
Slide 249
List interface An interface that extends the Collections
interface. An ordered collection (also known as a sequence). The
user of this interface has precise control over where in the list
each element is inserted. The user can access elements by their
integer index (position in the list), and search for elements in
the list. Unlike Set, allows duplicate elements. Provides a special
Iterator called ListIterator for looping through elements of the
List.
Slide 250
Additional methods in List Interface List extends Collection
with additional methods for performing index-based operations: void
add(int index, Object element) boolean addAll(int index, Collection
collection) Object get(int index) int indexOf(Object element) int
lastIndexOf(Object element) Object remove(int index) Object set(int
index, Object element)
Slide 251
List/ListIterator Interface The List interface also provides
for working with a subset of the collection, as well as iterating
through the entire list in a position friendly manner: ListIterator
listIterator() ListIterator listIterator(int startIndex) List
subList(int fromIndex, int toIndex) ListIterator extends Iterator
and adds methods for bi-directional traversal as well as
adding/removing elements from the underlying collection.
Slide 252
Concrete List Implementations There are two concrete
implementations of the List interface LinkedList ArrayList Which is
best to use depends on specific needs. Recall that linked lists are
optimal for inserting/removing elements. ArrayLists are good for
traversing. Note that LinkedList and ArrayList both extend abstract
partial implementations of the List interface.
Slide 253
LinkedList Class The LinkedList class offeres a few additional
methods for directly manipulating the ends of the list: void
addFirst(Object) void addLast(Object); Object getFirst(); Object
getLast(); Object removeFirst(); Object removeLast(); These methods
make it natural to implement other simpler data structures, like
Stacks and Queues.
Slide 254
LinkedList examples See heavily commented LinkedList Example in
course notes A few things to be aware of: it is really bad to use
the positional indexing features copiously of LinkedList if you
care at all about performance. This is because the LinkedList has
no memory and must always traverse the chain from the beginning.
Elements can be changed both with the List and ListIterator
objects. That latter is often more convenient. You can create havoc
by creating several iterators that you use to mutate the List.
There is some protection built-in, but best is to have only one
iterator that will actually mutate the list structure.
Slide 255
ArrayList Class Also supports the List interface, so top-level
code can pretty much invisibly use this class or LinkedList (minus
a few additional operations in LinkedList). However, ArrayList is
much better for using positional index access methods. At the same
time, ArrayList is much worse at inserting elements. This behavior
follows from how ArrayLists are structured: they are just like
Vectors.
Slide 256
More on ArrayList Additional methods for managing size of
underlying array size, isEmpty, get, set, iterator, and
listIterator methods all run in constant time. Adding n elements
take O[n] time. Can explicitly grow capacity in anticipation of
adding many elements. Note: legacy Vector class almost identical.
Main differences are naming and synchronization. See short
ArrayList example.
Slide 257
Set Interface Set also extends Collection, but it prohibits
duplicate items (this is what defines a Set). No new methods are
introduced; specifically, none for index-based operations (elements
of Sets are not ordered). Concrete Set implementations contain
methods that forbid adding two equal Objects. More formally, sets
contain no pair of elements e1 and e2 such that e1.equals(e2), and
at most one null element Java has two implementations: HashSet,
TreeSet
Slide 258
HashSets and hash tables Lists allow for ordered elements, but
searching them is very slow. Can speed up search tremendously if
you dont care about ordering. Hash tables let you do this. Drawback
is that you have no control over how elements are ordered.
hashCode() computes integer (quickly) which corresponds to position
in hash table. Independent of other objects in table.
Slide 259
HashSet Class Hash tables can be used to implement several
important data structures. Simplest of these is HashSet add
elements with add(Object) method contains(Object) is redefined to
first look for duplicates. if duplicate exists, Object is not added
What determines a duplicate? careful here, must redefine both
hashCode() and equals(Object)!
Slide 260
HashSet Look HashSetExample.java Play around with some
additional methods. Try creating your own classes and override
hashCode method. Do Some timings. Be certain you understand this
for final!
Slide 261
Tree Sets Another concrete set implementation in Java is
TreeSet. Similar to HashSet, but one advantage: While elements are
added with no regard for order, they are returned (via iterator) in
sorted order. What is sorted order? this is defined either by
having class implement Comparable interface, or passing a
Comparator object to the TreeSet Constructor. Latter is more
flexible: doesnt lock in specific sorting rule, for example.
Collection could be sorted in one place by name, another by age,
etc.
Slide 262
Comparable interface Many java classes already implement this.
Try String, Character, Integer, etc. Your own classes will have to
do this explicitly: Comparable defines the method public int
compareTo(Object other); Comparator defines the method public int
compare(Object a, Object b); As we discussed before, be aware of
the general contracts of these interfaces. See
TreeSetExample.java
Slide 263
Maps Maps are similar to collections but are actually
represented by an entirely different class hierarchy. Maps store
objects by key/value pairs: map.add(1234, Andrew); ie Object Andrew
is stored by Object key 1234 Keys may not be duplicated Each key
may map to only one value
Slide 264
Java Map interface Methods can be broken down into three
groups: querying altering obtaining different views Fairly similar
to Collection methods, but Java designers still thought best to
make separate hierarchy no simple answers here.
Slide 265
Map methods Here is a list of the Map methods: void clear()
boolean containsKey(Object) boolean containsValue(Object) Set
entrySet() boolean get(Object) boolean isEmpty() Set keySet()
Object put(Object, Object) void putall(Map) Object remove(Object)
int size() Collection values()
Slide 266
Map Implementations We wont go into too much detail on Maps.
Java provides several common class implementations: HashMap a
hashtable implementation of a map good for quick searching where
order doesnt matter must override hashCode and equals TreeMap A
tree implementation of a map Good when natural ordering is required
Must be able to define ordering for added elements.
Slide 267
JNI Linking Java and C code
Slide 268
JNI Stands for Java Native Interface Set of tools/code that
allows user to call native methods from Java. Includes bindings for
C/C++. Can be used to call C/C++ from Java (typical), or Java from
C (invocation API) Differs from spawning executable data is passed
to/from C/C++ method Question: why is this difficult?
Slide 269
Reasons for using JNI Feature not available in java language
(rare). Code already written in another language, dont want to
rewrite (typical). Java is slow (how slow?) Other language has no
additional features per se, but has much better syntax for handling
certain operations (Fortran for math).
Slide 270
Problems with JNI Only provides C/C++ bindings. Going to
Fortran, COBOL, Ada, etc. requires extra step. Not portable Mapping
is not trivial Can be unsafe Cannot run from applet (security
issues)
Slide 271
Machinery for using JNI Steps to follow
Slide 272
Basic steps to calling native code 1. Write java class with at
least one method declared with native keyword. Provide no
implementation public native void sayHello(); Example above is most
simple, but method may pass any parameters or have any return type.
2. Add a call to System.loadLibrary(libname) in the class that
declares the native method: static{
System.loadLibrary(hello);}//static means called only once.
Slide 273
Steps, cont. 3. Compile the class javac Hello.java 4. Produce
the C/C++ header files using the javah utility: Javah Hello This
produces the header file Hello.h 5. Write your implementation file
by first copying the function signature produced in the include
file. Also, #include the header file. #include Hello.h
Slide 274
Steps, cont. 6. Write the implementation in C/C++. This will
require using JNI methods to access the data or possibly casts to
convert to basic C/C++ types 7. Best technique: Break into two
steps. Think of your C/C++ function as a wrapper which accesses the
Java data and maps it to C data using JNI methods, then shoves the
converted data into a prewritten standalone C program.
Slide 275
Steps, cont. 8. Compile your native method(s) as a shared
object (or DLL on Windows). WARNING: Be sure to point your linker
to the include files in /jdk1.3/include and jdk1.3/include/linux
(for example). WARNING: Mixing languages is much easier using a
straight C wrapper rather than C++. 9. Set the environment variable
LD_LIBRARY_PATH to the shared object directory Run main Java
class.
Slide 276
C language bindings What does Java pass to my method?
Slide 277
What does Java pass to my C function? JNIEnv* : A pointer to
the the JNI environment. This pointer is a handle to the current
thread in the JVM, and contains mapping functions and other
housekeeping information. jobject : A reference to the object that
called the native code. (like this pointer). Any arguments
specified by the method.
Slide 278
Pause for some nice pictures
Slide 279
Slide 280
Legacy C calls Java
Slide 281
Java calls legacy
Slide 282
Slide 283
JNI is inter-language glue
Slide 284
Simple examples on union HelloWorld Example: No data passed
Hello.javaHello.java Hello.ccHello.cc Max example : Only native
dataypes Utils.javaUtils.java utils.ccutils.cc Advanced Max
example: Arrays Utils.javaUtils.java utils.ccutils.cc Max
Java-C-Fortran: max.fmax.f
Java object Mappings Object passed by reference All objects
have type jobject as:
Slide 288
Object mappings, cont. For example, if a method getLine exists
in a class call Prompt, then: private native String getLine(String
Prompt); is mapped into JNIExport jstring JNICALL
Java_Prompt_getLine(JNIEnv *, jobject, jstring); But how to access
data/methods from object that is passed in?
Slide 289
JNI Advice Can seem like a bewildering number of functions. Do
not try to learn it all. Keep interfaces very simple. Preferably,
only native datatypes, Strings, and arrays. Be careful about Copies
vs. rerences Freeing memory Best not to allocate memory from with
native code.
Slide 290
Accessing java strings Do NOT do the following: JNIEXPORT
jstring JNICALL Java_Prompt_getLine(JNIEnv *env, jobject obj,
jstring prompt){ printf(%s, prompt); } Why is this bad?
Slide 291
Right way to access Strings Must use special methods in env
structure char *str = (*env)->GetStringUTFChars(env,prompt,0);
/* this maps into regular C char* */ printf(%s, str); /* now it is
ok to print */ (*env)->ReleaseStringUTFChars(env, prompt, str);
/* must release String to avoid memory leaks */
Slide 292
Returning Strings Previous technique allows us to use a String
passed in from Java. What if we want to return a String? Can use
NewStringUTF as: char buf[128]; /* allocate memory for local char*
in C */ scanf(%s, buf); /* read into char* from stdio */ return(
(*env)->NewStringUTF(env, buf)); /* construct and return the
Java String */
Slide 293
Other JNI String methods GetStringChars Takes the Java String
and returns a pointer to an array of Unicode characters that
comprise it. ReleaseStringChars Releases the pointer to the array
of Unicode characters NewString Constructs a new String object from
an array of Unicode Characters GetStringLength Returns the length
of a string of Unicode characters
Slide 294
Java arrays Note that you can NOT do the following: JNIExport
jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj,
jintArray arr){ int i, sum = 0; for (i = 0; i
Array methods The previous example should be written as: jsize
len = (*env)->GetArrayLength(env,arr); jint *body =
(*env)->GetIntArrayElements(env,arr,0); for
(i=0;iReleastIntArrayElements(env,arr,body,0); /* very important
copies back to java array if copy had to be made */
Slide 296
Array methods, cont. Note that there are analagous functions
for float, byte, double, etc: Get ArrayElements Release
ArrayElements Important: These Get functions may copy the entire
array. If this is undesirable, use Get/Set ArrayRegion
functions
Slide 297
Function for accessing arrays FunctionArray Type
GetBooleanArrayElementsboolean GetByteArrayElementsbyte
GetShortArrayElementsshort GetIntArrayElementsint
GetLongArrayElementslong GetFloatArrayElementsfloat
GetDoubleArrayElementsdouble GetObjectArrayElementsobject
Slide 298
Functions for releasing arrays FunctionArray Type
ReleaseBooleanArrayElementsboolean ReleaseByteArrayElementsbyte
ReleaseShortArrayElementsshort RelaseIntArrayElementsint
ReleaseLongArrayElementslong ReleaseFloatArrayElementsfloat
ReleaseDoubleArrayElementsdouble
ReleaseObjectArrayElementsobject
Slide 299
Calling java methods What if you pass a java object to a C
routine and wish to call back a method on the Java object. Good to
avoid this when you can but sometimes it is very important. Need to
use the jobject reference that is passed in by java.
Slide 300
Steps to follow Native method calls JNI function GetObjectClass
returns the jclass object that is type of that obj Native method
calls JNI function GetMethodID returns jmethodID of method in class
(0 for no such method) Finally, native method calls JNI function
CallVoidMethod. invokes an instance of method with void return
type. You pass object, methodID, and actual arguments.
Slide 301
A simple alternative spawning a system executable Advantages
Infinitely simpler Portable Can use any native language
Disadvantages Can only pass data to and from vi stdout Must reload
executable for each invocation
Slide 302
Legacy Collections java.util.Vector Still useable, but
typically ArrayList is preffered. Only major difference is if you
are using muliple threads java.util.HashTable Still useable, but
typically HashMap is preferred. Again, different if using multiple
threads.
Slide 303
Multithreaded programming with Java
Slide 304
What are threads? Like several concurrent subprograms running
within the same address space. Within a program, individual threads
are explicitly spawned and give the appearance of simultaneously
running sequences of commands. On a single proc machine, the
simultaneous running is an illusion cpu is time splicing. Differ
from separate processes in that each process runs in its own
address space shared memory model
Slide 305
Why use threads? Single-user programs/clients continuously
responsive user interfaces accept input when event handler is bus
Can actually speed up certain tasks Servers Allows multiple client
connections simultaneously
Slide 306
General examples User clicks GUI button to download web page
(occurs in separate thread so GUI isnt frozen) Massive numerical
problems split among processors assumes each thread runs on
separate processor; not necessarily the case Server spawns thread
for each client connection and main thread goes back to accept()
User clicks button which begins time-consuming database lookup.
Client can accept more input while lookup is taking place.
Slide 307
Concrete example Consider two versions of a program which
animates a ball bouncing around in a window. In one version, the
animation takes place in the event handler thread. Thus, the gui is
frozen for the whole animation In a second version, the animation
takes place in a new thread spawned in the event handler. This
gives the event thread a chance to operate. Run Bounce.java and
BounceThread.java
Slide 308
Second concrete example Imagine a GUI program that performs a
time-consuming task in the event handler (such as the
AuctionSimulator). How can the GUI remain responsive? If we do task
in a separate thread and sleep it periodically, user interface
thread will appear live. See FrameThread.java and
FrameNoThread.java
Slide 309
Machinery How to setup threads in Java
Slide 310
How to create separate threads in Java -- technique I Extend
Thread. Specifically... Create a class that extends Thread and
place the work that the Thread will carry out in the run() method
(ie override the run method). Create an object from your class that
extends the Thread class. Call the start() method on the Thread
object. The new Thread then unters the runnable state (it may or
may not run depending on resources/priority).
Slide 311
How to create threads Technique 2 Implement Runnable.
Specifically... Create a class that implements the Runnable
interface. Place all of the work that the Thread will perform in
the run() method. Create an object from the Runnable class. Create
a Thread object and pass the Runnable object to the constructor.
Call the start() method on Thread object. See simple examples under
basic directory.
Slide 312
Simple Example Thread Class ThreadExample{ public static void
main(String[] args){ System.out.println(Main thread started);
MyFirstThread t = new MyFirstThread() t.start(); } Class
MyFirstThread extends Thread{ void run(){ System.out.println(in new
thread ); }
Slide 313
Example using second technique class ThreadTest{ public static
void main(String[] args){ System.out.println(main thread started );
MyRunnableObj r = new MyRunnableObj(); Thread t = new Thread(r);
t.start(); } Class MyRunnableObj implements Runnable{ public void
run(){ System.out.println(new thread started ); }
Slide 314
What happens to new threads? Main thread continues New threads
execute the run method and die when they are finished If any thread
calls System.exit(0), it will kill all threads. Think of each run()
as its own main Program does not exit until all non-daemon threads
die.
Slide 315
Thread States Four states a Thread can be in: New When you
create with new operator but havent run yet. Runnable When you
invoke start() method. Note that Thread is not necessarily running,
could be waiting. Blocked When sleep() is called Blocking operation
such as input/output wait() is called by the Thread object Thread
tries to obtain a lock on a locked object
Slide 316
Thread states, cont. Dead Dies a natural death because the run
method exits normally Dies abruptly after an uncaught exception
terminates the run method Use isAlive() method to determine if
Thread is currently alive (either runnable or blocked).
Slide 317
Thread Priority The execution of multiple threads on a single
CPU is called scheduling. The Java runtime supports a very simple,
deterministic scheduling algorithm known as fixed priority
scheduling.
Slide 318
Thread Priority Each Java thread is given a numeric priority
between MIN_PRIORITY and MAX_PRIORITY. When multiple threads are
ready to be executed, the thread with the highest priority is
chosen for execution. Only when that thread stops, or is suspended
for some reason, will a lower priority thread start executing.
Scheduling of the CPU is fully preemptive. If a thread with a
higher priority than the currently executing thread needs to
execute, the higher priority thread is immediately scheduled.
Slide 319
Thread Priority The Java runtime will not preempt the currently
running thread for another thread of the same priority. In other
words, the Java runtime does not time-slice. However, the system
implementation of threads underlying the Java Thread class may
support time-slicing. Do not write code that relies on
time-slicing. In addition, a given thread may, at any time, give up
its right to execute by calling the yield method. Threads can only
yield the CPU to other threads of the same priority--attempts to
yield to a lower priority thread are ignored.
Slide 320
Thread Priority When all the runnable threads in the system
have the same priority, the scheduler chooses the next thread to
run in a simple, non-preemptive, round-robin scheduling order.
Slide 321
A common scenario: polling vs callbacks How do we implement the
following? Thread1 spawns Thread2 Thread1 does work Thread2 does
work that results in new value of variable (or new data in file,
etc). Thread1 finishes work and needs update value (or file) from
Thread2s work. How can we synchronize activities?
Slide 322
Whats so difficult? Atomic processes, sharing resources,
synchronization, deadlock
Slide 323
Slide 324
Bottom Line Any time a writeable variable is visible to more
than one thread, potential problems exist. Simple example: two
clients try to purchase item at same time. Order or execution
unpredictable If (itemsLeft > itemsRequested) not reliable! Must
create thread-safe programs More on this later
Slide 325
Managing Threads Everything in either Object or Thread class
Two classes of methods: Those defined in Object wait(), notify(),
notifyAll() Those defined in Thread class join(), sleep(),
interrupt(), isAlive(), yield(), etc. All involve situations where
threads communicate with each other in some way. Will discuss
later
Slide 326
Producer/Consumer example One thread is called the Producer.
Producer shoves consecutive integers into a Cubbyhole object as
fast as it can. Other thread is called Consumer. Consumer grabs
from the Cubbyhole object as fast as it can. Consumer would like to
grab once for each put by the Producer, but what if one goes faster
than the other?
Slide 327
Producer Class public class Producer extends Thread { private
CubbyHole cubbyhole; private int number; public Producer(CubbyHole
c, int number) { cubbyhole = c; this.number = number; } public void
run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i); try
{ sleep((int)(Math.random() * 100)); } catch (InterruptedException
e) { } }}}
Slide 328
Consumer class public class Consumer extends Thread { private
CubbyHole cubbyhole; private int number; public Consumer(CubbyHole
c, int number) { cubbyhole = c; this.number = number; } public void
run() { int value = 0; for (int i = 0; i < 10; i++) { value =
cubbyhole.get(); System.out.println("Consumer #" + this.number + "
got: " + value); }}}
Slide 329
Comments Note that these classes of themselves do not forbid a
race condition. This is done by shychronizing access to the
Cubbyhole object. We want to guarantee that the Consumer thread
cant get until the Producer has produced. Need to study wait() and
notify() methods.
Slide 330
How to synchronize code This topic confuses many beginning Java
programmers Two forms: synchronized(objReference){ }//synchronize a
block synchronized void methodName(){}//synch a method Former is
more general, but causes confusion. Best to use simple form
whenever possible. Second form is equivalent to: synchronized(this)
for entire method body
Slide 331
Synchronizing a method Fairly straightforward rules: When a
given thread is executing a synchronized method in an object, no
other thread can execute an other synchronized method on the SAME
OBJECT! We say that the first thread obtains a lock on the object
and doesnt release it until it finishes the synched method Beware
that only code which tries to obtain a lock on the object will have
to wait. For example, if a thread wishes to call a non-synched
method in the object, it will not be blocked.
Slide 332
Synchronizing a block Remember the following rules: When a
thread encounters a synchronized block of code, it attempts to
obtain a lock on the object that is being synchronized upon.
Consider the first thread in a program that encounters the lock.
Since it is the first thread, it will successfully obtain the lock.
Now consider a second thread that encounters any synchronized block
of code that synchronzies on the same object.
Slide 333
Synchronizing a block, cont. This second thread will attempt to
obtain the lock on objReference. It will fail to obtain the lock
unless the first thread has released it. This means that the first
thread must have finished its synchronized block of code. If the
second thread cannot obtain the lock, it must wait until the first
thread releases it.
Slide 334
wait() and notify()/notifyAll() A common scenario is as
follows: A thread enters a synchronized block of code (and thus
obtains the object lock). The code cannot continue the sychronized
block until some other thread has done some work on the same object
and left it in a new state Thus, the first thread wants to
temporarily relinquish the lock to another thread.
Slide 335
wait() and notify()/notifyAll() Called when a thread needs to
wait for some other thread(s) to complete a task before continuing.
The current thread simply calls wait(), and the thread freezes
until another object calls notify() upon the waiting object (or
notifyAll()). notifyAll() is much safer since notify() chooses
randomly!
Slide 336
wait() and notify()/notifyAll() Beware, wait() can only be
called from a synchronized method or block of code. When wait is
called on an object, its lock is released until it is
notified.
Slide 337
Moving out of blocked state Must use the opposite route that
put the Thread into the blocked state If put to sleep, specified
time interval must elapse. If waiting for i/o operation, operation
must have finished. If the thread called wait(), then another
thread must call notify/notifyAll. If waiting for a lock, then
owning thread must have relinquished the lock.
Slide 338
Synchronized Cubbyhole public class CubbyHole { private int
contents; private boolean available = false; public synchronized
int get() { while (available == false) { try { wait(); } catch
(InterruptedException e) { } } available = false; notifyAll();
return contents; }
Interrupting Threads Thread terminates when run method ends.
So, run method should check once in a while whether there is more
work to do in regular way. However, what if thread is sleeping or
otherwise blocked? This is where interrupt() method comes into
play.
Slide 341
Interrupting, cont. When interrupt method is called on thread
that is blocking, the blocking call is terminated by an
InterruptException. public void run(){ try{ while (more work to
do){ do work } catch(InterrupetedException e){ //thread was
interrupted during sleep or wait //do whatever you wish here }
Slide 342
Interrupting, cont. Problem with previous code is that
interrupts only succeed if thread is blocked in call to sleep() or
wait(). Can get around this by calling interrupted() periodically
to see if thread has recently been interrupted: while
(!interrupted() && more work to do){ // do work }
Slide 343
Deadlock Dining Philosophers example
http://java.sun.com/docs/books/tutorial/esse
ntial/threads/deadlock.html
Slide 344
Atomic operations -- Bank Account example See BankTest.java and
SynchBankTest.java
Slide 345
Tips on writing thread-safe code Obvious way is to use
synchronization (see next slide) Performance problems Can lead to
deadlock General rule: dont overuse if possible Local variables
Each thread gets its own copy Immutable sequences Objects which
cant be changed (String, Integer, etc.)
Slide 346
Re-entrant threads Javas model supports a concept called re-
entrant threads. If a thread t obtains a lock on object o by
calling a synchronized method in o (say m1), and then from within
m1 calls a second sychronized method in o m2, deadlock is
guaranteed not to occur.
Slide 347
Other useful methods join() tells the calling thread to halt
execution until the second thread (whose yield method is called),
has completed. Thread t = new Thread(runnableObj); t.join();
Slide 348
Additional Topics Priorities Thread Groups Creating Thread
pools Threads and Swing Higher-level methods Timer class
Slide 349
Distributed Objects Higher level alternative to sockets RMI or
CORBA
Slide 350
Nested Classes
Slide 351
An nested class is a class that is defined inside another
class. To this point we have only studied top-level classes. at
most one public per file arbitrarily man package-scope per file
either package or public ONLY Nested classes introduced in
jdk1.1
Slide 352
Why use nested classes? Simplifies many coding tasks can define
small classes on the fly near the objects created from them +
concise syntax can access outer classes ivs automatically no need
to pass a this pointer to the constructor of separate outer class
can be hidden from other classes in the same package However, price
to pay in terms of complexity, number of gotchas, etc.
Slide 353
Pre jdk1.1 In jdk1.0, the clean and simple class rules were
ballyhooed as a major improvement over C++ Addition of inner
classes complicates things significantly However, they do make
certain code much less awkard to write, particularly when writing
GUIs Still, you do not have to use them, but they can be quite cool
and I do recommend it in moderation!
Slide 354
Types of nested classes Inner classes local anonymous or named
non-local named only Static nested classes non-local named
only
Slide 355
Non-local inner classes Simply a nested class that does not
have the static attribute and is not defined within a class method.
Can be private, public, package, protected, abstract, etc. just
like any class member. Think of outer class as owning inner class
inner class can only be instantiated via outer class reference
(including this) Inner class has access to all outer class ivs,
private or otherwise!
Slide 356
Simple non-local inner class example class Outer{ private int
x1; Outer(int x1){ this.x1 = x1; } public void foo(){
System.out.println(fooing);} public class Inner{ private int x1 =
0; void foo(){ System.out.println(Outer value of x1: +
Outer.this.x1); System.out.println(Inner value of x1: + this.x1);
}
Slide 357
Simple example, cont -- driver Rules for instantiation a little
funny public class TestDrive{ public static void main(String[]
args){ Outer outer = new Outer(); // can create in regular way
Inner inner = outer.new Inner(); //must call new through //outer
object handle inner.foo(); // note that this can only be done if
inner is visible // according to the regular scoping rules }
Slide 358
When to use non-local inner classes Most typically used when
inner class is instatiated from outer class. If classes naturally
belong together, it is cumbersome to pass a this pointer to a
separate outer class just so second class can access first classs
properties/methods. Note that inner class can access outer classs
private data, making them even more powerful than mechanism implied
above!
Slide 359
Local inner classes Inner classes may also be defined within
class methods. These are called local inner classes. Principle
advantage is scoping: such classes are completely inaccessible
anywhere but the method itself where they are defined. Thus, they
have no visibility attribute (public, etc.) Also, can NOT access
local variables other than those declared with final
attribute.
Slide 360
Local anonymous inner classes Local inner classes can be taken
a step further it is not required to give them an explicit name.
This is very convenient when you want to use a class only once and
the code that it contains is succinct. Great example is defining
Swing callback functions.
Slide 361
Anonymous class example but.addActionListener( new
ActionListener(){ public void actionPerformed(actionEvent ae){ //do
work here } );
Slide 362
Final Exam Review Questions
Slide 363
Question0 class A { static void display ( ){ System.out.println
( "Class A" ) ; } } class B extends A { static void display ( ) {
System.out.println ( "Class B" ); } } When we create an object and
call the display ( ) method as:. A aa = new B() ; aa.display ( )
What is displayed ?? What if display is non-static??
Slide 364
Question1 Given a class A with a protected iv ivp, which of the
following are possible ways of accessing ivp? 1. using the this
pointer within a subclass of A within the same package 2. using the
this pointer within a subclass of B outside of the package 3. using
an instance of A from within any class in the same package 4. using
an instance of A from within any class 5. using an instance of A
from within any class in the CLASSPATH
Slide 365
Question2 Given a class A with a private iv ivp, which of the
following are possible ways of accessing ivp? 1. using the this
pointer within a subclass of A within the same package 2. using the
this pointer within a subclass of B outside of the package 3. using
an instance of A from within any class in the same package 4. using
an instance of A from within any class 5. using an instance of A
from within any class in the CLASSPATH
Slide 366
Question3 List the visibility keywords in order of most to
least restrictive. 1. private default protected public 2. public
protected default private 3. private protected default public 4.
public default private protected
Slide 367
Question4 If an iv has private scope in some superclass, then
no subclass can access the iv using the this pointer.
Slide 368
Question5 Immutable classes may contain accessor methods
Slide 369
Question6 Immutable classes are Threadsafe.
Slide 370
Question7 class X{ public boolean equals(Object o){ X anX = (X)
o; if (anX.iv1 == this.iv1) return true; return false; } ? int iv1;
What can be inferred about iv1? private, protected, default,
public, all, some??
Slide 371
Question8-10 Assuming the class X is exactly as it appears on
the previous slide (with public in place of ?), is the following
valid? X x2 = (X) anX.clone(); If so, is this clone and adequate
clone? If not, how would you modify the class X to make it
cloneable? Is X serializable as-is?
Slide 372
Question11 Is it appropriate to store anX in HashMap, again
assuming that X is defined verbatim as you see? Is it legal to
store anX in a HashMap?
Slide 373
Question12 Is it possible for a subclass to override a private
superclass method?
Slide 374
Question13 Can a static variable be used in a non-static
context?
Slide 375
Question14 Can a static method access a non-static
variable?
Slide 376
Question15 Can a class with all static methods be
instantiated?
Slide 377
Questions16-18 public class ClassA { public void methodOne(int
i) { } public void methodTwo(int i) { } public static void
methodThree(int i) { } public static void methodFour(int i) { } }
public class ClassB extends ClassA { public static void
methodOne(int i) { } public void methodTwo(int i) { } public void
methodThree(int i) { } public static void methodFour(int i) { } }
a.Which method overrides a method in the superclass? b. Which
method hides a method in the superclass? c. What do the other
methods do?
Slide 378
Question19-24 Exception handling (T or F) All java Exceptions
must either be caught or thrown. Classes can throw Exceptions.
Static methods can throw Exceptions. main can be declared to throw
Exception rethrowing Exceptions is bad programming style Every
method that throws an Exception should be placed in its own
try-catch block It is bad programming style to have empty catch
blocks, at least in production code.
Slide 379
Question25 Which best describes and Applet? 1. A thin client 2.
A fat client 3. A lightweight web server 4. A full-blown
application server
Slide 380
Question 26-31 All applets extend either Applet or JApplet.
Applets need a main method to run All applets must override at
least the start, stop, init, and destroy methods. start, stop,
init, and destroy methods are declared abstract in the Applet class
Unsigned applets cannot make socket connections to any server.
Unsigned applets cannot access files on the local directory
Slide 381
Somewhat irritating certification type questions
Slide 382
Question 1) Which of the following lines will compile without
warning or error? 1) float f=1.3; 2) char c="a"; 3) byte b=257; 4)
boolean b=null; 5) int i=10;
Slide 383
What will happen if you try to compile and run the following
code public class MyClass { public static void main(String
arguments[]) { amethod(arguments); } public void amethod(String[]
arguments) { System.out.println(arguments);
System.out.println(arguments[1]); }} 1) error Can't make static
reference to void amethod. 2) error method main not correct 3)
error array must include parameter 4) amethod must be declared with
String
Slide 384
Which of the following will compile without error 1) import
java.awt.*; package Mypackage; class Myclass {} 2) package
MyPackage; import java.awt.*; class MyClass{} 3) /*This is a
comment */ package MyPackage; import java.awt.*; class
MyClass{}
Slide 385
What will happen when you compile and run the following code?
public class MyClass{ static int i; public static void main(String
argv[]){ System.out.println(i); }} 1) Error Variable i may not have
been initialized 2) null 3) 1 4) 0
Slide 386
What will be the result of attempting to compile and run the
following code? abstract class MineBase { abstract void amethod();
static int i; } public class Mine extends MineBase { public static
void main(String argv[]){ int[] ar=new int[5]; for(i=0;i <
ar.length;i++) System.out.println(ar[i]); }} 1) a sequence of 5 0's
will be printed 2) Error: ar is used before it is initialized 3)
Error Mine must be declared abstract 4) IndexOutOfBoundes
Error
Slide 387
What will be printed out if you attempt to compile and run the
following code ? int i=1; switch (i) { case 0:
System.out.println("zero"); break; case 1:
System.out.println("one"); case 2: System.out.println("two");
default: System.out.println("default"); } 1) one 2) one, default 3)
one, two, default 4) default
Slide 388
Which of the following statements are true? 1)Methods cannot be
overriden to be more private 2) Static methods cannot be overloaded
3) Private methods cannot be overloaded 4) An overloaded method
cannot throw exceptions not checked in the base class
Slide 389
What will happen if you attempt to compile and run the
following code? class Base {} class Sub extends Base {} class Sub2
extends Base {} public class CEx{ public static void main(String
argv[]){ Base b=new Base(); Sub s=(Sub) b; }} 1) Compile and run
without error 2) Compile time Exception 3) Runtime Exception
Slide 390
What will happen when you attempt to compile and run the
following code?. class Background implements Runnable{ int i=0;
public int run(){ while(true){ i++; System.out.println("i="+i); }
//End while return 1; }//End run }//End class 1) It will compile
and the run method will print out the increasing value of i. 2) It
will compile and calling start will print out the increasing value
of i. 3) The code will cause an error at compile time. 4)
Compilation will cause an error because while cannot take a
parameter of true.
Slide 391
What will be the result when you try to compile and run the
following code? private class Base{ Base(){ int i = 100;
System.out.println(i);}} public class Pri extends Base{ static int
i = 200; public static void main(String argv[]){ Pri p = new Pri();
System.out.println(i);}} 1) Error at compile time 2) 200 3) 100
followed by 200 4) 100
Slide 392
JNI JNI (Java Native Interface)
Slide 393
JNI Stands for Java Native Interface Set of tools/code that
allows user to call native methods from Java. Includes bindings for
C/C++. Can be used to call C/C++ from Java (typical), or Java from
C (invocation API) Differs from spawning executable data is passed
to/from C/C++ method Question: why is this difficult?
Slide 394
Reasons for using JNI Feature not available in java language
(rare). Code already written in another language, dont want to
rewrite (typical). Java is slow (how slow?) Other language has no
additional features per se, but has much better syntax for handling
certain operations (Fortran for math).
Slide 395
Problems with JNI Only provides C/C++ bindings. Going to
Fortran, COBOL, Ada, etc. requires extra step. Not portable Mapping
is not trivial Can be unsafe Cannot run from applet (security
issues)
Slide 396
Machinery for using JNI Steps to follow
Slide 397
Basic steps to calling native code 1. Write java class with at
least one method declared with native keyword. Provide no
implementation public native void sayHello(); Example above is most
simple, but method may pass any parameters or have any return type.
2. Add a call to System.loadLibrary(libname) in the class that
declares the native method: static{
System.loadLibrary(hello);}//static means called only once.
Slide 398
Steps, cont. 3. Compile the class javac Hello.java 4. Produce
the C/C++ header files using the javah utility: Javah Hello This
produces the header file Hello.h 5. Write your implementation file
by first copying the function signature produced in the include
file. Also, #include the header file. #include Hello.h
Slide 399
Steps, cont. 6. Write the implementation in C/C++. This will
require using JNI methods to access the data or possibly casts to
convert to basic C/C++ types 7. Best technique: Break into two
steps. Think of your C/C++ function as a wrapper which accesses the
Java data and maps it to C data using JNI methods, then shoves the
converted data into a prewritten standalone C program.
Slide 400
Steps, cont. 8. Compile your native method(s) as a shared
object (or DLL on Windows). WARNING: Be sure to point your linker
to the include files in /jdk1.3/include and jdk1.3/include/linux
(for example). WARNING: Mixing languages is much easier using a
straight C wrapper rather than C++. 9. Set the environment variable
LD_LIBRARY_PATH to the shared object directory Run main Java
class.
Slide 401
C language bindings What does Java pass to my method?
Slide 402
What does Java pass to my C function? JNIEnv* : A pointer to
the the JNI environment. This pointer is a handle to the current
thread in the JVM, and contains mapping functions and other
housekeeping information. jobject : A reference to the object that
called the native code. (like this pointer). Any arguments
specified by the method.
Slide 403
Pause for some nice pictures
Slide 404
Slide 405
Legacy C calls Java
Slide 406
Java calls legacy
Slide 407
Slide 408
Slide 409
JNI is inter-language glue
Slide 410
Simple examples on union HelloWorld Example: No data passed
Hello.javaHello.java Hello.ccHello.cc Max example : Only native
dataypes Utils.javaUtils.java utils.ccutils.cc Advanced Max
example: Arrays Utils.javaUtils.java utils.ccutils.cc Max
Java-C-Fortran: max.fmax.f
Java object Mappings Object passed by reference All objects
have type jobject as:
Slide 414
Object mappings, cont. For example, if a method getLine exists
in a class call Prompt, then: private native String getLine(String
Prompt); is mapped into JNIExport jstring JNICALL
Java_Prompt_getLine(JNIEnv *, jobject, jstring); But how to access
data/methods from object that is passed in?
Slide 415
JNI Advice Can seem like a bewildering number of functions. Do
not try to learn it all. Keep interfaces very simple. Preferably,
only native datatypes, Strings, and arrays. Be careful about Copies
vs. rerences Freeing memory Best not to allocate memory from with
native code.
Slide 416
Accessing java strings Do NOT do the following: JNIEXPORT
jstring JNICALL Java_Prompt_getLine(JNIEnv *env, jobject obj,
jstring prompt){ printf(%s, prompt); } Why is this bad?
Slide 417
Right way to access Strings Must use special methods in env
structure char *str = (*env)->GetStringUTFChars(env,prompt,0);
/* this maps into regular C char* */ printf(%s, str); /* now it is
ok to print */ (*env)->ReleaseStringUTFChars(env, prompt, str);
/* must release String to avoid memory leaks */
Slide 418
Returning Strings Previous technique allows us to use a String
passed in from Java. What if we want to return a String? Can use
NewStringUTF as: char buf[128]; /* allocate memory for local char*
in C */ scanf(%s, buf); /* read into char* from stdio */ return(
(*env)->NewStringUTF(env, buf)); /* construct and return the
Java String */
Slide 419
Other JNI String methods GetStringChars Takes the Java String
and returns a pointer to an array of Unicode characters that
comprise it. ReleaseStringChars Releases the pointer to the array
of Unicode characters NewString Constructs a new String object from
an array of Unicode Characters GetStringLength Returns the length
of a string of Unicode characters
Slide 420
Java arrays Note that you can NOT do the following: JNIExport
jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj,
jintArray arr){ int i, sum = 0; for (i = 0; i
Array methods The previous example should be written as: jsize
len = (*env)->GetArrayLength(env,arr); jint *body =
(*env)->GetIntArrayElements(env,arr,0); for
(i=0;iReleastIntArrayElements(env,arr,body,0); /* very important
copies back to java array if copy had to be made */
Slide 422
Array methods, cont. Note that there are analagous functions
for float, byte, double, etc: Get ArrayElements Release
ArrayElements Important: These Get functions may copy the entire
array. If this is undesirable, use Get/Set ArrayRegion
functions
Slide 423
Function for accessing arrays FunctionArray Type
GetBooleanArrayElementsboolean GetByteArrayElementsbyte
GetShortArrayElementsshort GetIntArrayElementsint
GetLongArrayElementslong GetFloatArrayElementsfloat
GetDoubleArrayElementsdouble GetObjectArrayElementsobject
Slide 424
Functions for releasing arrays FunctionArray Type
ReleaseBooleanArrayElementsboolean ReleaseByteArrayElementsbyte
ReleaseShortArrayElementsshort RelaseIntArrayElementsint
ReleaseLongArrayElementslong ReleaseFloatArrayElementsfloat
ReleaseDoubleArrayElementsdouble
ReleaseObjectArrayElementsobject
Slide 425
Calling java methods What if you pass a java object to a C
routine and wish to call back a method on the Java object. Good to
avoid this when you can but sometimes it is very important. Need to
use the jobject reference that is passed in by java.
Slide 426
Steps to follow Native method calls JNI function GetObjectClass
returns the jclass object that is type of that obj Native method
calls JNI function GetMethodID returns jmethodID of method in class
(0 for no such method) Finally, native method calls JNI function
CallVoidMethod. invokes an instance of method with void return
type. You pass object, methodID, and actual arguments.
Slide 427
A simple alternative spawning a system executable Advantages
Infinitely simpler Portable Can use any native language
Disadvantages Can only pass data to and from vi stdout Must reload
executable for each invocation
Slide 428
Spawning Executable -- technique Process p =
Runtime.exec(some_exec); Use p to manage process:
p.getInputStream(); p.getOutputStream(); p.kill(); p.halt();
Slide 429
Part 2 Extending Web Server Functionality Servlets and JSP
Slide 430
Web Servers A server program that listens on a standard port
and handles http protocol. Http protocol consists mainly of
requests for documents Documents are typically html files Two most
important http protocol elements: GET (request document, may upload
data) POST (request document, upload data). This protocol is hidden
from you by browser.
Slide 431
Early Web Servers Earliest web sites were static: Browser
requests page Server hands over page CGI (Common Gateway Interface)
scripts defined a standard for extending functionality http
GET/POST data could be passed to and processed in separate function
(C, Perl, Python, etc.) This often included call to back-end
database and response to user via modified html document
Slide 432
Shortcomings of CGI E-Commerce became more popular and web
sites became more heavily used. This brought to the fore some
shortcomings of CGI: New process spawned for every hit not scalable
No concept of sesssion or state Pretty low level Security risks (C
in particular)
Slide 433
Servlets Javas answer to CGI, very simple, high- level
Requirements: a servlet-enabled web server When specified by your
web page, web page passes http requests to java method (assuming
everything is setup properly) Servlet method then has access to all
of Java capabilities jdbc very important here. Servlet then writes
html back to user.
Slide 434
Servlets, cont. Important: a web server takes care of all
interactions with the servlet servlet extends functionality. On the
client side, servlet pages are typically requested in one of two
ways: As a regular URL address As a link in a regular html document
Details are server-dependent
Slide 435
Writing servlets All servlets extend the Servlet class. All
http servlets (by far most typical) should extend the HttpServlet
class. In extending HttpServlet, you typically override the
following methods: init, doGet,doPost, destroy (very common) doPut,
doDelete, doOptions, doTrace (rare)
Slide 436
Main HttpServlet Methods init() called once when servlet is
loaded by server. Contains any initializations that are common to
all requests. doGet(HttpServletRequest, HttpServletResponse) Called
each time the servlet receives an http GET request posted by a
client. Passes two objects, one representing the information of the
request, the other used to configure a response.
Slide 437
Main HttpServlet Methods, cont. doPost(HttpServletRequest,
HttpServletResponse) Same as doGet but for an http POST request.
destroy() Called before servlet is unloaded from memory. Performs
any final cleanup, freeing memory, closing connections, etc.
Slide 438
Service Method Important: The method
service(HttpServletRequest, HttpServletResponse) is also called for
each servlet invocation. Service() in turn calls doGet and doPost,
etc. It is best not to override service even if you want to handle
doGet and doPost identically. Simply have one call the other.
Slide 439
HttpServletRequest Object Passed when browser calls doGet and
doPost. Most import methods for beginning servlet programming
getParameter(String paramName) getParameterNames()
getParameterValues() Makes getting data from web pages very simple.
Many other methods for images, cookies, etc.
Slide 440
HttpServletResponse Object Passed when browser calls doGet or
doPost Most import methods for beginning servlet programming:
getWriter(); Get Writer for communicating back to client
setContentType(String); Typically use text/html, indicating that
html will be sent back to the browser
Slide 441
Examples Use html form to connect to servlet, accept form data,
and then echo it back with the output stream. Postdata.java : Java
servlet Postdata.java Form.html : HTML front-end Form.html Basic
steps very simple just need to know a little HTML and a few Java
methods
Slide 442
General Comments Recall that each request for a servlet gets
its own thread but access the same methods. Thus, synchronization
issues arise.