69
Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : [email protected], http: www.cs.nott.ac.uk/~azt Threads

Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : [email protected], http: azt Threads

Embed Size (px)

Citation preview

Page 1: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Intermediate Level day 3 Part A

Athanasios Tsintsifas, LTR, University of Nottingham,

email : [email protected], http: www.cs.nott.ac.uk/~azt

Threads

Page 2: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Aims

To be able to create, execute, and terminate Threads.

To learn how Threads inter-communicate. To understand their States and their

Priorities. To use synchronized methods and blocks

in order to obtain locks on critical objects or sections of code.

Page 3: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Threads

An integral part of Java - From day one . Enable concurrent execution. A thread is a 'lightweight process' ;

– The VM is the process. One run-time stack per thread. One program counter per thread. A process has usually several threads

running.

Page 4: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Threads

Shared address space and memory. Inter-thread communication. Cheap creation and switching. All standard libraries are 'Thread Safe’. Cannot enter unknown states. Protected from multiple simultaneous access.

Page 5: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Creating a Thread

Two ways to create a Thread:

– 1. Implement Runnable, • Implement the run() method.

– 2. Extend Thread, • Override the run() method.

This is due to single inheritance in Java. Extending Thread means you cannot extend another class. The first alternative is more used.

Page 6: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Runnable

Runnable is a very simple interface, it has just one method.

The Thread’s start() method calls the Runnable’s run() method.

public interface Runnable {

public abstract void run();

}

Page 7: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Thread constructors and names There are four basic constructors; their arguments can be:

– A name (String) for the Thread (default null).• Should be unique, used for debugging etc.

– An object (Runnable) to call a run() method in. • Default is this object

class ThreadExample implements Runnable { public ThreadExample { Thread t1 = new Thread(); Thread t2 = new Thread("sun"); Thread t3 = new Thread(this); Thread t4 = new Thread(this, "t4"); String n2 = getName(); t3.setName("t3"); } public void run() { }}

Page 8: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Executing Threads run()

– Run it! (Runnable) start()

– Activates the thread and calls run().

stop() – Forces the thread to stop.

suspend() – Temporarily halt the thread.

resume()– Resume a halted thread.

destroy()

- equivalent to UNIX’s “kill -9”

isAlive()– Is it running?

yield() – Let another thread run.

join() – Wait for the death of a

thread. sleep(long)

– Sleep for a number of milliseconds.

interrupt() – Interrupt sleep,wake up!

Page 9: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

InterThread Communication Inter-thread communication methods are declared in

java.lang.Object. Each object could be associated with a monitor (a sort of

thread lock).

wait() – Suspend the thread.– Wait can also be time limited.

notify() – Unlock the first monitored thread.– (The first that called wait() within the monitor.)

notifyAll() – Unlocks all monitored threads. – Highest prioritised first!

Page 10: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Thread states

Page 11: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Implementing Runnableclass MyThread implements Runnable {

MyThread() {

}

public void run() {

// Loop forever...?

}

public static void main(String[] args) {

Thread mythread = new Thread(new MyThread());

mythread.start();

mythread.stop();

}

}

Page 12: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Extending Threadclass MyThread extends Thread {

MyThread() {

}

public void run() {

// Loop forever...

}

public static void main(String args[]) {

MyThread myThread = new MyThread();

myThread.start();

myThread.stop();

}

}

Page 13: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Priorities Priority per thread :

– No real-time priorities, – Initiated to the creator’s priority.

public class Thread implements Runnable {

...

public final static int MIN_PRIORITY; // 1

public final static int NORM_PRIORITY; // 5

public final static int MAX_PRIORITY; // 10

public final int getPriority();

public final void setPriority(int);

...

}

Page 14: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Other Thread methods

currentThread()– Returns the currently executing thread (static).

setDaemon(boolean)– Sets a thread as daemon; the VM exits when all threads are

daemons.

isDaemon() – Returns true if the thread is a daemon.

Page 15: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Synchronizing, locks and monitors All objects may be associated with a monitor. Monitors aggregate mutually exclusive locks :

– Synchronized methods, – Synchronized statements.

Page 16: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Synchronized methods A synchronized method -> mutual exclusion (lock)

per object. A synchronized static method -> mutual exclusion

(lock) per class.

synchronized void myObjectMethod() {

}

synchronized static void myClassMethod() {

}

