Full HTML for

Basic foilset Java Tutorial - Fall 1997 Part 4: Multithreading, useful Java classes, I/O, Networking, and the future

Given by Nancy J. McCracken,Geoffrey C. Fox, Tom Scavo at CEWES Tutorial, CPS606, JSU Class CSC499 on July 22-25 1997, Fall 97. Foils prepared 17 Nov 97
Outside Index Summary of Material


In Part 1 2 and 3 of the Tutorial We Covered:
  • Overview including History and alpha versus production issues
  • Comparison of Java and Javascript
  • Overall Java Philosophy and Features including security etc.
  • Java Programming Language
  • Introduction to Applications,Applets and their Invocation from HTML
  • "Hello World" and Basic Graphics Applets
  • Object Oriented and Class Structure
  • Methods, Constructors etc.
  • Interfaces
  • Exceptions
  • Introduction to Threads
  • Graphics in more detail
  • Downloading and Drawing Images
  • Abstract Windowing Toolkit
  • Keyboard and Mouse Events
  • Components, Actions, Layouts
In This Part of the Java Tutorial We Cover:
Threads in Detail
Useful Java Classes
  • Object Math Date String Vector Hashtable
Networking and I/O
Futures and HPCC Implications

Table of Contents for full HTML of Java Tutorial - Fall 1997 Part 4: Multithreading, useful Java classes, I/O, Networking, and the future

Denote Foils where Image Critical
Denote Foils where HTML is sufficient
denotes presence of Additional linked information which is greyed out if missing

1 Java Tutorial - Fall 1997
Part 4: Multithreading, Useful Java Classes, I/O, Networking, and the Future
http://www.npac.syr.edu/projects/tutorials/Java/

2 Threads are part of the Java Language!
(a more serious discussion than in part III of tutorial)

3 Initial Remarks on Threads
4 API to show relationship between Thread class and Runnable interface for Foil 4 How to Use Threads
5 Thread Examples for Foil 5 Subclassing the Thread Class
6 Thread Execution and Concurrency
7 The Life of a Thread
8 Thread Methods for Foil 8 Moving out of a Blocked State
9 Thread Priorities and Groups
10 Synchronization
11 Synchronization is Implemented by Monitors
12 Threads and Synchronization I
13 Threads and Synchronization II
14 Thread Synchronization Examples for Foil 14 Threads and Synchronization - Example
15 Useful Java Classes
16 The Overarching Object Class
17 Determining and Testing Class of Object
18 java.lang.Object Wrappers
19 The java.lang.Math class
20 The Date class
21 The String Class
22 More on Strings and the StringBuffer Class
23 A pizza order example.  The bill display uses stringbuffer to line up and display dollar amounts. ReverseString Class
24 The Vector Class
25 Methods for Vectors
26 The Hashtable class
27 I/O and the powerful Stream Zoo
28 Java I/O stream constructors for Foil 28 I/O Streams
29 Standard Input/Output for Foil 29 Standard Input/Output
30 OutputStream classes for Foil 30 The Output Stream Zoo
31 FilterOutputStream classes for Foil 31 FilterOutputStreams
32 InputStream classes for Foil 32 The Input Stream Zoo
33 FilterInputStream subclasses for Foil 33 FilterInputStreams
34 SequenceInputStream class for Foil 34 SequenceInputStream
35 Random Access Files for Foil 35 Random Access
36 Reader/Writer classes for Foil 36 Character Streams
37 BufferedReader class for Foil 37 Buffered Text I/O
38 Buffered Reader/Writer classes for Foil 38 A Monster Chain
39 File class for Foil 39 The File Class
40 Object Serialization
41 Networking and Web Access
42 Networking and Web Access in Java
43 Security Concerns for Applets (Untrusted Code)
44 Table for Java file and network access
45 URL objects in Java
46 Reading a file by URL for Foil 46 Read a File on the Server I
47 ReadConnection class for Foil 47 Read a File on the Server II
48 Socket examples for Foil 48 Socket from the Client Side
49 Socket Server examples for Foil 49 Sockets from the Server Side
50 Additional network examples for Foil 50 Connecting to a CGI Script
51 Performance
and dreaming about the Future

52 Use of Native Classes to Speed Up Execution
53 Comments on Native C Methods
54 HPCC and Java -- High Performance HPjava -- I
55 HPCC and Java -- HPjava -- II

