Advanced Topics Chapter 13 Chapter Contents Chapter Objectives 13.1 Introductory Example: Sorting a List 13.2 Topic: Multithreading 13.3 Topic: Client-Server Networking 13.4 Graphical/Internet Java: Moon Animation Part of the Picture: The TCP/IP Communications Architecture 13.5 The End? Chapter Objectives • Study the use of threads in Java • Learn about Java's built in support for communication across a network • See an example of threads used in animations • Investigate the TCP/IP communications architecture 13.1 Introductory Example: Sorting a List • Recall use of ArrayList and LinkedList classes – examples of collection classes • A Collections class also exists – one of its methods is sort() – given any List of objects that can be compared, it will arrange them in ascending order • Our example creates an ArrayList of 1,000,000 items – contrasts two different sort routines Design • First approach: Build an ArrayList of n random Integer values – measure time required for the sort • Second approach: Build two ArrayList objects of n/2 random Integers a) measure time to sort first list using Sorter object running as separate thread b) sort second list normally c) merge the two into a single sorted list of length n Anticipated Results • On computer with single CPU, first method should be slightly faster • On computer with multiple CPUs, second method slightly faster – thread performing step a) runs on one CPU – step b) performed on different CPU • Program uses 10 trials and takes average times • Note source code, Figure 13.1 – the extends Thread portion of the declaration gives the ListSorter object its own thread of execution Actual Results • On Pentium II uniprocessor – single-threaded sort took less time – double threaded routine must share processor • On Sun multiprocessor – two-threaded sort faster – multiple CPUs allow two threads to run simultaneously – give 30% faster results 13.2 Topic: Multithreading Thread of Execution • When a program runs, it executes a series of statements – in sequence – some may be skipped in a branch – some may be repeated in a loop • This series is called a thread of execution Multithreading • Programs studied until now are singlethreaded • Java supports multithreaded programs • Advantages of multithreading – speeds up through parallel processing by dividing task into n pieces, each solved independently on separate processors – separates input tasks from processing tasks, processing thread can continue while input thread is blocked Extending the Thread Class 1. Define a class that extends thread – contains a run() method to perform tasks in a separate thread class ListSorter extends Thread { // … public void run() { … } // statements the thread is to execute } 2. Have the normal thread create an instance of the class so defined ListSorter secondSorter = new ListSorter (list1); Extending the Thread Class 3. Make this thread begin running by sending it the start() message secondSorter.start() normal thread secondSorter = new ListSorter(list1); secondSorter.start(); 2nd thread Visualized below: Implementing the Runnable Interface • A class can extend only one other class – if a class needs to extend some nonThread class and run as a distinct thread, the preceding approach will not work • Thus the Runnable interface approach Implementing the Runnable Interface 1. Define a class that implements the Runnable interface • contains a run() method class ListSorter extends Whatever implements Runnable { // … public void run() { … } // statements that thread will execute } Implementing the Runnable Interface 2. Have the normal class create an instance of the class defined in 1. ListSorter secondSorter ListSorter secondSorter = new ListSorter(list1); 3. Also have the class create a new instance of the Thread class • initialized with object created above Thread secondThread = new Thread(secondSorter); Implementing the Runnable Interface 4. Send the new Thread object the start() message secondThread.start(); Note: this is a more complicated approach – used only to run a separate thread that must also extend a non Thread class Synchronizing Accesses to Shared Data • Consider an Account class which provides debit and credit methods which change the balance • If multiple Transaction threads want to access the same Account object problems could arise "Atomic" Operations • Operations that cannot be divided into "smaller" operations • Example: for myBalance being accessed by either the debit() or credit() methods at about the same time – these methods are not atomic at the bytecode level – each has about four separate steps Non Atomic Operations in Separate Threads • Assume credit() and debit() are in separate threads Both will • 1. 2. 3. 4. • read the balance create a temp value add to (or subtract from) the temp value replace the old balance with the temp value If each step is happening at about the same time – each replaces the old balance with its own temp value without knowing about the action of the other, giving an incorrect new balance value !!! Making Methods Atomic • Use the keyword synchronized to declare each method that accesses the critical information class Account{ . . . synchronized public void debit(double amount) { … } synchronized public void credit(double amount { … } private myBalance; } Making Methods Atomic • When a thread … – sends a synchronized message to an object – and … no other thread is executing a synchronized method on that object • Then … – Java locks the object – other synchronized methods cannot access the object until the first terminates 13.3 Topic: Client-Server Networking • Java has built-in support for programs to communicate across a network • Client-server model has two kinds of programs – server programs that wait for other programs (clients) to request service – client programs that contact servers and ask them to perform a service Client-Server Networking Example – web browsers • User clicks on a link, browser (client) program contacts server at that link site • Server retrieves requested file, sends it to browser (client) Modern e-mail programs work in a similar fashion Sockets • Communication endpoints by which programs can send and receive information • Server creates a ServerSocket – waits for clients to connect to it • Client creates a Socket to connect to that server's ServerSocket Socket Details • Sockets must be distinct from all others • Java requires special integer value, called a port • Ordered pair (ComputerName, portNumber) is the unique socket identification Example: A Daytime Client • To illustrate how a Socket uses a port • Note source code for TCP daytime client, Figure 13.3 Features • Client Socket initialization – connects to ServerSocket at that time – Socket constructor needs name of remote host and port of socket needed Socket S = new Socket(remoteHost, DAYTIME_PORT); Reading form a Socket • Connection alone not enough – must be able to read from it – considered an input operation • Input stream declared BufferedReader M = new BufferedReader( new InputStreamReader( S.getInputStream() )); • Input stream accessed timeOfDay = M.readln(); Writing to a Socket • The server sending the data must declare the output stream PrintWriter W = new PrintWriter( S.getOutputStream(), true); // true enables auto-flush • Server then transmits the information w.println(" … "); ServerSocket Initialization • Client socket initialization – specify remoteHost and port Socket s = new Socket(remoteHost,port); • ServerSocket created by server – no remote host to be specified – specify port only – if 0 specified, sS will be given any free port ServerSocket sS = new ServerSocket(port); Accepting a Connection • The ServerSocket constructor builds, initializes an object – • must also explicitly tell the object to listen for incoming connections Socket s = sS.accept() Results of accept() 1. server sending the accept() blocks until a client requests connection 2. accept() builds, sends a Socket that is the actual end-point for connection back to client Reading from, Writing to a ServerSocket • Done in same way as Socket is treated • Build a BufferedReader or PrintWriter – as a wrapper for the ServerSocket • Then use readLn() or println() – to communicate with the client Closing a Socket • Consider it a stream – closed with the close() command myReader.close(); • If socket not closed – programs can become "zombie processes" Example: A Daytime Server Behavior 1. Build ServerSocket to listen for connections on port 1013 2. Repeat the following a) use accept() to accept connection request b) Build PrintWriter for resulting Socket c) Get current day, time from system d) Write current day, time to PrintWriter Note source code, example e) Close PrintWriter (and of Socket) run, Figure 13.4 Multithreaded Servers • Program of Figure 13.4 is singlethreaded – same thread accepts connect requests, then processes – uses a forever loop • Single thread here sufficient, quick response possible • Longer task would cause backlog of client requests Multithreaded Servers • Each iteration of the processing loop will: – accept connection request – create a handler thread for that client – server thread immediately returns to top of processing loop for( ; ; ) { Socket sessionSocket = myServerSocket.accept(); // create new thread for service using // sessionSocket // start the thread } Example: Multithreaded Echo Server • Server will read lines of text client sends – echo back each line – may be multiple lines, time consuming • EchoServer class – builds its ServerSocket – repeatedly invokes accept() creates new EchoHandler thread for each request Echo Server • Source code for multithreaded echo server, Figure 13.5 • Echo-handler thread source code, Figure 13.6 • Echo Client program, figure 13.7 • Multithreading rule of thumb: If providing a server's service takes less time than creating a thread, then a singlethreaded server should be used 13.4 Graphical/Internet Java: Moon Animation • Application will present a stationary moon – use animation to show change of appearance over time – use "slider" to control speed of animation – use pause, play, forward, backward buttons Behavior Moon Phases Faster Slower || Process States • Running state (view on previous slide) • Paused state – shows Backward, Forward, Play buttons – removes slider, pause Forward pressed Pause pressed running paused Play pressed Backward pressed Strategy • Load images from file with getImage() command • Load images into an array • Iterate through array in circular fashion – display in sequence • Must also listen for user-generated events (buttons pushed) • Listening and animating at the same time requires two threads Source Code • Note source code, Figure 13.8 • Getting the Images – in constructor, for loop – routine waits for all images before displaying, no flicker • Constructor also starts the thread in running state • paintComponent() method used to draw images Source Code • Defining Thread behavior – run method repeatedly checks for pause and then increments image and repaints • Pausing execution – synchronized pause() method sets flag – synchronized waitIfPaused() method calls wait() – synchronized go() changes flag Behind the Scenes • Java objects have an attribute called a "monitor" – Used for synchronization of methods • A class must "own the monitor" before it can execute a synchronized method • Synchronized methods each have a lock, checked when a thread seeks to execute • Thread suspended on "lock list" while waiting to own the monitor Behind the Scenes • Consider a thread executing synchronized method which invokes wait() – thread gives up monitor – Java suspends thread on "waiting list" to be notified – left on waiting list until another synchronized thread sends notify() – notify() transfers thread to lock list to wait for re-acquisition of the monitor MoonPhases Class • Note source code, Figure 13.9 • New feature used, slider control mySlider = new JSlider(0,1000, INITIAL_DELAY); – implements ChangeListener interface – requires stateChanged() method • actionPerformed() method – determines which button pressed, – sends appropriate message to MoonAnimator Part of the Picture: The TCP/IP Communications Architecture • Universal standards have been adopted for interconnection software • Before standards developed, we need … – structure or protocol architecture – defines the communication tasks Most widely • Two current architectures used – TCP/IP – OSI (Open Systems Interconnection) Organization of TCP/IP Five relatively independent layers: 1. Physical layer • connects computer with network 2. Network access layer • concerned with access to and routing data across a network for end systems 3. Internet layer • procedures for data to traverse multiple interconnected networks Organization of TCP/IP Five relatively independent layers: 4. Host-to-host layer or transport layer • concerned with reliable data exchange 5. Application layer • • supports variety of applications separate modules needed for each application Operation of TCP/IP Consider a sample operation – application associated with port 1 at host A wishes to send message to another application, port 2, host A • Application gives message to CCP – send to host B, port 2 • TCP gives message to IP – send to host B (need not mention port) – note that control info and data may be broken into smaller blocks of data – blocks include TCP header and TCP segment – header can include destination port, sequence number, checksum Operation of TCP/IP • IP hands message to network access layer – – – – – send it to router J IP also appends header of control information Network layer appends header, transmits packet to router headers contain information needed for routing include destination subnetwork address and facilities requests • At router, packet header removed, IP header examined – datagram directed to destination • At destination, reverse process occurs – headers removed at various levels – destination application receives message TCP and UDP • Note header format for TCP, Figure 13.13a • UDP – User Datagram Protocol – provides connectionless service for application-level procedures – does not guarantee delivery, preservation of sequence, duplication protection – provides message sending with minimum protocol IP and IPv6 • Provides functional enhancements over current IP • Accommodates higher transmission speeds, mixing of data streams • Handles increasing number of addresses TCP/IP Applications • Simple mail transfer protocol (SMTP) – basic electronic mail – features include mailing lists, return receipts, forwarding – uses TCP to send it to SMTP module elsewhere • File transfer protocol (FTP) – accommodates both text and binary files – enables user access control TCP/IP Applications • TELNET provides remote logon capability – user at one computer can log on to remote computer – user can function as if directly connected to remote location – terminal traffic between user and server carried on TCP connection 13.5 The End? • End of the text … but … not the end of Java! – we have covered only a small part of its capabilities • We have concentrated mainly on programming … – computer science is so much more • Take what you have learned – use it – enlarge upon it!