Page 17: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Account Example This is an example of synchronized methods : public class Account {

private double balance;

public Acount(double initialDeposit) {

balance = initialDeposit;

}

public synchronized double getBalance() {

return balance;

}

public synchronized void deposit(double amount) {

balance += amount;

}

}

Page 18: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Synchronized statements

The synchronized statement: – mutual exclusion (lock) of data access instead of a

synchronized method. – very lightweight.

Syntax:

synchronized(Object) {

}

Page 19: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Synchronized statements

Example (mutual exclusive lock on the variable values) :

public static void abs(int[] values) { synchronized(values) {

for (int i=0; i < values.length; i++) {

if (values[i] < 0)

values[i] = -values[i];

}

}

}

Page 20: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Thread groups

A thread group represents a set of threads. In addition, a thread group can also include other thread groups. A thread may only access information about its own thread

group.

public Thread(ThreadGroup, Runnable);

public Thread(ThreadGroup, Runnable, String);

public Thread(ThreadGroup, String);

The VM is one ThreadGroup while the application is another one.

Page 21: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Summary Creation of threads. Thread constructors and names. Execution of threads. Inter-thread communication. Thread states & priorities. Synchronization issues & synchronize keyword. Thread groups.

Page 22: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Quiz Imagine that one thread, T1, needs to access two

objects (one file for writing banking data, and a String that contains the balance). These two objects are declared Synchronized, so that no other thread can access these objects at the same time. A second thread, T2, runs in parallel

with T1 and needs to access the same objects too. While T1 locks the file (but not the String), T2

manages to lock the String, but not the file. What happens next?

Page 23: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Exercises 1 Create a console application and create and use two

threads that are printing an increasing counter. Change the threads priorities and notice the effect on the

counters. Use the Thread’s sleep method if you need to slow down the printing.

Create a simple animation on a Container which holds a Pause and a Play button. To do so you will need to control a thread that loops and calls Panel’s repaint method.

Create a Frame and put three of the above containers. Append a list for the user to select from a range of thread priorities. Can you see any difference on your animation?

Page 24: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Exercises 2 Create an application that displays the number

of threads and ThreadGroups which are running in the Java Virtual Machine (activeCount(), activeGroupCount() ).

Modify the previous example in order to also display the names (getName()) and priorities (getPriority() / getMaxPriority()), of the threads and their respective ThreadGroups. For the threads, also indicate whether they are daemon threads (isDaemon()) and if they are alive (isAlive()). Use the thread methods currentThread() and getThreadGroup() to move through the system’s threads in order to find the “root” ThreadGroup (getParent() returns null) and from there start listing the various threads/groups recursively. Finally, display your results in a TextArea.

Page 25: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Intermediate Level day 3 Part B

Athanasios Tsintsifas, LTR, University of Nottingham,

email : [email protected], http: www.cs.nott.ac.uk/~azt

Networking with Java

Page 26: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Aims

Understand Java’s networking. Use InetAddress. Create, query and get data from a URL. Use Sockets (for clients and for servers)

and know their exceptions. Get introduced to Remote Method Invocation.

Page 27: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Networking with Java

• Java is the first programming language designed with networking in mind. It is therefore uniquely suited for building network applications.

• Using the java.net package makes network programming easy. Much easier than in any other languages.

• The java.net package contains : IP, Sockets, DNS handling, URL

Page 28: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

InetAddress

Creating new InetAddress objects :

1) public static InetAddress getByName(String host)InetAddress iaddr = InetAddress.getByName(”www.acm.org");

2) public static InetAddress[] getAllByName(String host)

InetAddress iaddr[] = InetAddress.getAllByName(”x.xx.x");

3) public static InetAddress getLocalHost()

InetAddress iaddr = InetAddress.getLocalHost();

If a host is not found a UnknownHostException is thrown.

Page 29: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

URL basics Uniform Resource Locator - URL defined in RFC1738. An URL is the standard way of addressing resources on

the Internet today. An URL consists of 4 main parts :

- protocol, host, port, file.

URL Usage : protocol://host:port/file

e.g. : http://www.cs.nott.ac.uk:80/~azt/index.html

Supported standard protocols in 1.1 are: http, ftp, news,

mailto, gopher and file.

Page 30: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Creating new URLs

1) public URL(String spec) : – URL u1 = new URL("http://www.cs.nott.ac.uk/~azt/");

2) public URL(String protocol, String host, String file) :– URL u2 = new URL("http", "www.cs.nott.ac.uk/~azt/", "/java/");