Outside Index Summary of Material



HTML version of Basic Foils prepared 17 Nov 97

Foil 1 Java Tutorial - Fall 1997
Part 4: Multithreading, Useful Java Classes, I/O, Networking, and the Future
http://www.npac.syr.edu/projects/tutorials/Java/

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Instructors: Geoffrey Fox,
Nancy McCracken,
Tom Scavo
Syracuse University
111 College Place
Syracuse
New York 13244-4100

HTML version of Basic Foils prepared 17 Nov 97

Foil 2 Threads are part of the Java Language!
(a more serious discussion than in part III of tutorial)

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index

HTML version of Basic Foils prepared 17 Nov 97

Foil 3 Initial Remarks on Threads

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Java is remarkable for threads being built into the language
Threads are "light-weight" processes (unlike UNIX processes), which communicate by a combination of shared memory and message passing
  • This communication mechanism is employed naturally by Java
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 (see work of Chandy at Caltech) 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

HTML version of Basic Foils prepared 17 Nov 97

Foil 4 How to Use Threads

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index API to show relationship between Thread class and Runnable interface for Foil 4
One can implement threads in two ways:
  • First, by subclassing the Thread class
  • Second, by implementing the Runnable interface
A class that implements the Runnable interface (including the Thread class itself) must implement the run() method containing the "body" of the thread.
The Runnable interface makes it possible for an applet to utilize threads. (Remember, an applet extends the Applet class and so cannot multiply inherit from the Thread class.)

HTML version of Basic Foils prepared 17 Nov 97

Foil 5 Subclassing the Thread Class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Thread Examples for Foil 5
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 instantiated like this:
MyThread mt = new MyThread(...);
Thread control:
  • When the thread is created, it does not automatically start running. The class that creates it must call the Thread method start().
  • Other methods may be called: Thread.sleep( long ), Thread.yield(), suspend(), resume(), stop(), and join(). (Note that sleep( long ) and yield() are static methods.)

HTML version of Basic Foils prepared 17 Nov 97

Foil 6 Thread Execution and Concurrency

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Threads are implemented by a scheduler in Java, which asks the local operating system to run threads in the "runnable" state.
Typically, the OS runs each thread in turn for a "time slice". However, some operating systems (early versions of Solaris, e.g.) run a thread to completion unless another thread of higher priority preempts the running thread.
Example of two threads running: Each thread gives up execution voluntarily (by executing yield(), suspend(), etc.) or because its time slice has ended:

HTML version of Basic Foils prepared 17 Nov 97

Foil 7 The Life of a Thread

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
A thread is always in one of the five states shown in this diagram, which includes the most common methods for changing state:

HTML version of Basic Foils prepared 17 Nov 97

Foil 8 Moving out of a Blocked State

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Thread Methods for Foil 8
A thread must move out of a blocked state into the runnable state using the opposite of whatever put it into the blocked state:
  • If a thread has been put to sleep(), the specified timeout period must expire.
  • If a thread has been suspended, someone must call its resume() method.
  • If a thread called wait(), then someone else using the resource for which it is waiting must call notify() or notifyAll().
  • If a thread is waiting for the completion of an input or output operation, then the operation must finish.

HTML version of Basic Foils prepared 17 Nov 97

Foil 9 Thread Priorities and Groups

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Every thread has a priority, which can be set by the user with setPriority( int ) using constants MIN_PRIORITY (1), MAX_PRIORITY(10), or NORM_PRIORITY.
Whenever the thread scheduler picks a thread to run, it picks the highest priority thread that is currently runnable. (If there is more than one thread with the same priority, each thread gets a turn in some order.)
The user can also create a ThreadGroup to organize a large number of threads by functionality. The methods stop(), suspend(), and resume() can be used on a ThreadGroup.

HTML version of Basic Foils prepared 17 Nov 97

Foil 10 Synchronization

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
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.
Suppose more than one thread can access an account:
public class Account
{ int bankBalance; ...
  • public synchronized void CreditAcct(int amt)
  • { ... bankBalance += amt; ... }}

HTML version of Basic Foils prepared 17 Nov 97

