© M. Winter COSC 3P91 – Advanced Object-Oriented Programming 3.13.1 What is XML? XML stands for E X tensible M arkup L anguage XML is a markup language.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Object-Oriented Software Engineering Concurrent Programming.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 11.
26-Jun-15 Threads and Turns. Thread review There are two ways to create a Thread object.. Extend Thread and supply a run method: class MyThread extends.
Definitions Process – An executing program
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Multithreading.
Java Programming: Advanced Topics
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Internet Software Development Controlling Threads Paul J Krause.
Threading Eriq Muhammad Adams J
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Chaining & Threading Steve Chenoweth Office: Moench Room F220 Phone: (812)
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Concurrent Programming in JAVA Steve Pruett - Introduction Jaime Mendez – Thread Creation Adrian Garcia – Thread Management Eric Orozco – Thread Safety.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multi Threading.
Multithreading.
Multithreaded Programming in Java
Threads Chate Patanothai.
What is XML? XML stands for EXtensible Markup Language
Condition Variables and Producer/Consumer
Java Based Techhnology
Multithreading.
Multithreaded Programming
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming What is XML? XML stands for E X tensible M arkup L anguage XML is a markup language much like HTML, but –all XML elements must have a closing tag –XML tags are case sensitive –All XML elements must be properly nested –All XML documents must have a single root element –Attribute values must always be quoted XML was designed to describe data XML tags are not predefined. You must define your own tags. Example: Rob Jani Reminder Don't forget me this weekend!

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example <walls north="true" east="false" south="false" west="false"/>...

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming XML Schema XML Schema is a language that can be used to describe the syntactical structure of XML documents. It is expressed in XML, self-describing and simple, can be used to validate XML documents, W3C approved (World Wide Web Consortium). An XML document may specify its schema using the schemaLocation attribute.... In Java XML parsers can be triggered to use a specific schema.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Parsing XML In order to parse an XML source you’ll need: javax.xml.parsers.DocumentBuilderFacory A factory creating DocumentBuilder s. According to the parameters of the factory the generated DocumentBuilder will use certain XMLSchemas. javax.xml.parsers.DocumentBuilder This class will parse the input and create a Document. the input – an element of one of the following classes –File –org.xml.sax.InputSource –Reader –InputStream –String (url)

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Interface Node An XML document is represented by a tree structure, in which each tree node is a class implementing the interface org.w3c.dom.Node. important methods –String getNodeName() #document #text user defined tag –NamedNodeMap getAttributes() Attr getNamedItem(String name) –Node getFirstChild() –Node getLastChild() –NodeList getChildNodes() int length() Node item(int i)

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example #document factory #text location #text floor #text location #text floor #text #walls #text... The tree structure of the factory example with the name of each node.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example in Java factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_XML_SCHEMA); } catch (Exception ex) {... }; String schema = "...factory.xsd"; String[] schemas = { schema }; factory.setAttribute(JAXP_SCHEMA_SOURCE,schemas); try { builder = factory.newDocumentBuilder(); } catch (Exception ex) {... }; File f = new File("...factory.xml"); try { document = builder.parse(f); } catch (Exception ex) {... };

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming COSC3P40.xml Package for easy creating and parsing XML code. public interface XMLObject { public String toXMLString(); } public interface XMLNodeConverter { public E convertXMLNode(Node node); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming COSC3P40.xml.XMLReader public class XMLReader { private static final String JAXP_SCHEMA_LANGUAGE = " private static final String W3C_XML_SCHEMA = " private static final String JAXP_SCHEMA_SOURCE = " private DocumentBuilderFactory factory; private DocumentBuilder builder = null; private Document document = null; private XMLNodeConverter converter = null;

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public XMLReader() { factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); try { factory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_XML_SCHEMA); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }; } public void setXMLSchema(String schema) { String[] schemas = { schema }; factory.setAttribute(JAXP_SCHEMA_SOURCE,schemas); try { builder = factory.newDocumentBuilder(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public void setXMLNodeConverter(XMLNodeConverter converter) { this.converter = converter; } public E readXML(File f) { checkStatus(); try { document = builder.parse(f); } catch (Exception ex) { ex.printStackTrace(); }; return converter.convertXMLNode(document.getFirstChild()); }... private void checkStatus() { if (builder==null) { System.out.println("No XMLSchema set."); System.exit(1); }; if (converter==null) { System.out.println("No XMLNodeConverter set."); System.exit(1); }; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming COSC3P40.xml.XMLTools Collection of useful (static) methods. public static List getChildNodes(Node node) { List result = new LinkedList (); NodeList list = node.getChildNodes(); for(int i=0;i<list.getLength();i++) if (!list.item(i).getNodeName().equals("#text")) result.add(list.item(i)); return result; } public static int getIntAttribute(Node node, String name) { Attr attr = (Attr) node.getAttributes().getNamedItem(name); return Integer.valueOf(attr.getValue()); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public static boolean getBoolAttribute(Node node, String name) { Attr attr = (Attr) node.getAttributes().getNamedItem(name); return Boolean.valueOf(attr.getValue()); } public static String getStringAttribute(Node node, String name) { Attr attr = (Attr) node.getAttributes().getNamedItem("name"); return attr.getValue(); } public static Enum getEnumAttribute(Class c, Node node, String name){ Attr attr = (Attr) node.getAttributes().getNamedItem(name); Class[] array = new Class[1]; array[0] = String.class; Object obj = null; try { obj = c.getMethod("valueOf",array).invoke(null,attr.getValue()); } catch (Exception e) {... }; if (obj instanceof Enum) return (Enum) obj; return null; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example public class Factory implements XMLObject {... public static Factory load(String fileName) { String xsd = "../XSD/factory.xsd"; XMLReader reader = new XMLReader (); reader.setXMLSchema(xsd); reader.setXMLNodeConverter(new FactoryReader()); return reader.readXML(new File(fileName)); }... public String toXMLString() { String result = "<factory xSize=\"" + xSize + "\" ySize=\"" + ySize +"\">\n"; for(int i=0; i<xSize; i++) for(int j=0; j<ySize; j++) result += grid[i][j].toXMLString() + "\n"; return result + " "; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class FactoryReader implements XMLNodeConverter { private LocationReader locReader;... public Factory convertXMLNode(Node node) { Factory factory = null; if (node.getNodeName().equals("factory")) { int xSize = getIntAttribute(node,"xSize"); int ySize = getIntAttribute(node,"ySize"); Location[][] grid = new Location[xSize][ySize]; List list = getChildNodes(node); if (list.size() == xSize*ySize) { for(int i=0; i<xSize; i++) for(int j=0; j<ySize; j++) grid[i][j] = locReader.convertXMLNode(list.get(i*ySize+j)); factory = new Factory(xSize,ySize,grid); }; return factory; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Multithreading multitasking Example: Downloading a file from the internet while writing a paper at the same time. thread –single sequential flow of control –managed by the same Java virtual machine –share common memory space thread versus process; process –managed by the operating system –no shared memory space –communication just via interprocess communication channels

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Multithreading (cont.) advantages –reactive systems continuously monitor arrays of sensors and react according to the sensor readings –reactive GUI allows to respond to user input immediately even if the application is engaged in a time-consuming task –multi-client servers –multiple processors executing threads on different processors in parallel

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Multithreading (cont.) nondeterministic thread ordering –multi processors –time-sharing Thread A Thread B Thread A starts Thread B starts Time

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Creating and Running Threads Three possibilities: extending the Thread class implementing the Runnable interface using anonymous inner classes

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Thread class class for active objects –subclasses of Thread should override the run method run hook method –implements the interface Runnable implement run start method –run should not invoked directly. Doing so would cause the method to be executed in the thread of the caller, not in a new thread. –use the start method to execute a thread

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Extending the Thread Class public class MyThread extends Thread { public void run() { System.out.println(“Do something cool here.“); } Thread myThread = new MyThread(); myThread.start();

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Implementing the Runnable interface public class MyClass extends SomeOtherClass implements Runnable { public MyClass() { Thread thread = new Thread(this); thread.start(); } public void run() { System.out.println(“Do something cool here.“); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Using anonymous inner classes new Thread() { public void run() { System.out.println(“Do something cool here.“); } }.start();

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Comparison of the methods Extending the Thread class is easy but uses inheritance. Use the Runnable interface if you want to have a class that extends another and can also run as a thread. Use anonymous inner classes only if the code in the run method is very short.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Thread safety Safety properties are conditions that should hold throughout the lifetime of a program. –stipulate that nothing bad should ever happen –interrupted threads may leave an object in an invalid state public class Maze { private int playerX; private int playerY; public boolean isAtExit() { return (playerX == 0 && playerY == 0); } public void setPosition(int x, int y) { playerX = x; playerY = y; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Initial state of p : playerX = 1 playerY = 0 p.setPosition(0,1); playerX = x; p.isAtExit(); Thread A Thread B Thread A is pre-empted by Thread B returns true playerY = y; playerX = 0 playerY = 0 playerX = 0 playerY = 1

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Controlling Threads states of a thread –new –alive runnable blocked –dead priorities –always runs highest priority thread random choice, among those with same priority preemptive, i.e., a thread of higher priority will preempt a thread with lower priority –use priorities only to tune the performance of programs

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Dead Alive BlockedRunnable Wait for target to finish Wait to be notified SleepingInterruptedNot interrupted New notify() notifyAll() wait() join() Target finish sleep() Time out interrupt() start() run() returns yield()

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Synchronization public class Maze { private int playerX; private int playerY; public synchronized boolean isAtExit() { return (playerX == 0 && playerY == 0); } public synchronized void setPosition(int x, int y) { playerX = x; playerY = y; } This code is thread-safe.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Synchronization (cont.) When the JVM executes a synchronized method, it acquires a lock on that object. if one synchronized method owns a lock, no other synchronized method can run until the lock is released only one lock on an object at a time lock is released when the method is finished

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Synchronization (cont.) Do not oversynchronize ! synchronize if one or more threads will access the same object or field. do not synchronize an entire method if only parts of the method need to be synchronized public void myMethod() { synchronize(this) { // code that needs to be synchronized } // code that is already thread-safe } do not synchronize a method that uses only local variables: //a method which should not be synchronized public int square(int n) { int s = n * n; return s; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Using sleep() sleep() is a static method of the class Thread. Thread.sleep(1000); causes the currently running thread to sleep for 1000 (or any amount of time given as an argument) miliseconds (state blocked ) a sleeping thread does not consume any CPU time when the specified duration of time expires the thread returns to the runnable state

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Using wait() and notify() Problem: Thread A should wait on Thread B to send a message: Solution 1: //Thread A public void waitForMessage() { while (hasMessage == false) { Thread.sleep(100); } //Thread B public void sendMessage(String message) { … hasMessage = true; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Solution 2: //Thread A public synchronized void waitForMessage() { try { wait(); } catch (InterruptedException ex) {} } //Thread B public synchronized void sendMessage(String message) { … notify(); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming The wait(), notify() and notifyAll() methods are defined in the class Object. the wait() method is used in synchronized blocks of code. –the lock is released and the thread waits to be notified (state blocked ) the notify() method is also used in synchronized blocks of code. –notifies on thread waiting on the same lock (randomly) –waiting thread becomes runnable variants –wait for a maximum amount of time: wait(100); there is no way to tell whether the wait() method returned because of a timeout or because the thread was notified –notify all threads waiting on the lock: notifyAll();

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Using join() The join() method causes a thread to enter the blocked state and wait for another thread to finish, at which time it will be returned to the runnable state. useful, when you want to make sure all threads are finished before you do some cleanup

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public static void main(String[] args) { Thread playerA = new Thread() { public void run() { System.out.println("A started"); try { Thread.sleep(10000); } catch (InterruptedException e) {}; System.out.println("A terminated"); } }; Thread playerB = new Thread() { public void run() { System.out.println("B started"); try { Thread.sleep(15000); } catch (InterruptedException e) {}; System.out.println("B terminated"); } };

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming playerA.start(); playerB.start(); try { playerA.join(); playerB.join(); } catch (InterruptedException e) {}; System.out.println("Cleanup"); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Deadlock Deadlock is the result of two threads that stall because they are waiting on each other to do something. General situation: 1.Thread A acquires lock 1. 2.Thread B acquires lock 2. 3.Thread B waits for lock 1 to be released. 4.Thread A waits for lock 2 to be released.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Deadlock - Example MessageHandler a; MessageHandler b; //Thread A //Thread B a.waitForMessage(); b.waitForMessage(); b.sendMessage(“...“); a.sendMessage(“...“); In general, detecting and preventing deadlock is difficult. Using the deadlock detector. 1.run your program 2.press Ctrl+break (DOS box) 3.JVM displays a full thread dumb

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Liveness Liveness properties stipulate that something positive will eventually happen. Examples: 1.A certain task will be completed eventually. 2.A thread should always respond to user input. 3.The status of certain systems must be displayed and updated constantly. Common types of liveness failures: deadlock contention – aka starvation or indefinite postponement –thread never gets a chance to run –sleep() or yield() dormancy –blocked thread never released –failure to call notify() premature termination

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example – Thread pool A thread pool is a group of threads designed to execute arbitrary tasks. limits the number of threads on the system for processor-intensive tasks ThreadPool threadPool = new ThreadPool(3); for (int i=0; i < 8; i++) { threadPool.runTask(createTask(i)); } threadPool.join();

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming private static final Runnable createTask() { return new Runnable() { public void run() { System.out.println("Task " + taskID + ": start"); // simulate a long-running task try { Thread.sleep(500); } catch (InterruptedException ex) { }; System.out.println("Task " + taskID + ": end"); } };

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Thread group ThreadPool uses the ThreadGroup class. A ThreadGroup is a group of threads and some methods to modify the threads. setDaemon() - changes the daemon status of this thread group. A daemon thread group is automatically destroyed when its last thread is stopped. interrupt() – interrupts all threads in this thread group. activeCount() - returns an estimate of the number of active threads in this thread group. enumerate() - copies into the specified array (argument) every active thread in this thread group.

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public class ThreadPool extends ThreadGroup { private boolean isAlive; private LinkedList taskQueue; //Java 1.5 private static int threadID; private static int threadPoolID; public ThreadPool(int numThreads) { super("ThreadPool-" + (threadPoolID++)); setDaemon(true); isAlive = true; taskQueue = new LinkedList (); //Java 1.5 for (int i=0; i<numThreads; i++) { new PooledThread().start(); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming private class PooledThread extends Thread { public PooledThread() { super(ThreadPool.this,"PooledThread-" + (threadID++)); } public void run() { while (!isInterrupted()) { Runnable task = null; // get a task to run try { task = getTask(); } catch (InterruptedException ex) { } if (task == null) { //if getTask() returned null return; //or was interrupted close this } //thread by returning. try { //run the task, and eat any task.run(); //exceptions it throws } catch (Throwable t) { uncaughtException(this, t); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public synchronized void runTask(Runnable task) { if (!isAlive) { throw new IllegalStateException(); } if (task != null) { taskQueue.add(task); notify(); } protected synchronized Runnable getTask() throws InterruptedException { while (taskQueue.size() == 0) { if (!isAlive) { return null; } wait(); } return taskQueue.removeFirst();//Java 1.5 }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public void join() { // notify all waiting threads that this ThreadPool is no // longer alive synchronized (this) { isAlive = false; notifyAll(); } // wait for all threads to finish Thread[] threads = new Thread[activeCount()]; int count = enumerate(threads); for (int i=0; i<count; i++) { try { threads[i].join(); } catch (InterruptedException ex) { } }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming public synchronized void close() { if (isAlive) { isAlive = false; taskQueue.clear(); interrupt(); }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Task 0: start Task 1: start Task 2: start Task 0: end Task 3: start Task 1: end Task 4: start Task 2: end Task 5: start Task 3: end Task 6: start Task 4: end Task 7: start Task 5: end Task 6: end Task 7: end Press Enter to continue An example

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design Pattern Guarded Suspension a concurrency pattern intent: –avoid the deadlock situation that can occur when a thread is about to execute an object’s synchronized method and the state of the object prevents the method from executing to completion motivation: –a Queue class in a multiple thread environment –call of pull when the Queue is empty (caller has to wait until an element is pushed to the queue) solution –if the precondition is not fulfilled wait but release the lock (in Java use wait() )

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Collaboration diagram q : Queue 1a: pull() {concurrency = guarded | !isEmpty() 1b: push() {concurrency = guarded

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example public class Queue { private ArrayList data = new ArrayList (); … synchronized public void push(E element) { data.add(element); notify(); } synchronized public E pull() { while (data.size() == 0) { try { wait(); } catch (Exception e) {}; }; E element = data.removeFirst(0); return element; }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Design Patter Producer-Consumer aka Pipe (just one Producer) a concurrency pattern intent: –coordination of asynchronous production and consumption of information or objects Queue push(X : T) pull() : T size() : Int ProducerConsumer 0..* 1 1 queue consumer Consume-queued objects Queue-produced objects

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example Class Queue as before (using the design pattern Guarded Suspension). public class Producer implements Runnable { private Queue myQueue; … public Producer(Queue myQueue) { this.myQueue = myQueue; … } public void run() { … myQueue.push(myData); … }

© M. Winter COSC 3P91 – Advanced Object-Oriented Programming Example (cont’d) public class Consumer implements Runnable { private Queue myQueue; … public Consumer(Queue myQueue) { this.myQueue = myQueue; … } public void run() { … myData = myQueue.pull(); … }