57
© M. Winter COSC 3P91 – Advanced Object-Oriented Programming 3.1 What is XML? XML stands for EXtensible Markup Language 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: <note date="12/11/2002"> <to>Rob</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>

© 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

Embed Size (px)

Citation preview

Page 1: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.1

What is XML?• XML stands for EXtensible Markup Language• 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:<note date="12/11/2002">

<to>Rob</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

Page 2: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.2

Example

<?xml version="1.0"?>

<factory xSize="7" ySize="7">

<location>

<floor/>

</location>

<location>

<floor/>

<walls north="true" east="false"

south="false" west="false"/>

</location>

...

</factory>

Page 3: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.3

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.<factory xSize="2" ySize="2"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="...factory.xsd">

...

In Java XML parsers can be triggered to use a specific schema.

Page 4: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.4

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">

<xs:include schemaLocation="belt.xsd"/> ... <xs:element name="factory"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" ref="location"/> </xs:sequence> <xs:attribute name="xSize" use="required" type="xs:nonNegativeInteger"/> <xs:attribute name="ySize" use="required" type="xs:nonNegativeInteger"/> </xs:complexType> </xs:element> <xs:element name="location"> <xs:complexType> <xs:sequence> <xs:choice minOccurs="1" maxOccurs="1"> <xs:element ref="belt"/>

... </xs:choice> <xs:choice minOccurs="0" maxOccurs="1">

<xs:element ref="crusher"/><xs:element ref="pusher"/>

</xs:choice> <xs:element ref="walls" minOccurs="0" maxOccurs="1"/>

</xs:sequence> </xs:complexType> </xs:element></xs:schema>

Page 5: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.5

Parsing XMLIn order to parse an XML source you’ll need:

• javax.xml.parsers.DocumentBuilderFacory

A factory creating DocumentBuilders. According to the parameters of thefactory 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)

Page 6: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.6

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)

Page 7: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.7

Example#document

factory#textlocation

#textfloor#text

#textlocation

#textfloor#text#walls#text

#text...

The tree structure of the factory example with the name of each node.

Page 8: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.8

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) { ... };

Page 9: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.9

COSC3P40.xml

Package for easy creating and parsing XML code.

public interface XMLObject {

public String toXMLString();

}

public interface XMLNodeConverter<E> {

public E convertXMLNode(Node node);

}

Page 10: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.10

COSC3P40.xml.XMLReader

public class XMLReader<E> {

private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";

private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";

private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";

private DocumentBuilderFactory factory; private DocumentBuilder builder = null; private Document document = null; private XMLNodeConverter<E> converter = null;

Page 11: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.11

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); }; }

Page 12: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.12

public void setXMLNodeConverter(XMLNodeConverter<E> 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); };}

Page 13: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.13

COSC3P40.xml.XMLTools

Collection of useful (static) methods.

public static List<Node> getChildNodes(Node node) {List<Node> result = new LinkedList<Node>();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());

}

Page 14: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.14

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;

}

Page 15: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.15

Example

public class Factory implements XMLObject {...public static Factory load(String fileName) {

String xsd = "../XSD/factory.xsd"; XMLReader<Factory> reader = new XMLReader<Factory>(); 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 + "</factory>";

}

Page 16: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.16

public class FactoryReader implements XMLNodeConverter<Factory> {

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<Node> 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;}

}

Page 17: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.17

Multithreading

• multitaskingExample: Downloading a file from the internet while writing a paper atthe 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

Page 18: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.18

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

Page 19: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.19

Multithreading (cont.)

• nondeterministic thread ordering– multi processors– time-sharing

Thread A

Thread B

Thread A starts Thread B startsTime

Page 20: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.20

Creating and Running Threads

Three possibilities:

• extending the Thread class• implementing the Runnable interface• using anonymous inner classes

Page 21: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.21

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

Page 22: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.22

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();

Page 23: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.23

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.“);

}

}

Page 24: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.24

Using anonymous inner classes

new Thread() {

public void run() {

System.out.println(“Do something cool here.“);

}

}.start();

Page 25: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.25

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.

Page 26: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.26

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;

}}

Page 27: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.27

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

Page 28: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.28

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

Page 29: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.29

Dead

Alive

Blocked Runnable

Wait for target to finish

Wait to be notified

Sleeping Interrupted

Not interrupted

New

notify() notifyAll()

wait()

join()

Target finish

sleep()

Time outinterrupt()

interrupt()

start()

run() returns

yield()

Page 30: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.30

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.

Page 31: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.31

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

Page 32: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.32

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 synchronizedpublic int square(int n) {

int s = n * n;return s;

}

Page 33: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.33

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

Page 34: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.34

Using wait() and notify()Problem: Thread A should wait on Thread B to send a message:

Solution 1:

//Thread Apublic void waitForMessage() {

while (hasMessage == false) {Thread.sleep(100);

}}

//Thread Bpublic void sendMessage(String message) {

…hasMessage = true;

}

Page 35: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.35

Solution 2:

//Thread A

public synchronized void waitForMessage() {

try {

wait();

}

catch (InterruptedException ex) {}

}

//Thread B

public synchronized void sendMessage(String message) {

notify();

}

Page 36: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.36

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();

Page 37: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.37

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

Page 38: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.38

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"); } };

Page 39: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.39

playerA.start();

playerB.start();

try {

playerA.join();

playerB.join();

}

catch (InterruptedException e) {};

System.out.println("Cleanup");

}

Page 40: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.40

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.

Page 41: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.41

Deadlock - ExampleMessageHandler 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 program2. press Ctrl+break (DOS box)3. JVM displays a full thread dumb

Page 42: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.42

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

Page 43: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.43

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();

Page 44: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.44

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");

}

};

Page 45: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.45

Thread group

ThreadPool uses the ThreadGroup class. A ThreadGroup is a group ofthreads 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.

Page 46: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.46

public class ThreadPool extends ThreadGroup {

private boolean isAlive;

private LinkedList<Runnable> 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<Runnable>(); //Java 1.5

for (int i=0; i<numThreads; i++) {

new PooledThread().start();

}

}

Page 47: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.47

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); } }

}}

Page 48: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.48

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

}

Page 49: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.49

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) { }

}

}

Page 50: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.50

public synchronized void close() {

if (isAlive) {

isAlive = false;

taskQueue.clear();

interrupt();

}

}

Page 51: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.51

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

Page 52: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.52

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())

Page 53: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.53

Collaboration diagram

q : Queue

1a: pull()

{concurrency = guarded | !isEmpty()

1b: push()

{concurrency = guarded

Page 54: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.54

Examplepublic class Queue<E> {

private ArrayList<E> data = new ArrayList<E>();…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;

}}

Page 55: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.55

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

Producer Consumer

0..*

0..*

1

1

queue

consumer

Consume-queued objects

Queue-produced objects

Page 56: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.56

ExampleClass 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);…

}}

Page 57: © 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

© M. Winter

COSC 3P91 – Advanced Object-Oriented Programming

3.57

Example (cont’d)

public class Consumer implements Runnable {

private Queue myQueue;

public Consumer(Queue myQueue) {

this.myQueue = myQueue;

}

public void run() {

myData = myQueue.pull();

}

}