Foil 11 Synchronization is Implemented by Monitors

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
An object that can block threads and notify them when it is available is called a monitor. A monitor is associated with an instance of the class; it has a lock and a queue.
If a class has one or more synchronized methods, each object (instance) of the class has a monitor. The queue holds all threads waiting to execute a synchronized method.
  • A thread enters the queue by calling wait() inside the method or when another thread is already executing the method.
  • When a synchronized method returns, or when a method calls wait(), another thread may access the object.
  • As always, the scheduler chooses the highest-priority thread among those in the queue.
  • If a thread is put into the queue by calling wait(), it can't be scheduled for execution until some other thread calls notify().

HTML version of Basic Foils prepared 17 Nov 97

Foil 12 Threads and Synchronization I

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
If a thread must wait for the state of an object to change, it should call wait() inside a synchronized method.
void wait()
void wait( int timeout )
  • These methods cause the thread to wait until notified or until the timeout period expires, respectively.
  • The timeout argument is optional. If missing or zero, the thread waits until either notify() or notifyAll() is called. (See next foil.)
  • wait() is called by the thread owning the lock associated with a particular object; wait() releases this lock (atomically, i.e., safely)

HTML version of Basic Foils prepared 17 Nov 97

Foil 13 Threads and Synchronization II

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
void notify()
void notifyAll()
  • These methods must be called from a synchronized method.
  • These methods notify a waiting thread or threads.
notify() notifies the thread associated with the given synchronization object that has been waiting the longest time
notifyAll() notifies all threads associated with the given object and is therefore safer than notify()
One can mark a variable as "threadsafe" to inform the compiler that only one thread will be modifying this variable.

HTML version of Basic Foils prepared 17 Nov 97

Foil 14 Threads and Synchronization - Example

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Thread Synchronization Examples for Foil 14
Suppose that several threads are updating a bank balance (i.e., several threads can access one instance of class Account below). Then a thread that finds insufficient funds to debit an account can wait until another thread adds to the account:
public class Account
{ int bankBalance; ...
  • public synchronized void DebitAcct (int amt)
  • { while ((bankBalance - amt) < 0) wait();
  • bankBalance -= amt; ... }
  • public synchronized void CreditAcct (int amt)
  • { bankBalance += amt;
  • notify(); ... } }

HTML version of Basic Foils prepared 17 Nov 97

Foil 15 Useful Java Classes

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index

HTML version of Basic Foils prepared 17 Nov 97

Foil 16 The Overarching Object Class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
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 a class) can use methods of Object.
Methods of Object include:
  • clone() creates a clone of the object
  • equals( Object ) compares two objects, returning a boolean result
  • getClass() returns a descriptor of type Class (a child of Object) defining the class of the object
  • toString() returns a String representation of the object. It is expected that each subclass will override this method
  • wait(...) in various forms causes threads to wait
  • finalize() executed when the object is deleted by system (i.e., garbage collected)

HTML version of Basic Foils prepared 17 Nov 97

Foil 17 Determining and Testing Class of Object

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Suppose we have an object called obj. We get the class of obj by:
Class class = obj.getClass();
and its name by:
String name = class.getName();
One can also use instanceof in following fashion:
"foo" instanceof String
evaluates to true, but
( new mPoint(x,y) ) instanceof String
evaluates to false.

HTML version of Basic Foils prepared 17 Nov 97

Foil 18 java.lang.Object Wrappers

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Primitive types such as int, char, float, etc. are NOT classes. Thus one cannot use methods such as
int var;
var.toString();
ALL primitive types have associated wrappers:
Character myChar = new Character( 'A' );
The Character class has methods such as:
if ( myChar.equals( ch ) ) ...
System.out.print( myChar.toString() );
There are also many static (class) methods:
ch = Character.toLowerCase( myChar );
if ( Character.isUpperCase( myChar ) ) ...
The methods in a wrapper class are also useful to convert types, such as a String to a Double.

HTML version of Basic Foils prepared 17 Nov 97

Foil 19 The java.lang.Math class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
This class provides standard mathematical functions, using types int, long, float and double.
It is a static class, meaning that you only use the methods and never create "Math objects".
The methods include
  • IEEEremainder, abs, ceil, cos, exp, floor, log, max, min, pow, random, sin, sqrt, and other trig functions.
  • The random number generator is a linear congruential generator, which is fast but not random enough for many scientific applications.

HTML version of Basic Foils prepared 17 Nov 97

