Given by Nancy McCracken, Geoffrey C. Fox at DoD Modernization Users Group Conference Monterey on June 7 99. Foils prepared July 6 99
Outside Index
Summary of Material
Overview of Java features and uses |
Details of language features:
|
Java Grande Forum
|
Outside Index Summary of Material
Geoffrey Fox and Nancy McCracken |
Northeast Parallel Architectures Center |
at Syracuse University |
http://www.npac.syr.edu/projects/tutorials/Java |
http://www.npac.syr.edu/projects/tutorials/JavaCSE |
Overview of Java features and uses |
Details of language features:
|
Java Grande Forum
|
What is Java?
|
Java is interesting because
|
The Web is becoming the dominant software development arena; this will drive Java as the best supported, most widely taught language |
The Java Language has several good design features
|
Java has a very good set of libraries covering everything from commerce, multimedia, images to math functions (under development at http://math.nist.gov/javanumerics) |
Java has best available electronic and paper training and support resources, growing labor force trained in Java |
Java is rapidly getting best integrated program development environments |
Java naturally integrated with network and universal machine supports powerful "write once-run anywhere" model |
HPCC is a small field and Scientific Computing a modest size field with limited resources for very hard problems and must leverage as much software as possible |
Web Software provides an excellent pervasive user interface with Java Applets and WebWindows |
Web Software provides a potentially excellent high performance object oriented language (Java) for scientific and engineering computation |
All(!?) we need to do is to add high performance and special features of scientific computing (math libraries) to the Web! |
Technology for generating parallelism (user decomposition, parallelizing compilers) not provided by web and must come from HPCC |
Bottom of Pyramid has 1000 times dollar value and compute power of best supercomputer (tip of pyramid) but supercomputer has high performance network to support close synchronization needed by classic parallel algorithms |
Web Software MUST be cheaper and better than MPP software as factor of 100 more money invested! |
Therefore natural strategy is to get parallel computing environment by adding synchronization of parallel algorithms to loosely coupled Web distributed computing model |
web server |
Java code |
is compiled |
to produce |
applet codes, |
called bytecodes, |
part of web |
document |
collection |
web client, running browser |
such as Netscape or IE |
executes (restricted) |
applet code to display |
in browser window |
Internet |
Browsers (Netscape 2.0/3.0/4.0, HotJava, Microsoft IE ...) supporting Java allow arbitrarily sophisticated dynamic multimedia applications inserts called applets, written in Java, to be embedded in the regular HTML pages and activated on each exposure of a given page. |
Java code |
is compiled |
to produce |
bytecodes |
run by Java |
interpreter |
to produce |
results |
OR |
Java code |
is compiled |
to produce |
native code |
run directly |
on machine |
for better |
performance |
Java applications are compiled and run on a machine just like any other general programming language such as C/C++. No web server or network are required although Java applications may also use network connections for distributed computing. |
The Java compiler and interpreter come in a software package called the Java Development Kit. |
The compiler, called javac, produces bytecodes, which is compiled code, not for any particular machine, but for the Java Virtual Machine (VM), and abstract machine definition. Thus the compiled code is architecture independent. |
The interpreter, called java, executes the bytecodes for a particular machine. The semantics are carefully specified to be the same on all machines. |
There is also a program primarily for debugging, called appletviewer, to view applets, a sort of mini-browser. |
Currently in use are two versions:
|
All Java programs are written into a file with a ".java" extension. |
Applications are .java files with a main method which is excuted first. |
How to compile and run a Java application (via bytecodes):
|
Since Java is object-oriented, programs are organized into modules called classes, which may have data in variables and subroutines called methods. |
class HelloWorld |
{ public static void main (String[] args) |
{ System.out.println("Hello World!"); |
} |
} |
Each program is enclosed in a class definition. |
main() is the first method that is run. |
The notation class.method or package.class.method is how to refer to a public method (with some exceptions). |
Syntax is similar to C - braces for blocks, semicolon after each statement. One difference: upper and lower case matter! |
Java applets are classes written in Java which are intended not to run as stand-alone programs (as applications do) but as subprograms of a browser which is already managing a window. |
Applets should NOT have main method but rather methods called init, start, paint etc. for displaying on the browser window |
Applets are not trusted as a default, so they have several restricitions on running on the client machine
|
The applet should be run through javac compiler getting a .class file as before: javac MyApplet.java |
The resulting file MyApplet.class is then stored in the document collection of a web server (hence has a URL location). |
Also create an HTML file (say MyApplet.html) with an applet tag to MyApplet.class. |
When the browser loads the .html file, it will also download the .class file and invoke the java interpreter to run the init, start, and paint methods. |
Java applets are part of the class hierarchy that can call methods to display on a screen (within the browser window). One way to draw on the screen is to call the method drawString from the standard method paint. |
import java.awt.Graphics; |
public class HelloApplet extends java.applet.Applet |
{ public void paint (Graphics g) |
{ g.drawString("Hello World!", 5, 25); |
} |
} |
The import statement allows the use of methods from the Graphics class without the dot notation . |
The paint method displays a graphics object on the screen - one of the standard methods that takes the place of main for applets. |
Puts this as a subclass of Applet. |
You should name the file with your applet name, HelloWorldApplet.java, run the compiler (javac), getting a bytecode file HelloWorldApplet.class, which you put in a web directory. |
<html><head> |
<title>Simple Hello Page</title> |
</head> |
<body> |
My Java applet says: |
<applet code="HelloWorldApplet.class" width=150 height=25> |
</applet> |
</body></html> |
Name of your applet class. |
The browser will use a rectangle of width 150 pixels and height 25 pixels to display the applet within the other html. |
Distributed applications on the web naturally have a multi-tier architecture. |
Java plays a role at all three levels:
|
Middle level servers |
Client user interface running through browser |
Internet |
Internet or proprietary network |
Backend computing or databases |
Java for the Graphical User Interface and client side analysis systems, including visualization: Java has unique advantages over other languages |
Java for Coarse Grain Software Integration: as in collaboration and metacomputing
|
Java as a high performance scientific language: for "inner" (and outer) loops
|
The original resource was The Java Language Specification by Sun Microsystems, Inc., March 1995 updated to October 1995 but superceded by
|
http://www.javasoft.com web site has plenty of references including
|
There are a multitude of Java books, many are excellent, here are two we have used for course textbooks:
|
The most highly recommended reference book
|
These range from simple tools that give a windowing interface to the edit/compile/run or view cycle:
|
to the elaborate commercial development environments that can also track projects and help generate code for user interface components
|
Java syntax has many similarities to C and C++. |
Some differences
|
Some similarities
|
A variable is either a primitive type such as int, float or double, or it is an object. |
Note that there is no primitive type for Complex. |
Type Size in bits Values: example Standard |
boolean 1 true or false |
char 16 \u0000 to \uFFFF ISO Unicode |
byte 8 signed integer: 0 |
short 16 signed integer |
int 32 signed integer |
long 64 signed integer |
float 32 floating pt: 0.0f IEEE 754 |
double 64 floating pt: 0.0 IEEE 754 |
Arrays are objects, but have a special syntax for creating and indexing, more like C and C++.
|
For an array of length n, indices run from 0 to n-1. There is run-time checking of indices. |
Multi-dimensional arrays are arrays of arrays
|
Arrays can have values that are any type of object
|
public class SumArray |
{ |
public static void main (String[] args) |
{ // array declaration |
int a[ ] = new int[10]; |
int total=0; |
/* initialize a - note the use of array instance variable length */ |
for (int i = 0; i < a.length; i++) |
{ a[i] = i * 5; } |
/* sum the array */ |
for (int i = 0; i < a.length; i++) |
total += a[i]; |
System.out.println( "\n" + "The sum of the array is " + total + "\n"); |
} |
} |
Familiar C operators ++ and += |
String catenation |
Programs are composed of a set of modules called classes. Each class is a template specifying a set of behaviors on the data of the class. |
Each class has instance variables to hold the data and methods (called functions or procedures in other languages) to define the behaviors. Each object in a program is created as an instance of a class. Each class instance has its own copy of the instance variables. |
Classes can be used for data encapsulation, hiding the details of the data representation from the user of the class (by marking variables as private). |
Instance |
Variables |
Methods |
The class definition consists of
|
public class FAstate extends otherClass implements someInterface { // instance variables private int state; //constructors public className ( . . . parameters . . . ) { . . . initialize instance variables (perhaps with parameters) . . . } // other method declarations public int getState ( ) { return state; } public advanceState ( int inc ) { . . . Change the state, using parameter inc . . . } } |
In the Java class header, we put B extends A which means B is a subclass of A, if B has all the variables and methods of A (and more). |
In the class definition of B, the child class, there is no need to repeat declarations of variables and methods of A, they are assumed to be there. The definition of B has the additional variables and methods of B. |
Or B may give a new definition of some method of A. This is called overriding. |
The modifiers in the class head control how other classes can access this one:
|
These modifiers are also used for access control to the instance variables and methods. |
There are other modifiers. For example, a static variable or method only has the same value for all instances of the class. A final variable cannot be assigned to (used for constants). |
Some classes, such as our hello application, have just one or more method that will be executed as a program. Only one instance of these classes is created (by the interpreter). |
Other classes are used to structure data, such as the previous example. Another example might be to have a class to represent type Complex. It would have
|
A computational class could create several instances of the class Complex and use them with the methods for arithmetic. |
A package is a collection of classes. |
Java directly associates the names of classes and packages with the directory (folder) structure:
|
Packages of classes may be defined by users as well as forming the structure of the remaining Java libraries. |
What we have seen so far is all there is to the base language Java (with the exception of Exceptions!). All of the rest of Java functionality comes as classes defined in packages that come with the language. |
Suppose that you want to use two Buttons in an applet. The Button class is in the package java.awt. java.awt.Button b1 = new java.awt.Button( "label" ); All objects created this way are represented internally as references. |
Or you can more succintly use the import statement to open the context of the package java.awt: |
import java.awt.*; |
public class MyApplet extends java.applet.Applet |
{ public void init ( ) |
{ Button b1 = new Button ( "start"); |
Button b2 = new Button ( "stop"); |
. . . b1.setLabel ( "pause"); |
} |
} |
This calls the class constructor method Button to create the new instance and initialize the label . |
Exceptions are run-time errors that may arise
|
They are handled with try and catch blocks: try { some code that may generate an exception } catch (Exception ex) { some code to handle this case } |
Exceptions are described by objects which are instances or subclasses of the class Exception. You may create your own. |
You don't have to handle all run-time exceptions such as divide by zero and array index out of bounds. |
Java has classes for a rich set of data structures.
|
This package contains all the classes to create graphical user interfaces. |
It allows some primitive drawing (in a subpackage called graphics). |
It has a number of components corresponding to parts of a windowing interface
|
There are layout managers to help arrange the components. |
There are events and a model to handle events that come from user interactions such as clicking a button or typing in text. import awt.* ;
|
Think of a Java applet as a graphics window on which to draw text and other objects |
The graphics window has a particular width and height as specified in the <APPLET> tag |
The origin is in the top left-hand corner of the graphics window: the x-coordinate increases from left to right, while the y-coordinate increases from top to bottom |
There are graphics methods to draw lines, arcs, ovals, rectangles and other shapes. Here is one method: |
The drawRect(...) method draws a rectangle anchored at point (x,y): public void drawRect( int x, int y, int w, int h ); |
For example, this can be used to draw histograms. |
(x,y) |
w |
h |
For each basic component, one can create one or more instances of the component type and then use one of the "add" methods to place it into a Container such as an applet window.
|
For each basic component, additional methods allow access to the properties of the components:
|
Click here |
Initial text |
The user can interact with the GUI on many of its components, by clicking a button, typing in text, etc. These actions cause an Event to be generated, which will be reported by the system to a class which is an Event Listener, and which will have an event handler method for that event. This method will provide the appropriate response to the user's action. |
An Event Listener is an instance of any class that wants to receive events. |
An event source is an object that generates events.. An event source will keep a list of event listeners who want to be notified for particular events.
|
The event source notifies event listeners by invoking a particular method of the event listener (aka the event handler method) and passing it an Event object, which has all the information about the event.
|
Each basic component has a defined Event class, Listener interface, and event handling method names. |
Note that an interface is a class in which there are headers of methods with no method body. It just gives the name(s) of methods such as actionPerformed that the user is to provide. |
public class MadLib extends java.applet.Applet implements ActionListener |
{ Button firstmadlib, clearbutton; Label prompt1,prompt2; |
TextField input1, input2 ; TextArea output ; |
. . . . . } |
public void init ( ) |
{ // add labels and textfields (without events) |
prompt1 = new Label ( "Enter a noun: ") ; add ( prompt1 ) ; |
input1 = new TextField ( 20 ) ; add ( input1 ) ; |
. . . } |
public void actionPerformed (ActionEvent event) |
{ if ( event.getSource ( ) == firstmadlib ) |
{String word1 = input1.getText ( ) ; |
output.setText (word1 + . . .); . . . } |
if ( event.getSource ( ) == clearbutton ) |
{input1.setText ( "" ) ; . . . }} |
The various panels in a container are laid out separately in terms of their subcomponents |
The arrangement is controlled by general strategies which are embodied in 5 LayoutMangers |
To create a layout, such as FlowLayout, in your panel:
|
Other Layout Managers:
|
The AWT has many additional capabilities. It can create separate windows either in the form of frames or dialog boxes.
|
The "swing" set has more advanced features such as internal frames, dynamically sized tables, trees, color choosers, overlapping components, progress bars, popup menus and many other sophisticated user interface elements. |
Threads are "light-weight" processes (unlike UNIX processes), which communicate by a combination of shared memory and message passing
|
Java threads are limited and for those coming from an HPCC background, we note Java threads have no immediate support for some key parallel computing concepts such as distributed memory (threads running in separate operating system instances) |
Java threads are based on a locking mechanism using monitors for synchronization, introduced by Hoare in 1974 |
One way to create threads is to write a separate class that subclasses the Thread class. |
The main line of execution is put in a method called run(), which overrides the method of the same name from the Thread class. |
Instances of this subclass are created like this:
|
Thread control:
|
Another way to introduce a thread is to create a thread that uses a run method in another class. This class has to be declared to implement the interface Runnable, which has one method called run. |
This is the correct way to run an animation in an applet, which can show a simulation or other sequence of drawings. |
We have created a template program for an applet with a drawing area for the animation and a layout with room for several control buttons, textfields, etc. |
In Java, two threads can communicate by accessing a shared variable (shared-memory model). |
If two threads can both modify an object, that is, they can both execute a method that assigns to a shared variable, then the modifications must be synchronized. |
This is easy - just declare the method to be synchronized! |
This means that Java will ensure that only one thread executes the method at a time and is not interrupted. |
Suppose more than one thread has an instance of an account:
|
Often, one thread is producing some data, while another thread wants to use it. |
A flag variable is introduce that both threads can check. |
If the data is not ready (flag is false), the consuming thread can call the method wait ( ), which causes it to be suspended until some other event occurs. |
When the producing thread has some data, it can set the flag to be true and call the method notify ( ), which causes an event that will "wake up" one of the suspended threads. |
If the user doesn't get the logic right, there are possibilities for deadlock or other forms of non-progress. |
A stream is a sequence of bytes or characters. |
All types of streams are treated similarly, but may have different stream sources and sinks:
|
The most basic byte streams are InputStream and OutputStream. These classes have methods that can read or write a byte from or to a stream:
|
All of the above methods throw a possible IOException. |
The read() and write( int ) methods "block" during transfer. |
To read and write text, numbers, etc., you layer various filters on top of the basic input and output streams. These classes have additional methods to read and write data, both ascii and binary. |
For example, opening a file and reading lines of text: BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream( "filename.txt" ) ) ); while (( line = in.readLine() ) != null ) { buffer.append ( line + "\n"); } in.close ( );
|
While applications can read/write files, view file directory structure, create file dialog boxes, and so on, applets are more resricted (without using certificates to relax security on the client machine). But an applet can read data from a file on the host that the applet was downloaded from. |
We have created a template program that reads data from a file and displays it. This is the template for the Java CFD examples at NPAC. |
A Java application can create and use URL's to anywhere; applets are restricted to URL's to their own web server.
|
A method URL.openConnection() returns an instance of class URLConnection:
|
Applications can also use conn.getOutputStream(), but not applets. |
Note that one can connect not just to HTML files but also to CGI scripts and other web documents. |
A java applet, which is downloaded from a web server host, can connect via a network socket to any port on the same machine. This could be a java application acting as a server. |
Java applications can connect network sockets to any host machine on the Internet
|
web server host machine |
browser |
Applet is downloaded |
from web server |
applet |
Internet |
80 |
nnnn |
web |
server |
Java |
application |
Socket based on |
TCP/IP protocol |
web server |
host machine |
applet |
Internet |
nnnn |
Java |
application |
Sockets |
applet |
Java |
application |
Java |
application |
Java application acting as a server |
A Java application can open sockets to any number of clients |
Again, note that socket communication is via streams, where the client and server agree on a message protocol to communicate . |
Applets and applications acting as clients |
Java RMI allows the programming of distributed applications across the Internet at a more abstract level than sockets. One Java application or applet (the client in this context) can call the methods of an instance, or object, of a class of a Java application (the server in this context) running on another host machine. |
An example of Distributed Object Programming - similar to CORBA, except that CORBA allows the remote objects to be programmed in other languages. |
The goal is to make calls to remote methods on the local machine have the same syntax and semantics as local calls. |
Local Machine |
Remote Machine |
Local Java |
local method |
Remote Java |
remote method |
One key piece is a server that acts as the network lookup, a naming registry from which the client can get a reference to the remote object (the server). |
Another key piece is object serialization. Parameters to and from the remote methods must be sent in a standard encoding across the network. |
client |
Server with |
implementations |
of remote methods |
Naming registry |
RMI |
RMI |
RMI |
Calls to methods in the remote object may pass parameters and receive results |
Java is now being used to develop web servers. |
Java is also being used as the language to develop server side code for web servers, using the Common Gateway Interface (CGI) of the HTTP protocol. These are called servlets.
|
JDBC provides a set of classes for Java with a standard SQL database access interface.
|
Provides an API for database "drivers" to make actual connections and transactions to database products.
|
JDBC is "low-level" interface, calling SQL commands directly but is meant to be a base for higher-level interfaces. |
Java application or applet with JDBC |
Java applet or |
HTML browser |
Application Server (Java) |
with JDBC |
Jdbc Driver |
DBMS |
Two-tier Model |
Jdbc Driver |
DBMS |
Three-tier Model |
DBMS Proprietary Protocol |
DBMS Proprietary Protocol |
The JDBC API is in the package java.sql. |
The classes include a DriverManager that keeps track of available database drivers. Download the driver you want and use it to connect to the database server. |
Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection ("jdbc:oracle:thin:@carver.npac.syr.edu:1521:europe", "dbusername", "dbpassword"); |
There are several classes for making SQL statements.
|
The query returns a result set, which has database table rows satisfying the query.
|
SQL statements may insert, update and delete, and may execute stored procedures in the database. Additional classes deal with transaction commit and rollback. |
"Reusable software components that can be manipulated visually in a builder tool." |
They are Java's implementation of "component-based" visual programming |
This modern software engineering technique produces a new approach to libraries which become a "software component infrastructure(SCI)" |
There is a visual interface to discovery of and setting of values of and information about parameters used in a particular software component |
JavaBeans uses the event model of JDK1.1 to communicate between components |
The visual interface allows inspection of and implementation of both individual beans and their linkage (events) . This visual construction of linkage allows one to form nontrivial programs with multiple communicating components |
A Java Bean component can be a simple GUI component such as a Button or a complex program with many properties and methods such as a spreadsheet. |
Apart from the event mechanism used for communication and linkage, ComponentWare (and JavaBeans in particular) "just" give a set of universal rules (needed for interoperability) for rather uncontroversial (albeit good) object-oriented and visual programming practices |
Encourages and develops the use of Java for
|
Java has potential to be a better environment for "Grande application development" than any previous languages such as Fortran and C++ |
The Forum Goal is to develop community consensus and recommendations for either changes to Java or establishment of standards (frameworks) for "Grande" libraries and services |
These Language changes or frameworks are designed to realize "best ever Grande programming environment"
|
Two major working groups promoting standards and community actions |
Numerics: Java as a language for mathematics led by Ron Boisvert and Roldan Pozo from NIST
|
Distributed and Parallel Computing led by Dennis Gannon and Denis Caromel (INRIA, France)
|
Development of Grande Application benchmarks |
The Java Grande forum has a draft proposal for a class to implement type Complex, although there are still several difficulties in having a class instead of a primitive type:
|
The Forum is working with Sun on these issues. |
One version of the constructor: Complex z = new Complex ( x, y ); // x and y are doubles |
Syntax for operators: Complex z1, z2, z3; z1 = Complex.plus ( z2, z3 ) ; or z1 = z2.plus ( z3 ) ; |
Many additional operators |
Definitions based onC9x Annex G:"IEC 559-compatible complex arithmetic. |
There is a rectangular array interface, which would allow multiple implementations. |
Class doubleArray implements part of the interface by providing get and set methods for indexing elements. |
Classes doubleArray1D, doubleArray2D, . . . implement the various ranks |
One of the constructors: new doubleArray2D ( a ); takes a Java array a of type double[ ] [ ] and makes a rectangular array of the same shape and values. |
Various get methods allow to select elements, rows, columns, or various slices. The implementation may store the array as a 1D object and can thus optimize these operations. |
There is a rectangular array interface, which would allow multiple implementations. |
Class doubleArray implements part of the interface by providing get and set methods for indexing elements. |
Classes doubleArray1D, doubleArray2D, . . . implement the various ranks |
One of the constructors: new doubleArray2D ( a ); takes a Java array a of type double[ ] [ ] and makes a rectangular array of the same shape and values. |
Various get methods allow to select elements, rows, columns, or various slices. The implementation may store the array as a 1D object and can thus optimize these operations. |