440 likes | 597 Vues
Java Advanced Topics CSE 422. Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These materials are excerpted from a course created by Arthur Ryman of IBM Toronto, and used at the University of Toronto. Thanks!. Agenda. Introduction to Java (today)
E N D
Java Advanced TopicsCSE 422 Michigan State Universityprepared by Philip K. McKinleypresented by SeyedMasoud SadjadiThese materials are excerpted from a course created by Arthur Ryman of IBM Toronto, and used at the University of Toronto. Thanks!
Agenda • Introduction to Java (today) • What is Java? • Tools Overview • Language Overview • Advanced Topics (next session) • Error Handling • Multithreading • Networking
Traditional Error Handling • Requires status information to be returned • Caller may ignore error codes or choose to process the information by either: • handling the error directly, or • returning a similar error code to its caller (possibly obscuring the original error code) • This style breaks up the normal control flow if ((errorcode = obj.someMethod (args))!= OK) { //do something about it ... }
Java Exceptions • Java’s Exception model is a clean OO way for handling errors. • When a server (service method) detects an error that it cannot cope with, it “throws” an exception (object) • A caller (direct or indirect) can indicate a willingness to “try” and handle the error (catch the exception) • Exception objects are normal objects • They may encapsulate an arbitrary amount of state (which is transferred from the “throw” point to the “catch” point) • Exceptions are caught by class (the type of exception is matched with the argument type of the available catch clauses)
Catching Exceptions • The system will automatically throw exceptions if it detects an error. You just need to catch the error. try { int count = 0, i; Byte[] b = new byte[100]; FileInputStream f = new FileInputStream("x.lis"); while ((i = f.read(b)) >= 0) { count += i; } } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("IO Exception"); } • The system defines a large hierarchy of potential exceptions.
Java Exception Keywords • An exception is signaled by use of the throw keyword • Each exception handler is a catch block • The handler’s reach is the try block • A method which can possibly throw an exception must declare that fact via a throws clause • A finally block, used for clean-up, can be associated with a try block
Exceptions Syntax public class Aclass { public void f1 () throws AnException // … if (someCheck) throw new AnException(); // … } } /* Some client code snippet */ Aclass myobj = new Aclass (); try { myobj.f1 (); } catch (AnException ev) { System.err.println(ev.toString()); } finally{ //Some stuff }
Exceptions: Flow of Control fee() fie() throws X foe() throws X try{ fie() // more stuff } catch (X e) { … } throw new X () foe() X
Designing Your Own Exceptions • An object that is thrown must be derived from the Throwable class. Exception is a class derived from Throwable. • You can define new exceptions by deriving from Exception or one of its sub classes. class MyProtocolException extends ProtocolException { public MyException() { super(); } }
Exceptions: When to Use Them • Exceptions are superior to error codes when local and encapsulated handling of the errors is not guaranteed • Separatesdetection mechanism from handling policy • Exceptions cannot be ignored • Exceptions can easily pass large amounts of information to the handler point • Better separation of normal vs. error logic • Improved normal path performance -- when there are no exceptions, testing and forwarding are eliminated • Pay overhead when exceptions do occur
class Except1 extends Exception {} class Except2 extends Exception { private String theMessage; public Except2(String aMsg) {theMessage = aMsg;} public String toString () {return "Except type 2" + theMessage;} } public class except_example { public static void main (String args[]) { for (int i=0; i<3; ++i) try { new Worker().f1(i); {System.out.println("no exception, "+i); } } catch (Except1 e) {System.out.println(e.toString()+"i="+i); } catch (Except2 e) {System.out.println(e.toString()+"i="+i); } finally { System.out.println("Finally code");} } } class Worker { public void f1 (int val) throws Except1, Except2 { switch (val) { case 1: throw new Except1 (); case 2: throw new Except2 ("againnn"); }}} Exceptions - Complete Example
Runtime Exceptions • The compiler will enforce the rule that all exceptions must be caught or explicitly passed up the stack (using a throws list on a method). • Exceptions of the RuntimeException class are special - we don’t need to explicitly catch them • Provided to reduce programming overhead for commonly written code (e.g. a[] potentially throws an index out of bounds exception, a/0 throws an arithmetic exception) • Can derive own exceptions from RuntimeException, but not a good idea
Agenda • Introduction to Java (today) • What is Java? • Tools Overview • Language Overview • Advanced Topics (next session) • Error Handling • Multithreading • Networking
Concurrency Issues • Most applications can be decomposed into multiple subsystems or functions • Often, some of these subsystems are fundamentally independent of each other • No intrinsic temporal dependencies between subsystem execution (tasks) • If the resources are available, concurrent tasks could operate parallel to one another
Threads and Runnable Objects • Threads are the basic unit of concurrency in Java • The java.lang.Thread class is the base for all objects that can behave as threads • Most of the time, threads are conceptually just an activity. These activities need a focal point (e.g., what code they are to run) • All Threads need a handle to an object (a Runnable object) whose run() method it will “execute in” • To facilitate this protocol, Java supplies a simple interface java.lang.Runnable Example:public interface Runnable { public abstract void run();}
Two ways to use the Thread class: by implementingRunnable and starting new activities by wrapping them inside Threads created with the Thread(Runnable) constructor by subclassingThread, and overriding the run method In the second case, the Thread itself is the “Runnable” object Runnable vs. Subclassing Thread
class ThreadA implementsRunnable { synchronized public void run () { for (int i=0; i<50; ++i) System.out.println("ThreadA"); } } class ThreadB extendsThread { synchronized public void run () { for (int i=0; i<50; ++i) System.out.println("ThreadB"); } } public class Threading { public static void main(String a[]){ new Thread(new ThreadA()).start ( ); new ThreadB().start( ); } } Thread Examples
Thread Life Cycle dead new stop start sleep/done sleeping suspend/resume runnable blocked wait/notify I/O block/complete
Controlling Activities • Threads are meant to be controlled (i.e., when to run, when to pause, etc.) • stop() stops and kills a thread in a controlled fashion. Any locks held by the thread will be released. • destroy()stops and kills a thread (without any cleanup) • interrupt() causes any kind of wait to be aborted • suspend()halts a thread in a way which can be continued normally after receiving resume( ) • yield() give control back to the scheduler • sleep() suspend for a given amount of time • The wait(), notifyAll() andnotify() methods are used on Object to synchronize threads
Scheduling and Priorities • Threads compete for CPU time • System responsiveness requires certain activities to have higher priority • Java uses a pre-emptive fixed-priority scheduler • Time slicing is implementation dependent • Each thread has a priority in the range Thread.MIN_PRIORITY-Thread.MAX_PRIORITY • When created, the priority (and daemon flag) is set equal to the priority of the thread that created it
Thread Groups • A structuring mechanism exists for coordinating large groups of threads • Aids security by isolating threads from each other • A ThreadGroup object can contain threads and other ThreadGroup objects (i.e., the nest) • When a thread is constructed, it can be placed into a ThreadGroup (default is the same ThreadGroup of the thread creating the new thread) • The ThreadGroup class exports operations to get handles to all contained threads, to stop all contained threads, etc.
Java and Mutual Exclusion • A monitor describes total protection for the entire object • In Java, a subset of methods are checked (i.e., methods are declared synchronized, not the class) • Associated with each object (and each class for static methods) is a synchronization lock, similar to a monitor’s lock • A thread, invoking a synchronized method, must acquire the object’s lock upon entering and release it upon leaving the method
Each synchronized method has a protective layer surrounding it In order for a thread to invoke a synchronized method, it must first acquire exclusive access to the object One thread in the object (monitor) at a time entries( ) nth( ) add ( ) get( ) remove( ) Monitors AnObject
Synchronized Statement • Activity-centered synchronization (e.g., critical sections) is also possible in Java synchronized (anObject){ //code block associated //with critical section … } • The lock of anObject is acquired prior to entry into the block and is released upon exit from the block
Competition and Waiting • A sychronized method, once invoked, will run to completion before any other thread gets a chance to run any synchronized method of the same object EXCEPT • when the thread is explicitly suspended via wait or suspend • Note: • a thread running in a synchronized method does not restrict any activity on the object via non-synchronized methods
Guarded Actions • wait() • suspends the thread until a subsequent notify / notifyAll() call is made, on the same object, by some other thread • notifyAll() • wakes up all suspended threads that have been blocked via wait within any method (or synchronized block) of the same object. Suspended threads in Java do not automatically wake up. Resumption must be signaled explicitly. • notify() • wakes up the first suspended thread
Buffer (1) class Buffer { private int contents; private boolean available = false; public synchronized int get() { while (! available ) { try { wait(); } catch (InterruptedException e) { } } available = false; notify(); return contents; }
Buffer (2) public synchronized void put (int value) { while (available) { try { wait(); } catch (InterruptedException e) {} } contents = value; available = true; notify(); } }
Wait • A thread will need to suspend within a synchronized method whenever it detects a situation in which it can’t continue (until some other action occurs) • To prevent deadlock and to maintain the properties of the monitor, such waiting must: • release the monitor lock • actually suspend its activity • Upon resumption, insure that the monitor lock is reacquired before operation within the synchronized method continues
More Wait ( ) and NotifyAll( ) • In general, conditional waits should always be placed in while loops (as previous). When the action resumes, the condition may or may not (still) be true • Like sleep, wait can be broken by an interruption (use try block around wait) • notifyAll() • in the current implementations, does NOT relinquish the monitor lock. However, the thread will release the lock upon exiting the synchronized method.
Agenda • Introduction to Java (today) • What is Java? • Tools Overview • Language Overview • Advanced Topics (next session) • Error Handling • Multithreading • Networking
Networking in Java • The classes in the java.net package are designed to support Client-Server computing and Web-based applications • Client-Server model is supported by sockets. This is low-level. Requires knowledge of protocol, host and ports, and I/O model. • Web-based work is handled by a higher-level URL (universal resource locator) model which given a location on the Web automatically constructs Java objects.
Socket Based I/O • Supports client-server model • Client-server refers to a model of computation where services are implemented as stand-alone processes • One or more clients obtain services from a Server by invoking operations on them. • Middleware client-server solutions provide an RPC (remote procedure call) mechanism on top of a message passing interface
The java.net Socket related Classes • InetAddress – represents Internet address. Provides functions to query hostnames, etc. • Socket – Encapsulates a connected socket. To construct a socket you must do so by connecting to some server • SocketImpl – Both Socket and ServerSocket get services from the OS via a SocketImpl • DatagramSocket – Support for sending and receiving Datagrams • DatagramPacket – Encapsulation of a self-describing packet • ServerSocket – Main classes used by a server which wants to accept connections at an advertised port
Sockets • All network communication is application to application (point-to-point) • An endpoint is identified by a Socket, which encapsulates a host and an application address (port) • Two broad categories of Sockets based on the nature of the communication: • Stream Sockets maintains a connection between two endpoints, offers reliability guarantees and is bi-directional (TCP/IP) • Datagram Socket is used for "one-shot" one-way messages and does not offer any reliability guarantees (UDP/IP) • Most Internet services (protocols), e.g. ftp, sendmail, telnet, http, . . . are built on top of Stream Sockets • SNMP uses Datagram Sockets
Endpoint Naming • To communicate you must uniquely identify a host and service: • The host is encapsulated by the InetAddress class • The service address or port, is a 32 bit integer • An InetAddress object corresponds to an IP (Internet Protocol) address and comes in two forms: • Dotted ASCII, e.g. ncc.hursley.ibm.com • Dotted Decimal, e.g. 193.129.184.100 • Currently, IP addresses are 32 bits, presented as a byte array ( this accommodates future 64 bit IP addresses) • The InetAddress class has no public constructors. Use public static methods ("virtual constructors") • InetAddress getByName (String) • InetAddress[] getAllByName(String) • InetAddress getLocalHost()
String find(String w) throws UnknownHostException { StringBuffer sb = new StringBuffer(); Socket s; try { s = new Socket( "whois.internic.net", 43 ); InputStream in = s.getInputStream(); DataOutputStream out = new DataOutputStream(s.getOutputStream()); out.writeBytes(w + "\r\n"); out.flush(); for (int c=in.read(); c >= 0; c = in.read()) sb.append( (char) c ); } catch( IOException e ) { /* handle error */ } finally { try {if (s != null) s.close(); } catch (IOException e) {/* handle error*/} } return sb.toString(); } Connecting to a Service (Whois)
Connecting to a Server (non-Java) Server Listen and Accept Client Connection Request create socket stream bind socket to port create socket stream listen for connection connect request accept connection write to socket read on session socket
Connecting to a Server (Java) Client Connection Request Server Listen and Accept create ServerSocket accept connection create Socket open InputStream open OutputStream write read on InputStream
Socket Connection - Server public class Server { private ServerSocket theListen; private int myPort = 9876; public void listenLoop() { try { theListen = new ServerSocket(myPort); while (true) { Socket aSession = theListen.accept(); doSomething (aSession); } } catch (IOException e) {System.out.println("Server"+e.getMessage())}; }
Socket Connection - Client public class Client { private String hostname; private int port; public void someMethod() { try { Socket mySession=new Socket(hostname, port); doSomething (mySession); } catch(IOException e) {System.out.println("Client"+e.getMessage())}; } }
Datagram Sockets • The java.net package also supports communicating via Datagrams • DatagramSockets constructor performs both socket creation and address binding • Read and write DatagramPackets from/to DatagramSocket • A DatagramPacket describes destination socket, and inserts data into a byte array • Datagrams support broadcast • Used by SNMP, games, etc.
Web-based Applications • Web Based applications use concept of URL to locate and identify the content of information on the Web. • Uniform Resource Locator: • http://www.ibm.com/index.html • Protocol 'http:' • Server name (and port) 'www.ibm.com(:80)' • File name and reference 'index.html'
Topic Summary • Error Handling • Java uses exceptions for error handling • Methods which throw exceptions must be called from within a block to catch and handle the exception • The finally block is always executed • Multithreading • Runnable objects • Scheduling and priorities • Synchronization and locking • Networking • Java provides a layered set of networking classes • At the lowest level are sockets • At the highest level are URLs