Foil 20 The Date class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
This class provides an implementation of "date" structures. Date has methods to create and compare dates, obtain and set the time, and convert dates to strings.
The Date constructor creates today's date:
Date today = new Date();
In Java 1.1, most Date methods have been deprecated in favor of the Calendar class:
Calendar date1 = Calendar.getInstance();
date1.set( 999, 12, 31 ); /* Dec. 31, 999 */
Calendar date2 = Calendar.getInstance();
date2.set( 1996, 12, 31, 23, 59, 59 )
    • /* Dec.31,1996 at 23:59:59 */

HTML version of Basic Foils prepared 17 Nov 97

Foil 21 The String Class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Strings are fixed-length collections of Unicode characters.
Usually a string is created from a string literal or by using the constructor on an array of characters:
String greeting = "Hello";
or
char[] bunch = {'H', 'e', 'l', 'l', 'o'};
String greeting = new String( bunch );
Once created, individual characters of a string cannot be changed in place. The following example uses String methods to create a new string:
String test = "Chicken soup with rice";
int n = test.indexOf( 'w' );
String newtest = test.substring(1,n-1) +
    • "is n" + test.substring(n+5);
  • /* giving "Chicken soup is nice" */

HTML version of Basic Foils prepared 17 Nov 97

Foil 22 More on Strings and the StringBuffer Class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
String comparison is done with the methods equals() and equalsIgnoreCase(). Note that == tests if two strings are the same string instance, while equals() tests if two distinct strings have the same characters.
Other methods include length(), charAt( int ) and toLowerCase().
The StringBuffer class has mutable strings, but with a fixed maximum size. Methods such as append(...) automatically extend the length of the string.

HTML version of Basic Foils prepared 17 Nov 97

Foil 23 ReverseString Class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index A pizza order example.  The bill display uses stringbuffer to line up and display dollar amounts.
This class returns an object of class String that reverses order of characters in its argument:
class ReverseString {
  • public static String reverse( String s ) {
  • int i, len = s.length();
  • StringBuffer dest = new StringBuffer(len);
  • for( i = (len-1); i >= 0 ; i-- ) {
  • dest.append( s.charAt(i) );
  • }
  • return dest.toString();
  • }
}
Or more simply:
StringBuffer sb = new StringBuffer( s );
return sb.reverse().toString();

HTML version of Basic Foils prepared 17 Nov 97

Foil 24 The Vector Class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
In Java, while you can give the size of an array at run time, you cannot dynamically change the size of an array during the computation. The vector class provides a data structure with just this property, but the restriction is that all of the elements must be of type Object.
  • Usually, we insert an element of any type and Java will convert it to an Object, but when you extract an element, you must explicitly cast it to convert it back to the type you want.
A vector is created with an "initial capacity" and a "capacity increment". (The default is an initial capacity of 10 and an increment that doubles each time.) As you add elements, if the initial capacity is exceeded, then more memory is automatically allocated in the size of the capacity increment.
Vector shoes = new Vector();
Vector orders = new Vector(100, 10);

HTML version of Basic Foils prepared 17 Nov 97

Foil 25 Methods for Vectors

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Elements are created with the addElement( ... ) method:
Order missouri = new Order();
orders.addElement( missouri );
The object missouri of type Order is automatically converted to an Object and added to Vector instance orders defined on the previous foil.
There are methods for indexing vectors. Like arrays, the indexing is zero-based.
x = (Typeofx) v.elementAt(i);
v.setElementAt( x, i );
The length of the Vector may also be obtained:
int size = v.size;

HTML version of Basic Foils prepared 17 Nov 97

Foil 26 The Hashtable class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
This class is similar to a Perl associative array (or hash). It can store a set of key-value pairs, neither of which can be null.
Hashtable staff = new Hashtable();
Employee harry = new Employee("Harry Hacker");
staff.put( "987-98-9996", harry );
Values are retrieved by indexing with a key. Like Vectors, Hashtables only store objects of type Object, so you must cast the result:
steve = (Employee) staff.get("149-26-7355");
If there is no entry, a null value is returned.
Performance of the Hashtable can be affected by giving an initialCapacity and a loadFactor for reallocation.

HTML version of Basic Foils prepared 17 Nov 97

Foil 27 I/O and the powerful Stream Zoo

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index

HTML version of Basic Foils prepared 17 Nov 97

Foil 28 I/O Streams

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Java I/O stream constructors for Foil 28
A stream is a sequence of bytes or characters.
Stream sources and sinks include:
  • files
  • network connections
  • blocks of memory
  • threads