3) public URL(String protocol, String host, int port, String file) :– URL u3 = new URL("http"," www.cs.nott.ac.uk/~azt ", 80, "/java/");

4) public URL(URL context, String spec) :– URL u4 = new URL(u, "/java/");

If an invalid URL is specified a MalformedURLException is thrown.

Page 31: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Querying URLsThe URL class contains a number of methods for

splitting URLs into different parts :

public String getProtocol() public String getHost() public int getPort() public String getFile()

Page 32: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Getting data from a URLThere are three methods in the URL class for retrieving

data from a URL : public final InputStream openStream()

– returns a stream to the data. public URLConnection openConnection()

– is used to communicate directly with the server. It gives access to the raw data.

public final Object getContent()– tries to parse the data into an Object representing the data

based on the returned MIME-type. A content-handler for each type must exists but in JDK only a few are available: text/plain, text/generic, image/gif and image/jpeg.

Page 33: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

URL, other methods

public boolean sameFile(URL other)– Compares to URLs to see if they point to the same file.

public boolean equals(Object obj) – Compares to URL objects to see if they are the same.

public String toExternalForm()– Constructs an String representation of the URL.

public String toString() – Constructs a String representation of this URL by calling the

toString() method in the corresponding stream content handler.

Page 34: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Reading from a URLimport java.io.*;import java.net.URL;

