Given by Nancy J. McCracken,Geoffrey C. Fox at Peking Tutorial, Web Certificate on Spring-Summer 1997. Foils prepared 18 May 97
Outside Index
Summary of Material
In Part 1 2 and 3 of the Tutorial We Covered:
|
In This Part of the Java Tutorial We Cover: |
Threads in Detail |
Useful Java Classes
|
Networking and I/O |
Futures and HPCC Implications |
Outside Index Summary of Material
Instructors: Geoffrey Fox , |
Nancy McCracken |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
Java is remarkable for threads being built into the language |
Threads are processes which are typically "light-weight" (unlike UNIX processes) which communicate by a combination of shared memory and messaging
|
The Java Threads do not give all you want and for those coming from an HPCC background, we note Java threads have no immediate support for some key parallel computing concepts (see work of Chandy at Caltech) and distributed memory (threads running in separate operating system instances) |
Java threads are based on basic monitors ("lock mechanism") for synchronization which was introduced by Hoare |
One can implement threads in two ways
|
Only the second way is possible for applets as these already extend Applet class and so cannot multiply inherit from the Thread class |
Threads must have a run method which is code Thread executes. |
If you are using first way, this is written for this particular thread and overrides run() in Thread class |
In second way, the created Thread automatically takes its run() method to be the run method of the applet |
Threads enable you to have multiple flows of control, running concurrently. |
Concurrency does not necessarily mean that threads actually run at the same time, but that the Java interpreter switches between threads. |
Threads may also be assigned priority, in which case the higher priority thread may pre-empt the lower one. |
Each thread is always in one of five states, shown in this diagram with the most common methods for changing state: |
Synchronized methods and blocks are implemented in the applet class by acquiring a lock before running |
Code will therefore not run at the same time as other code that needs access to the same resource. |
Each object has one lock associated with it and each class has exactly one lock |
When invoked, a synchronized method waits until it can acquire the lock for the current instance (i.e., this); a static synchronized method waits to acquire the class lock |
Lock is released when code is done executing |
Locks are advisory |
synchronized blocks specify the object on which to synchronize |
A Synchronized method provides a guarantee that the method is the only synchronized method in the object running at the time. |
This is useful if the resource is contained completely in the object, and in general, no waiting for a resource is necessary. (The operation is contained completely in the method)
|
More fine-grained synchronization can be obtained by synchronizing on the particular object:
|
void wait() |
void wait(int timeout)
|
Threadsafe Variables |
void notify() |
void notifyAll()
|
notify() notifies the thread associated with given synchronization object that has been waiting the longest time |
notifyall() notifies all threads associated with given object |
One can mark a variable as "threadsafe" to notify the compiler that only one thread will be modifying this variable. |
public class AddApplet extends Applet implements Runnable {
|
public class Object is the root of the Class hierarchy. Every java class has Object as its ultimate parent and so any object (object with a small o is any instance of any class) can use methods of Object |
Methods of Object (used as object.Method()) include: |
clone() Creates a clone of the object |
equals(another object) compares two objects returning boolean answer |
getClass() returns a descriptor of type Class (a child of Object) defining class of object |
toString() returns a String which represents "value" of object. It is expected that each subclass will override this method |
wait() in various forms is used to cause threads to wait |
finalize() contains code to perform when object is deleted by system (I.e. garbage collected) |
Suppose an object is called obj , then we get Class of obj by |
Class itsclass = obj.getClass(); // and the name of this class by: |
String name = itsclass.getName(); |
One can also use instanceof in following fashion |
"foo" instanceof String // is evaluated to true but |
mPoint pt = new mPoint(x,y); |
pt instanceof String // is evaluated to false |
"types" such as int char float etc. are NOT classes |
Thus one cannot use methods such as |
int var; |
var.toString |
Thus ALL types have associated wrappers used like |
Character wrappedchar = new Character(char); |
now wrappedchar has lots of good methods you can use such as: |
wrappedchar.equals(anotherobject); |
wrappedchar.toString(); |
There are also static (class) functions such as: |
toUppercase(char ch); |
isUpperCase(char ch); |
This class provides the standard mathematical functions, using types int, long, float and double as appropriate. |
It is a static class, meaning that you only use the methods, never creating objects from this class. |
The methods include
|
This class exists to provide an implementation of "date" structures. As is typical of data encapsulation classes, it has methods to create dates, obtain and set the parts of dates, and convert dates to other data types. |
The constructor either creates today's date or any other day (and time) that you provide:
|
Strings are fixed length collections of Unicode characters stored as an instance of the class. |
Most commonly, a string is created from a string literal or by using the constructor on an array of characters:
|
or
|
Once created, individual characters of a string cannot be changed in place. This example shows using the methods of indexing, catenation (+), and substring to create a new string with one character changed:
|
String comparison can be done with the methods equals and equalsIgnoreCase. Note that == tests if two strings are the same string instance, while equals tests if two different strings have the same characters. |
Other methods include length, CharAt and toString. |
The StringBuffer class has mutable strings, but is created with a fixed maximum size. It has methods such as append to extend the length of the string. |
This class returns object of class String which reverses order of characters in input object source which is also an instance of class String |
class ReverseString {
|
In Java, while you can give the size of arrays at run time, you cannot dynamically change the size of an array during the computation. The vector class provides a data structure with this property - the restriction is that all of the elements must be of type Object.
|
A vector is created with an "initial capacity" and a "capacity increment". It always starts with 0 elements. As you add elements, if the initial capacity is exceeded, then more memory is automatically allocated in the size of the capacity increment. The default is an initial capacity of 10 and an increment which doubles each time.
|
Elements are created with the addElement method:
|
The object missouri of type Order is automatically converted to an Object in vector instance orders defined on previous foil. |
There are methods for indexing vectors. Like arrays, the indexing is zero-based.
|
The length of the Vector can be obtained:
|
This class is similar to the Perl associative array (or hash array with {} brackets). It can store a set of key and value pairs, neither of which can be null.
|
Values are retrieved by indexing with a key. Like Vectors, Hashtables only store things of type Object and you must cast the result.
|
If there was no entry, a null is returned. |
Performance of the Hashtable can also be affected by giving an initialCapacity and a loadFactor for reallocation. |
Streams are an abstraction of a sequence of bytes. |
The sources and destinations of these sequences can be
|
That is, all of these types of I/O are treated in the same way. |
The most basic I/O streams are InputStream and OutputStream. These classes have methods that can read or write a byte from the stream:
|
There are also methods for reading and writing arrays of bytes. |
These methods all "block" on the read or write during the data transfer. |
The subclasses of InputStream offer more methods that can read the stream in a more structured way or provide other functionality. |
Standard UNIX file I/O methods are available |
FileInputStream s = new FileInputStream("/usr/gcf/greatidea"); |
There is a clever class called FilterInputStream which can be used to add value to a raw InputStream. You can define your own filters but important ones provided are:
|
These streams can be constructed from each other or InputStream to give added functionality. If "is" is an InputStream, then it can be converted to a buffered input stream with methods from datainputstream: |
DataInputStream data = new DataInputStream(new BufferedInputSream(is)); |
This area will evolve rapidly as existing I/O systems get linked to Java with special classes such as those needed to link MPI (HPCC Message Passing) or Nexus (Well known distributed memory thread package) |
One can establish Web Connection with URL class and access documents there |
One can set up a more general URLConnection for more general input/output operations through Web(HTTP) protocol |
One can set up a Socket link which is permanent rather than on again off again Web client-server interaction |
One can send messages and so transfer information between different Applets |
One aspect of Java security is language restrictions designed not to let a Java applet or application access memory on the machine outside of its own space. |
Applets have additional restrictions:
|
As of summer 1996, no known applets have seriously broken security to steal client information or trash the local disk. Exceptions:
|
This table shows what Java programs can do in the following four cases:
|
JA - Java application (not an applet)
|
read local file no no yes yes |
write local file no no yes yes |
get file information no no yes yes |
delete file no no no yes |
run another program no no yes yes |
read the user.name proper no yes yes yes |
connect to network port on server yes yes yes yes |
connect to network port on other host no yes yes yes |
load Java library no yes yes yes |
call exit no no yes yes |
create a pop-up window with warning yes yes yes |
First you set the URL in various ways using something like |
String npacurl = "http://www.npac.syr.edu/index.html"; |
try { theinputurl = new URL(npacurl); } // URL class is in java.net |
catch ( MalformedURLException e) {
|
where you are meant to test to see if URL is legal! |
The simplest thing to do now is to see this page with |
getAppletContext().showDocument(theinputurl, Frame targetdisplayframe); |
More interesting is to access a URL and process the information there! |
This is done using streams: |
There are methods in class URL -- |
InputStream in = instanceofURL.openStream(); // opens an InputStream associated with given url |
More general is instanceofURL.openConnection() establishes a general connection and returns an instance of class URLConnection
|
Note that one can connect not just to HTML files but also to CGI scripts i.e. programs at server and so obtain flexible connectivity |
This applet creates a text area in the window, reads text from a file known by its URL, and displays the text in the text area. It uses the class URL from java.net, to set up a socket to the server, and the class InputStream from java.io. |
The openStream method opens the socket connection and returns an object of type InputStream. We convert this to a BufferedInputStream for performance and then to DataInputStream, where we have methods to read lines or characters of data. |
A Java applet or application can open a socket to a Java server application through the Socket class.
|
or Socket t = new Socket(this.getCodeBase().getHost(), port) |
The latter form is useful for applets as the applet can only use a socket to a server application running on the web host machine that the applet code was downloaded from. |
Sockets have methods getInputStream and getOutputStream which can be used for communication. Note that both communication directions are possible at the same time on a socket. |
A Java application can open a single Socket on a port and open an InputStream and OutputStream just like the client, but in general, a server will want to be able to open multiple sockets to establish communication with a number of clients at the same time. |
The ServerSocket class allows multiple sockets:
|
Then the Java server application can use the accept method to open a socket for each client which tries to open a socket on the port:
|
Typically, a server main program would be waiting to accept a client. When a client tries to establish a socket, the accept proceeds. Then the server would spawn a thread to handle that one socket, opening input and output streams as necessary and communicating with the client. |
One can essentially augment supplied Java Runtime by supplying your own C or other code implementing a particular functionality in a higher performance mode |
This of course generates machine dependence and should only be used if really needed |
First for classes you wish to implement in native fashion, put in your java code lines like: |
public native mustgofast(arguments); // default functions |
static { System.loadLibrary("faststuffhere"); } // static and in class and so runs only ONCE! and loads the native code |
Advantages
|
Disadvantages
|
So usually user defined native method can not be used remotely in Applet.
|
The activities that has gone into defining High Performance Fortran (HPF) and HPC++ can be reexamined for Java which is quite well suited for parallelism as
|
Interesting Compiler challenge independent of parallelism, is to produce efficient code from bytecodes. Here a technique called "just in time" compilation does compilation at runtime and can increase performance of Java code to within a factor of 4 (today) to 2 (tomorrow) performance of C |
Surely many will produce Fortran C PASCAL to Java translators so you can webify your existing applications
|
Current runtime (java Threads) assume shared memory but there are interesting possible distributed memory and distributed shared memory implementations |
One can imagine a data-parallel interface where methods would implement array and other data parallel operations with distributions specified by annotations as in HPF
|
Important implication for parallel CORBA using Java classes to interface with CORBA |
Java based servers will allow data and task parallel Java to implement World Wide compute webs |
see http://www.npac.syr.edu/projects/javaforcse |