That is, all types of streams are treated similarly.
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:
  • int read();
  • void write( int );
  • skip( long ); available(); flush(); close();
All of the above methods throw a possible IOException.
The read() and write( int ) methods "block" during transfer.

HTML version of Basic Foils prepared 17 Nov 97

Foil 29 Standard Input/Output

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Standard Input/Output for Foil 29
The System class in java.lang provides the "standard" IO streams System.in, System.out, and System.err.
System.in is an instance of InputStream.
System.out and System.err are instances of PrintStream.
PrintStream is a subclass of FilterOutputStream, which itself is a subclass of OutputStream. (See next foil.) PrintStream objects should not be instantiated; use other subclasses of FilterOutputStream for byte streams or PrintWriter objects for character streams.
PrintStream and PrintWriter define methods print(...) and println(...), which output any primitive type:
System.out.println( "Enter character: " );
int ch = System.in.read();
System.out.println( (char) ch );

HTML version of Basic Foils prepared 17 Nov 97

Foil 30 The Output Stream Zoo

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index OutputStream classes for Foil 30
The subclasses of OutputStream offer additional methods that write a byte stream in a more structured way or provide other functionality.
For example, to open a byte stream to an output file, use:
FileOutputStream s = new FileOutputStream("/usr/gcf/file");

HTML version of Basic Foils prepared 17 Nov 97

Foil 31 FilterOutputStreams

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index FilterOutputStream classes for Foil 31
DataOutputStream and BufferedOutputStream are two important FilterOutputStreams.
To open a data stream to an output file, use:
DataOutputStream out =
  • new DataOutputStream (
  • new FileOutputStream( filename ) );
where filename is a filename string.
Note that DataOutputStream has methods to write any primitive type.
To open a buffered output stream, use:
BufferedOutputStream out =
  • new BufferedOutputStream (
  • new FileOutputStream( filename ) );
Only bytes may be written to a BufferedOutputStream.

HTML version of Basic Foils prepared 17 Nov 97

Foil 32 The Input Stream Zoo

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index InputStream classes for Foil 32
The subclasses of InputStream are analogous to those of OutputStream.
For example, to open a byte stream to an input file, use:
FileInputStream s = new FileInputStream("/usr/gcf/file");

HTML version of Basic Foils prepared 17 Nov 97

Foil 33 FilterInputStreams

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index FilterInputStream subclasses for Foil 33
Subclasses of FilterInputStream are used to add value to a raw InputStream. You can define your own filters but useful ones are already provided in java.io:
  • BufferedInputStream -- establishes an intermediate buffer to service the stream
  • DataInputStream -- has methods to input other data types besides bytes (char, double, boolean, etc.)
  • PushbackInputStream -- allows one to "unread" a byte and put it back in the input stream
These streams may be "chained" for added functionality:
DataInputStream in =
  • new DataInputStream (new FileInputStream(file));
or
BufferedInputStream in =
  • new BufferedInputStream (new FileInputStream(file));
where file is a filename string.

HTML version of Basic Foils prepared 17 Nov 97

Foil 34 SequenceInputStream

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index SequenceInputStream class for Foil 34
The constructor of SequenceInputStream takes a pair of InputStreams and concatenates them together:
SequenceInputStream in =
  • new SequenceInputStream (
  • new FileInputStream( file1 ),
  • new FileInputStream( file2 ) );
Alternatively, SequenceInputStream takes a Java Enumeration type:
SequenceInputStream in =
  • new SequenceInputStream (
  • new FileListEnumerator( args ) );
where args is an array of command-line arguments and FileListEnumerator is a class that implements the Enumeration interface.

HTML version of Basic Foils prepared 17 Nov 97

Foil 35 Random Access

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Random Access Files for Foil 35
The RandomAccessFile class offers all the functionality of DataInputStream and DataOutputStream combined, plus additional capabilities.
To open a random access file for reading, use:
RandomAccessFile in =
  • new RandomAccessFile( filename, "r" );
Such a file may be accessed sequentially with
in.readLine();
or randomly by repositioning the file pointer:
in.seek( offset );
where offset is a byte offset into the random file. (Use "rw" for read/write access.)
Random access files have no inherent structure; the structure must be imposed by the programmer.

HTML version of Basic Foils prepared 17 Nov 97