public class URLReader { public static void main(String args[]) { URL myURL; InputStreamReader myURLContent; int intValue; try { myURL = new URL("http://thanassis.com"); myURLContent = new InputStreamReader(

myURL.openStream());

Page 35: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Reading from a URL

intValue = myURLContent.read(); while (intValue != -1) { System.out.print((char) intValue); intValue = myURLContent.read(); } myURLContent.close(); } catch (Exception e) { System.out.println("Error while opening URL"); } } // end main } // end class

Page 36: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Sockets for clients Sockets are a way with which applications communicate

with the OS, which in turn communicates with the network.

A socket performs seven basic operations: – 1.Connects to a remote host – 2.Sends data – 3.Receives data – 4.Closes a connection – 5.Binds to a port – 6.Listens for incoming data – 7.Accepts connections from remote machines on the bound port

There are two main types of application level sockets: – TCP - Transmission Control Protocol,

– UDP - User Datagram Protocol.

Page 37: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

The Socket class

public Socket(String host, int port) public Socket(InetAddress address, int port)

Getting information about a socket : public InetAddress getInetAddress()

– Returns the address to which the socket is connected. public int getPort()

– Returns the remote port to which this socket is connected. public int getLocalPort()

– Returns the local port to which this socket is bound.

Page 38: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Using Sockets

Streaming data through a socket :– public InputStream getInputStream()– public OutputStream getOutputStream()

Closing a socket :– public synchronized void close()

• closes the socket and cleans up system resources. This is done automatically when a program exits but it is good practice to do this in every program that no longer needs a connection.

Page 39: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Sockets Exceptions BindException :

– Thrown if the socket tries to use a local port that is busy or if the program has not enough priviligies to use that port.

ConnectException :– No connection to the remote host. No server is running on that

port.

NoRouteToHostException :– There is no path over the network to the remote host.

SocketException :– Something went wrong in the socket which is not covered by the

above exceptions.

Page 40: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Sockets for ServersThe difference between client sockets and server sockets

is that the server sockets wait for an incoming connection.

The basic life cycle of a server is: – 1. A new ServerSocket is created – 2. The socket listens for incoming connections using the

accept call which blocks. – 3.The server interacts with the client – 4.The client and/or server closes the socket – 5.The server returns to step 2.

Page 41: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Using Server Sockets Creating a server socket :

– public ServerSocket(int port).

Creates a server socket that listens on a local port :– public ServerSocket(int port,int backlog).

Accepting and closing connections :– public Socket accept() -> waits for connection. – public void close() -> closes the socket.

Other methods :– public InetAddress getInetAddress()->Get client address.

– public int getLocalPort() -> Get the client local port.

Page 42: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.rmi

Defines the fundamental classes and interfaces used for Remote Method Invocation.

Most of the classes are exception types. Subpackages of java.rmi provide additional, more

specialised functionality. When objects must be passed as arguments to

remote methods, RMI uses object serialization (java.io).

Page 43: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

RMI’s subpackages java.rmi.dgc : Defines the classes and interfaces required

for distributed garbage collection (DGC).

java.rmi.registry : Defines classes required for :

- a Java client to look up a remote object by name or

- a Java server to advertise the service it provides.

java.rmi.server : The heart of Remote Method Invocation. Defines classes and an interface that allow a Java program to create an object that can be used remotely by other Java programs.

Page 44: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Using RMI in 7 simple steps1. Create a iRemoteInterface that implements

java,rmi.Remote and has as its interface the remote methods.

2. Create the class of the remote object by implementing the iRemoteInterface and extending java.rmi.server. UnicastRemoteObject.

3. Run rmiregistry.

4. Instantiate the remote object and bind it with the registry using java.rmi.Naming.rebind(String, ro).

5. Compile the remote object and use rmic for stubs and skeletons

6. Write the clients using Naming.lookup to get iRemoteInterface reference to the remote object, after installing a RMISecurityManager.

7, Execute both the server and the client.

Page 45: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Summary

Java networking. InetAddresses. URLs: creating, querying, getting data from. Sockets: For clients, for servers, creating & using. Java’s RMI package. Using RMI in seven simple steps.

Page 46: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Quiz Applet security restrictions only allow an applet to

establish network connections to one host: the host from which it was downloaded. Suppose that you have an applet that needs to connect to another server. How do you proceed?

Both Sockets and RMI can be used to connect to remote machines, exchange data and share information. Can you think of any types of programs that are best suited for one of them?

Page 47: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Exercises Write an application that connects to the

specified URL, gets its contents and then checks if the links from that page actually exist. Use a TextField to allow the user to input the URL, a “GO!” button and a TextArea to display the results of your search. To do this, you’ll have to parse the URL content, finding any “<A HREF=“, “<IMG SRC=“ and “<applet code=“. To find out the link status try to open a stream to that connection.

Improve on the previous exercise by providing a way to recursively test links on the specified URL. You may let the user define a maximum depth for your search.

Page 48: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Intermediate Level day 3 Part C

Athanasios Tsintsifas, LTR, University of Nottingham,

email : [email protected], http: www.cs.nott.ac.uk/~azt

JDK 1.1 advanced featuresand Focusing on Java

Page 49: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Aims

Look at some of the jdk 1.1 packages. Learn how to improve your Java skills. Know the ten most common mistakes on java. Learn about the ten most common developing

mistakes. Find out where to look for info, what to use for

development and how to troubleshoot an error.

Page 50: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.applet java.awt java.awt.datatransfer java.awt.event java.awt.image java.awt.peer java.beans java.io java.lang java.lang.reflect java.math

java.net java.rmi java.rmi.dgc java.rmi.registry java.rmi.server java.security java.security.acl java.security.interfaces java.sql java.text java.util java.util.zip

JDK 1.1 packages

Page 51: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.applet Improvements :

- JAR files allow all the grouping of of an applet's files into a single archive.

- Digital signatures allow trusted applets to run with fewer security restrictions.

Page 52: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.awt

Java 1.1 AWT includes support for printing, cut-and-paste, popup menus, menu shortcuts, and focus traversal as well.

It also has improved support for colours, fonts, cursors, layout management, scrolling, image manipulation, and clipping.

Page 53: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.awt.datatransfer The classes and interfaces in this package define a

generic framework for inter-application (and intra-application) data transfer.

Uses a DataFlavor object to represent the type of data to be transferred.

Also includes classes to support a clipboard-based cut-and-paste data transfer model. This works for Java applications running on separate VMs too, or even for other, non-Java applications that run under the OS itself*.

One of the two underlying data transfer mechanisms supported by this package relies on the Object Serialization API of the java.io package.

*Custom types of DataFlavor do not correctly interface with the system clipboard

Page 54: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.math

A package for handling numbers with arbitrary precision.

The BigDecimal class gives its user complete control over rounding behavior, forcing the user to explicitly specify a rounding behavior for operations capable of discarding precision.

Page 55: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.util.zip

A package for handling Zip-files.

To list the files in a Zip-file:

ZipFile zipf = new ZipFile(filename);

for (Enumeration e = zipf.entries() ;

e.hasMoreElements() ;) {

ZipEntry entry = (ZipEntry)e.nextElement();

System.out.println(entry.getName() + ": " +

entry.getSize()/1024 + " KB");

}

Page 56: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.text

A package for handling international and country specific information.

It contains classes with information about : – DecimalFormats, – DateFormats, – MessageFormats, – Locale-specific text splitting.

Page 57: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.sql Java Database Connectivity.

A class for interfacing databases through an SQL interface.

JDK contains a Bridge-interface to Microsofts ODBC.

Database manufacturers must provide their own implementation and must conform to the standard API.

Page 58: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

The JavaSoft JDBC Framework

JDBC Middleware

protocol

JDBC Driver Manager

JDBC - NetDriver

Java Application

JDBC - ODBCBridge Driver

ODBC andDB Drivers

Driver A Driver B

Proprietary database access protocoks

JDBC API

JDBC drivers

Page 59: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

java.security

Cryptography : – public and private keys, certificates, digital

signatures. Has a default implementation relies on the BigInteger class.

Page 60: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Difficulties Learning Java

To master Java you need to know :

How to solve problems algorithmically using Java’s syntax and environment.

The various classes contained in Java’s packages and how to use them.

The OO model and the design behind Java’s classes.

Page 61: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

How to improve Read other people’s code. Experiment with the language itself . Experiment with all the basic classes. Read Java’s source code. Write the same program from scratch each time trying a

different way. Spend time reflecting on a design and try to identify parts

that worked well, felt nice and looked beautiful. When you find yourself spending a significant amount of

time designing over implementing it’s time to start learning OOD methods and Design Patterns.

Page 62: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

The 10 most common Java mistakes Missing ( ) [ ] : Unpredictable error messages. Forgotten Imports : Class not Found. A Class for an Object: Method not found (if not static). Spelling mistake : Various error messages. Wrong Signature : Wrong type of Arguments. Return nothing = void: Invalid method declaration. Wrong equality : Incompatible type for if. Endless loops : Program seems to be hanged. Many public classes : Public class x must be defined in a

file. called ”x.java". Trusting your code without testing!

Page 63: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

The 10 Developing mistakes Blob, The God class : Find related concepts and break it. Lava Flow : Only prevention or else painful cure. Functional Decomposition: similar to the Blob. Poltergeist : Remove and trim often. Golden hammer: Expand your horizons. Spaghetti Code : Refactoring - Clean up. Cut and Paste : Try to reuse at the black box level. Swiss Army Knife : Simplify. Reinvent the wheel : Find the right info. Reach a dead end : Know what you are using.

Page 64: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Where to find infoWeb Links http:// java.sun.com/ www.gamelan.com www.jars.com/ www.javaworld.com/ www.sigs.com www.apl.jhu.edu/~hall/java/

Magazines : Java-Report, Application Developer, Dr. Dobbs Journal, Communications of the ACM.

Page 65: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

What to read:

Java Books :• Thinking in Java, Prentice-Hall 1998, ISBN: 0-13-659723-8• Java in a Nutshell, O’Reilly, 1997, ISBN: 1-56592-262-X• A Little Java, A few patterns, MIT Press 1998, ISBN: 0-262-

56115-8

Design Books :• Design Patterns, Addison Wesley, 1995 ISBN 0-201-63361-2• Patterns Languages of Program Design 1,2,3, Addison Wesley

Page 66: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

How to troubleshoot

Debug either using a debugger or print statements. Try to isolate and identify the error’s source. Sometimes -not very often- it is not your fault and you bumped

into a genuine Java bug. In this case, it is quite likely that other people have already

found a workaround. Search the Usenet and specially :• comp.lang.java.programmer• comp.lang.java.api• comp.lang.java.tech• comp.lang.java.security• comp.lang.java.setup• comp.lang.java.misc

Page 67: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Summary JDK 1.1 special packages :

- java.applet, java.awt, java.awt.datatransfer,

- java.math, java.util.zip, java.text, java.sql,

- jdbc, java.security. Few ways to improve your Java skills. Ten of the most common programming mistakes. Ten of the most common developing mistakes. What to read and what to use. How to troubleshoot hard to find errors.

Page 68: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Exercises Write a small program to compress a file, using java.util.zip. Create

an InputStream to read from the source, and a GZIPOutputStream to write the compressed data to. Then, simply copy the data over the two streams. Don’t forget to close the streams!

Now that you compressed a file, write another program to decompress it. You may integrate these two programs into a single program that gets its arguments from the command line

(use main’s String[] args).

You may add a GUI to the above application: Create a menu with an option which, in case the user does not specify any command-line arguments, raises a FileDialog that lets the user select which file to compress.

Page 69: Intermediate Level day 3 Part A Athanasios Tsintsifas, LTR, University of Nottingham, email : azt@cs.nott.ac.uk, http: azt Threads

Java Intermediate Level day3