11. Threads A way to support several parallel activities in a program Execute asynchronously and ”simultaneously” e.g. timeslicing If two threads are dependent.

Slides:



Advertisements
Similar presentations
 Fundamentals of Web Design.  Describe the history and theory of XHTML  Understand the rules for creating valid XHTML documents  Apply a DTD to an.
Advertisements

History Leading to XHTML
11. Threads A way to support several parallel activities in a program Execute asynchronously and ”simultaneously” e.g. timeslicing If two threads are dependent.
XML DOM and SAX Parsers By Omar RABI. Introduction to parsers  The word parser comes from compilers  In a compiler, a parser is the module that reads.
 2002 Prentice Hall, Inc. All rights reserved. ISQA 407 XML/WML Winter 2002 Dr. Sergio Davalos.
Tutorial 9 Working with XHTML. XP Objectives Describe the history and theory of XHTML Understand the rules for creating valid XHTML documents Apply a.
Trees. Definition of a tree A tree is like a binary tree, except that a node may have any number of children –Depending on the needs of the program, the.
Creating a Well-Formed Valid Document. 2 Objectives Introducing XHTML Creating a Well-Formed Document Creating a Valid Document Creating an XHTML Document.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
CS 898N – Advanced World Wide Web Technologies Lecture 22: Applying XML Chin-Chih Chang
50.003: Elements of Software Construction Week 5 Basics of Threads.
XP New Perspectives on XML Tutorial 3 1 DTD Tutorial – Carey ISBN
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Javascript and the Web Whys and Hows of Javascript.
VICTORIA UNIVERSITY OF WELLINGTON Te Whare Wananga o te Upoko o te Ika a Maui SWEN 432 Advanced Database Design and Implementation Document Type Definition.
Working with XHTML Creating a Well-Formed Valid Document.
XP Tutorial 9New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with XHTML Creating a Well-Formed Valid Document Tutorial 9.
XP The University of Akron Summit College Business Technology Department Computer Information Systems 2440: 140 Internet Tools Instructor: Enoch E. Damson.
XML Anisha K J Jerrin Thomas. Outline  Introduction  Structure of an XML Page  Well-formed & Valid XML Documents  DTD – Elements, Attributes, Entities.
1 XML at a neighborhood university near you Innovation 2005 September 16, 2005 Kwok-Bun Yue University of Houston-Clear Lake.
Java WWW Week 10 Version 2.1 Mar 2008 Slide Java (JSP) and XML  Format of lecture: What is XML? A sample XML file… How to use.
XP 1 CREATING AN XML DOCUMENT. XP 2 INTRODUCING XML XML stands for Extensible Markup Language. A markup language specifies the structure and content of.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
3 XHTML.
XML 1 Enterprise Applications CE00465-M XML. 2 Enterprise Applications CE00465-M XML Overview Extensible Mark-up Language (XML) is a meta-language that.
XHTML. Introduction to XHTML What Is XHTML? – XHTML stands for EXtensible HyperText Markup Language – XHTML is almost identical to HTML 4.01 – XHTML is.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Chapter 27 The World Wide Web and XML. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.27-2 Topics in this Chapter The Web and the Internet.
1 XML - Extensible Markup Language. 2 HTML - Hypertext Markup Language n HTML has a fixed tag set. n Use these tags to describe how information is to.
1 Tutorial 13 Validating Documents with DTDs Working with Document Type Definitions.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
XML A web enabled data description language 4/22/2001 By Mark Lawson & Edward Ryan L’Herault.
XSLT Kanda Runapongsa Dept. of Computer Engineering Khon Kaen University.
XP Tutorial 9 1 Working with XHTML. XP SGML 2 Standard Generalized Markup Language (SGML) A standard for specifying markup languages. Large, complex standard.
XML - DTD Week 4 Anthony Borquez. What can XML do? provides an application independent way of sharing data. independent groups of people can agree to.
Lesson 3 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
WEB BASED DATA TRANSFORMATION USING XML, JAVA Group members: Darius Balarashti & Matt Smith.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Introduction to Concurrency.
WEB APPLICATION DEVELOPMENT For More visit:
Introduction to XML This presentation covers introductory features of XML. What XML is and what it is not? What does it do? Put different related technologies.
School of Computing and Information Systems CS 371 Web Application Programming XML and JSON Encoding Data.
Chapter 27 The World Wide Web and XML. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.27-2 Topics in this Chapter The Web and the Internet.
C# and Windows Programming XML Processing. 2 Contents Markup XML DTDs XML Parsers DOM.
Java Thread and Memory Model
When we create.rtf document apart from saving the actual info the tool saves additional info like start of a paragraph, bold, size of the font.. Etc. This.
What is XML? eXtensible Markup Language eXtensible Markup Language A subset of SGML (Standard Generalized Markup Language) A subset of SGML (Standard Generalized.
More XML XPATH, XSLT CS 431 – February 23, 2005 Carl Lagoze – Cornell University.
1 Introduction JAXP. Objectives  XML Parser  Parsing and Parsers  JAXP interfaces  Workshops 2.
XML CSC1310 Fall HTML (TIM BERNERS-LEE) HyperText Markup Language  HTML (HyperText Markup Language): December  Markup  Markup is a symbol.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
XP Tutorial 9New Perspectives on HTML and XHTML, Comprehensive 1 Working with XHTML Creating a Well-Formed Valid Document Tutorial 9.
Tutorial 9 Working with XHTML. New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition 2 Objectives Describe the history and theory of XHTML.
Web Technology (NCS-504) Prepared By Mr. Abhishek Kesharwani Assistant Professor,UCER Naini,Allahabad.
Tutorial 9 Working with XHTML. XP Objectives Describe the history and theory of XHTML Understand the rules for creating valid XHTML documents Apply a.
Review IS Overview: Data  Inside the application Collections  Outside the application Database XML  Getting/displaying Swing  Communicating.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
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.
XML 1.Introduction to XML 2.Document Type Definition (DTD) 3.XML Parser 4.Example: CGI Gateway to XML Middleware.
XML. Contents  Parsing an XML Document  Validating XML Documents.
Advanced Swing Trees. Contents I.Introduction to Trees II. Simple Trees III. Editing Trees and Tree Paths IV. Node Enumeration V. Rendering Nodes VI.
Multithreading / Concurrency
Creating a Well-Formed Valid Document
Tutorial 9 Working with XHTML
Java XML IS
Advanced Swing Trees.
Tutorial 9 Working with XHTML
Multithreading.
Java Concurrency.
Java Concurrency.
Synchronization and liveness
Presentation transcript:

11. Threads A way to support several parallel activities in a program Execute asynchronously and ”simultaneously” e.g. timeslicing If two threads are dependent on each other synchronization may be necessary If they depend on a shared resource then deadlock, livelock or race conditions can occur. One solution to synchronization is the semaphore

11.1 Example: Web browser Problem: fetching images, files, sound etc takes time. Don’t want to lock up screen while waiting, e.g. can’t scroll down screen or abort fetch. Solution: create separate thread for page fetch and start this on each new fetch.

11.2 Threads in Java Interface Runnable with method run() classes Thread, Write run() yourself To start a thread start() start() calls run() immediately To stop a thread interrupt() Try to avoid stop(), suspend(), resume()

11.3 Thread Safety/Management Problem: threads running methods on the same object may corrupt that object. E.g. internal bank transfer. acc[i] = acc[i]+x acc[i] = acc[i]+y acc[j] = acc[j]-x acc[j] = acc[j]-y Problem: keep the bank total constant!

Solution: synchronization on objects Aka Monitors Give each object a lock. Thread gets a lock by calling a synchronized object method. When one thread has the lock on an object no other thread may get the lock. Lock is on the object, not its methods Unsynchronized methods can still be called.

Lock a method with synchronized public synchronized void transfer (int from, int to) { acc[from] -= amount; acc[to] += amount; num_transactions++; } Looks fine, but what if an account mustn’t go negative (no credit facility)??

Problem: what happens if we get the lock and can’t proceed? Another thread which had the lock could allow us to proceed! Thread calls wait() method Gives up the lock temporarily, Enters queue of waiting threads on the object. notify() reawakens one thread in queue notifyAll() reawakens all threads in queue

public synchronized void transfer (int from, int to) { while ( acc[from] < amount ) { wait(); } // inactive wait! acc[to] += amount; num_transactions++; notifyAll(); } Try to avoid deadlocks, livelocks and races!!

11.4 Rules (for the WC!) 1.If 2 or more threads modify an object, declare them as synchronized. Read-only methods which are affected must also be synchronized. (Decency Rule 1) 2.If a thread must wait for a change, wait inside the object by entering a synchronized method and doing a wait. (Decency Rule 2)

3.Don’t spend a long time in a synchronized method. If you can’t complete, perform a wait(). (Fairness Rule 1) 4.Whenever a method changes the state of the object, execute a notifyAll(). (Fairness Rule 2) 5.wait() and notifyAll()/notify() are methods of the Object class, not the Thread class. make sure waits are matched by notifies on the same object. (Fairness Rule 3)

11.5 Real-Time Issues Real-time systems are not necessarily fast Programmer gives guarantees for execution time, etc Operating system must handle time, parallel activities, scheduling and priority of processes, as well as interrupts Program uses synchronization (semaphores), conditional execution (event variables) e.g. using monitors (ADT)

11.6 Timers Class Timer Constructor Timer(int delay, ActionListener l) void start() : starts the timer void stop(): stops the timer sending events actionPerformed() of l is called whenever a timer interval has elapsed.

11.7 Real-Time Example When we burn a CD the hardware must not pause but write continuously. The data buffer may therefore not become empty. In Windows or Unix there is no guarantee for this under heavy loading. In a real-time OS such loading is dealt with by lowered priorities (burn has highest).

12. Data Structures What kind of problem is to be solved? –Queue (FIFO) –Stack (LIFO) –Random Access (sorted or unsorted) Table with lookup using keys Set, 1 copy of each List many copies

12.1 Collections Collection Interfaces –JList –JTree –Vector, LinkedList –Set (1 copy of each object) –HashSet, TreeSet –Map (lookup key + value in a table) –AbstractMap, HashMap, TreeMap

12.2 Pattern Iterator For each data structure we need a method to traverse it, a so called iterator Example: Trees, breadth-first, depth-first Method will affect run-time performance, but end-user shouldn’t see this, only see iterator interface.

Iterator (Cont.) Data Structure Vector Start of traversal i = 0; Increment traversal i++; Get i-th element myVector.get(i); Finished traversal? i < myVector.size();

12.3 Trees Need a node called root A node can have several child nodes A childless node is called a leaf Example: DefaultMutableTreeNode parent.add(child); adds a child to a node See also DirTree.java in Lab ex. 4.

TreeModel model = … ; Jtree tree = new Jtree(model); Make a class that implements TreeModel interface. DefaultTreeModel already does this. TreeNode root = …; DefaultTreeModel model = new DefaultTreeModel(root); TreeNode is another interface.

DefaultMutableTreeNode already implements MutableTreeNode a subinterface of TreeNode. DefaultMutableTreeNode node = new DefaultMutableTreeNode(“Stockholm”); or node.setUserObject(“Göteborg”) Now to construct a tree!

DefaultMutableTreeNode root = new DefaultMutableTreeNode(“World”); DefaultMutableTreeNode country = new DefaultMutableTreeNode(“Sverige”); DefaultMutableTreeNode town = new DefaultMutableTreeNode(“Stockholm”); root.add(country); country.add(town); DefaultTreeModel model = new DefaultTreeModel(root); JTree tree = new JTree(model); Container contentPane = getContentPane(); contentPane.add(new JScrollPane(tree));

What about the iterators? enumeration e = root.breadthFirstEnumeration(); while (e.hasMoreElements()) { DefaultMutableTree node = (DefaultMutableTree)e.nextElement(); /* do something with node … e.g. */ if (node.getUserObject().equals(obj) ) return node; }

13. Java and Operating Systems Java is OS independent Class Runtime gives an interface to the OS Applets execute in a sandbox where a security manager controls access to file system, network connections, devices, etc. Applications can be given a security manager.

13.1 Execution of Java Class file is not binary and isn’t executed directly in hardware. Java byte code executes on a virtual java machine jvm … slow?? Applets execute in an appletviewer or a web-browser with a jvm Beans execute in a BeanBox

13.2 Execution of Java (Cont.) Can connect Java code to other code (C, C++, Fortran etc.) vis JNI java native interface 3 rd party suppliers have compilers to binary code. Increases speed but loses platform independence. Write-once, debug everywhere!! ?? (NM!)

14. BNF Grammars Standard format to define new context-free grammars, Backus-Naur-Form BNF. Example: Proposition ::= Subject Predicate Subject ::= “I” | “you” Predicate ::= “know” | “think” Gives strings I know, I think, you know, you think

14.1 BNF Example Statement ::= Proposition | Proposition Conjunction Statement Conjunction ::= “and” | “that” Gives I know that you think that I think and you know

14.2 Parse Trees I know that you think that I think subpred sub conj prop statement

14.3 Ambiguity This language is unambiguous. i.e. every string in the language has a unique parse tree. Tip: use recursive descent in lab ex. 4 and a method for each symbol in the grammar.

I know that you think that I think subpred sub conj prop statement prop/statement statement

14.4 Language Analysis Skaldic (old Icelandic) poetry – kennings man ::= “man” | “tree of the” battle | “thrower of the” sword | “giver of the” gold gold ::= “gold” | “fire of the” war war ::= “war” | “storm of the” spear spear ::= “spears” | “witch of the” shield shield ::= “shield” | “moon of the ship”

Giver of the fire of the storm of the witch of the moon of the ship Construct a parse tree for this kenning to understand its structure. Are kennings simply metaphors? Only a great poet was allowed to introduce a new kenning rule! Add some rules! M. I. Steblin-Kamenskii, Icelandic Culture, “As a rule, any kenning for a warrior was no richer in content than the pronoun “he” ”

14.5 XML Not related to UML!!! XML = eXtensible Markup Language An internet standard for data interchange, e.g. between databases. Defines a data interface. Originates from SGML and is related to HTML

14.6 XML Methodology Tagged data e.g. rose rose Data marked up with its identity e.g.

Helvetica 36 Karl Meinke 6337

Optional (recommended) header Optional document type declaration (DTD) Finally the root element … An element can contain child elements, text or both (but both makes a messy DTD!) Use attributes to modify data interpretation, and not to specify values

Parsing an XML document Document Object Model (DOM) parser reads an XML document into a tree structure Simple API for XML (SAX) pareser generates events as it reads an XML document. Sun provides its own DOM parser Be careful with whitespace around tags!

import javax.xml.parsers.*; import javax.swing.tree.*; … DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File f = … Document doc = builder.parse(f); /*tree structure of the document*/ Element root = doc.getDocumentElement(); NodeList children = root.getChildNodes(); Node firstchild = children.item(1);

14.7 DTD Usually an external file (small DTDs can be internal) Specifies the format of tagged data. An XML document is valid (wrt a DTD) if it satisfies the format of the DTD Can build XML validators – prevent data corruption, more efficient parse, etc. factory.setValidating(true);

e.g. A font element consists of a name element followed by a size element e.g. A kenning DTDs define regular expressions XML assumes grammar is unambiguous!!

RuleMeaning E*0 or more occurrences of E E+1 or more occurrences of E E?0 or 1 occurrences of E E 1 | … | E n E 1 or E 2 …. or E n E 1, …, E n E 1 followed by E 2 followed by … followed by E n #PCDATAText AnyAny children allowed EmptyNo children allowed

Can also specify attributes of elements Style attribute can be plain, bold or italic, but default is plain. Unit attribute of size is a character sequence and optional Now unit is not optional!

<!DOCTYPE Date [ <!ATTLIST Moon phase (new|between|full) “between”> ]>