Foil 36 Character Streams

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Reader/Writer classes for Foil 36
Java 1.1 introduced Reader and Writer classes for character streams, which are used to read/write text files.
To construct a character output stream, for example:
PrintWriter out =
  • new PrintWriter(
  • new OutputStreamWriter(
  • new FileOutputStream( filename ) ) );
The OutputStreamWriter constructor takes a byte stream and converts it to a character stream. As a shortcut, use
PrintWriter out =
  • new PrintWriter(
  • new FileWriter( filename ) );
where FileWriter is a subclass of OutputStreamWriter.

HTML version of Basic Foils prepared 17 Nov 97

Foil 37 Buffered Text I/O

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index BufferedReader class for Foil 37
For buffered text output, use the character stream:
BufferedWriter out =
  • new BufferedWriter(
  • new OutputStreamWriter(
  • new FileOutputStream( filename ) ) );
Similarly, for buffered text input, use:
BufferedReader in =
  • new BufferedReader(
  • new InputStreamReader(
  • new FileInputStream( filename ) ) );
Optionally use the subclasses FileWriter and FileReader for brevity (as in the previous foil).
Note that the BufferedReader class has a handy readLine() method for sequential text input.

HTML version of Basic Foils prepared 17 Nov 97

Foil 38 A Monster Chain

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Buffered Reader/Writer classes for Foil 38
The buffered output construct in the previous foil is of limited use since BufferedWriter has so few output methods. Instead, use the "monster" chain:
PrintWriter out =
  • new PrintWriter(
  • new BufferedWriter(
  • new OutputStreamWriter(
  • new FileOutputStream( filename ) ) ) );
which can be shortened somewhat by using FileWriter as shown earlier.
The PrintWriter class defines print(...) and println(...) methods for all primitive types, which unlike other Reader/Writer classes never throw exceptions.

HTML version of Basic Foils prepared 17 Nov 97

Foil 39 The File Class

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index File class for Foil 39
The File class defines methods and variables that provide access to the underlying file system in a machine-independent way.
For example, there are methods getParent() and getPath(), as well as boolean methods isDirectory() and isFile(), plus many more.
A very handy method is the list() method, which returns a string array of directory contents:
File dir = new File( "/tmp" );
if ( dir.exists() && dir.isDirectory() )
  • String directory[] = dir.list();
Instances of class File may be used in lieu of filename strings in InputStream constructors.

HTML version of Basic Foils prepared 17 Nov 97

Foil 40 Object Serialization

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Classes ObjectOutputStream and ObjectInputStream in package java.io implement object serialization.
Java objects are serialized with writeObject() and deserialized with readObject(). For example:
Vector lines = new Vector( 256 ); ...
try {
  • new ObjectOutputStream(
  • new GZIPOutputStream(
  • new FileOutputStream( filename ) ) );
  • out.writeObject( lines );
  • out.close();
} catch ( IOException e ) { }
Only objects of classes that implement Serializable (or Externalizable) can be serialized. (The Serializable interface defines no methods.)
Object variables not to be serialized are called transient.

HTML version of Basic Foils prepared 17 Nov 97

Foil 41 Networking and Web Access

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index

HTML version of Basic Foils prepared 17 Nov 97

Foil 42 Networking and Web Access in Java

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
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

HTML version of Basic Foils prepared 17 Nov 97

Foil 43 Security Concerns for Applets (Untrusted Code)

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
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:
  • they can never run a local executable program;
  • they cannot communicate with any host other than the server from which they were downloaded (the originating host);
  • they cannot read or write to the local computer's file system, except through the browser mechanism;
  • they cannot find out information about the local computer (see table on next slide for details).
As of summer 1997 no known applets have seriously broken security to steal client information or trash the local disk. Exceptions:
  • applets have been written to use up arbitrary amounts of client cpu.
  • applets with native code can trash the local disk. So far, native code is disallowed on publicly released browsers.

HTML version of Basic Foils prepared 17 Nov 97

Foil 44 Table for Java file and network access

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
This table shows what Java programs can do in the following four cases:
  • NL - Netscape loading a URL for applet
  • NF - Netscape loading a local file for applet
  • AV - Applet viewer
JA - Java application (not an applet)
    • NL NF AV JA
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

HTML version of Basic Foils prepared 17 Nov 97

Foil 45 URL objects in Java

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
The class java.net.URL has methods to create and manipulate URL objects:
String urlStr = "http://www.npac.syr.edu/";
try {
  • URL url = new URL( urlStr );
} catch ( MalformedURLException e ) {
  • System.err.println( "Bad URL: " + urlStr );
}
The document at this URL may be displayed in the current browser window with:
getAppletContext().showDocument( url );
Another version of showDocument(...) permits the document to be loaded into an arbitrary HTML frame.

HTML version of Basic Foils prepared 17 Nov 97

Foil 46 Read a File on the Server I

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Reading a file by URL for Foil 46
To read a file on the server, first instantiate a URL object:
try {
  • URL url = new URL( getCodeBase(), filename );
} catch ( MalformedURLException e ) {
  • System.err.println( "Bad URL:" + url.toString() );
}
where getCodeBase() returns the applet path. (Another method getDocumentBase() returns the path of the corresponding HTML document.)
Next, open a stream to this URL:
BufferedReader in =
  • new BufferedReader(
  • new InputStreamReader( url.openStream() ) );
The resulting character stream is treated like any other.

HTML version of Basic Foils prepared 17 Nov 97

Foil 47 Read a File on the Server II

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index ReadConnection class for Foil 47
A class called java.net.URLConnection provides another approach to URLs.
  • URLConnection provides the most general type of HTTP connectivity and indeed has some advantages over sockets (see following foils) as these are subject to special security restrictions in some browsers.
A method URL.openConnection() returns an instance of class URLConnection:
URLConnection conn = url.openConnection();
conn.connect(); // open a connection
Now use this URLConnection object to open a stream:
BufferedReader in =
  • new BufferedReader(
  • new InputStreamReader( conn.getInputStream() ) );
Note that one can connect not just to HTML files but also to CGI scripts and other web documents.

HTML version of Basic Foils prepared 17 Nov 97

Foil 48 Socket from the Client Side

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Socket examples for Foil 48
A Java applet or application can open a socket to a Java server application through the Socket class.
  • Socket t = new Socket("internet host name", port)
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.

HTML version of Basic Foils prepared 17 Nov 97

Foil 49 Sockets from the Server Side

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Socket Server examples for Foil 49
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:
  • ServerSocket s = new ServerSocket(port);
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:
  • Socket client = s.accept();
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.

HTML version of Basic Foils prepared 17 Nov 97

Foil 50 Connecting to a CGI Script

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index Additional network examples for Foil 50
Although an applet can read files from a web server machine, as in, for example, establishing a URL connection and doing getInputStream(). Applets are not allowed to directly write to files on the web server machine by doing getOutputStream(). (Java applications can do this!)
The applet can establish a socket the URL of the web server. Then it uses an OutputStream on the socket to send a message formatted in MIME, just as if it were from the browser. The header of this message requests the web server to run a CGI script. In addition, the applet can send data in the body of the message for the CGI script to read. And the CGI script can send back a MIME message to the applet.

HTML version of Basic Foils prepared 17 Nov 97

Foil 51 Performance
and dreaming about the Future

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index

HTML version of Basic Foils prepared 17 Nov 97

Foil 52 Use of Native Classes to Speed Up Execution

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
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

HTML version of Basic Foils prepared 17 Nov 97

Foil 53 Comments on Native C Methods

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
Advantages
  • May call resources available from C
    • Window/Graphic Systems
    • Database
    • Networking and Other Third Party Libraries
    • Higher performance as compiled (always) and as C (advantage with todays compilers)
Disadvantages
  • Classes with native methods, or library linking calls, may not be downloaded across the network.
  • Libraries may not be downloaded across the network.
  • Programmer must write a native library for every platform used.
So usually user defined native method can not be used remotely in Applet.
  • Can pre-download as a plugin

HTML version of Basic Foils prepared 17 Nov 97

Foil 54 HPCC and Java -- High Performance HPjava -- I

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
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
  • It essentially has task parallelism built in with Applet mechanism
  • As there are no pointers, it is easier to define data and other implicit parallelism so it can be efficiently implemented
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
  • This is an alternative to wrapper technology as in native classes

HTML version of Basic Foils prepared 17 Nov 97

Foil 55 HPCC and Java -- HPjava -- II

From Java Tutorial, July 1, 1996 CEWES Tutorial, CPS606, JSU Class CSC499 -- July 22-25 1997, Fall 97. *
Full HTML Index
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
  • Here one has a HPJava translator that produces java "plus message passing" code
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

© Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu

If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.

Page produced by wwwfoil on Wed Apr 1 1998