CP — Concurrent Programming 2. Java and Concurrency Prof. O. Nierstrasz Wintersemester 2005 / 2006.

Slides:



Advertisements
Similar presentations
Concurrent Programming Abstraction & Java Threads
Advertisements

12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Sources  Cay Horstmann, Computing.
CSC321 §6 Modelling Processes using FSP 1 Section 6 Modelling Processes using FSP.
ESE Einführung in Software Engineering 7. Modeling Behaviour Prof. O. Nierstrasz.
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
CP — Concurrent Programming 5. Safety and Liveness Properties Prof. O. Nierstrasz Wintersemester 2005 / 2006.
CP — Concurrent Programming 8. Liveness and Asynchrony Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
2. Java and Concurrency Prof. O. Nierstrasz Selected material © Magee and Kramer.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
10. Petri Nets Prof. O. Nierstrasz. Roadmap  Definition: —places, transitions, inputs, outputs —firing enabled transitions  Modelling: —concurrency.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Overview  Common errors … —Typical.
ESE Einführung in Software Engineering N. XXX Prof. O. Nierstrasz Fall Semester 2009.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
Object-Oriented Software Engineering Concurrent Programming.
13. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Summary, Trends, Research...  Summary: functional, logic and object-oriented.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
CP — Concurrent Programming 12. Petri Nets Prof. O. Nierstrasz Wintersemester 2005 / 2006.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Metamodeling Seminar X. CHAPTER Prof. O. Nierstrasz Spring Semester 2008.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
N. XXX Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.
12. Common Errors, a few Puzzles. © O. Nierstrasz P2 — Common Errors, a few Puzzles 12.2 Common Errors, a few Puzzles Sources  Cay Horstmann, Computing.
Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.
CP — Concurrent Programming 3. Safety and Synchronization Prof. O. Nierstrasz Wintersemester 2005 / 2006.
7. Liveness and Asynchrony Prof. O. Nierstrasz. Roadmap  Asynchronous invocations  Simple Relays —Direct invocations —Thread-based messages —Command-based.
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.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OORPT Object-Oriented Reengineering Patterns and Techniques X. CHAPTER Prof. O. Nierstrasz.
CP — Concurrent Programming X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
12. eToys. © O. Nierstrasz PS — eToys 12.2 Denotational Semantics Overview:  … References:  …
Lecture 4 : JAVA Thread Programming
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Concurrency: processes & threads1 ©Magee/Kramer Chapter 2 Processes & 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.
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
111 © 2002, Cisco Systems, Inc. All rights reserved.
2015 Concurrency: processes & threads 1 ©Magee/Kramer 2 nd Edition Chapter 2 Processes & Threads.
CSC321 §6 Modelling Processes using FSP 1 Chapter 6 Modelling Processes using FSP.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
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
Java Thread and Memory Model
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Multi-Threading in Java
CP — Concurrent Programming 6. Liveness and Guarded Methods Prof. O. Nierstrasz Wintersemester 2005 / 2006.
Multithreading and Garbage Collection Session 16.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
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.
Concurrency: processes & threads1 ©Magee/Kramer 2 nd Edition Chapter 2 Processes & Threads.
Multithreading / Concurrency
Chapter 13: Multithreading
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
Multithreaded Programming
Chapter 15 Multithreading
Threads and Multithreading
Representation and Management of Data on the Internet
Gentle Introduction to Threads
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CP — Concurrent Programming 2. Java and Concurrency Prof. O. Nierstrasz Wintersemester 2005 / 2006

© Oscar Nierstrasz CP — Java and Concurrency CP 2.2 Java and Concurrency Overview  Modelling Concurrency —Finite State Processes —Labelled Transition Systems  Java —Thread creation —Thread lifecycle —Synchronization Selected material © Magee and Kramer

© Oscar Nierstrasz CP — Java and Concurrency CP 2.3 Modelling Concurrency Because concurrent systems are non-deterministic, it can be difficult to build them and reason about their properties. A model is an abstraction of the real world that makes it easier to focus on the points of interest. Approach: Model concurrent systems as sets of sequential finite state processes

© Oscar Nierstrasz CP — Java and Concurrency CP 2.4 Finite State Processes FSP is a textual notation for specifying a finite state process: LTS is a graphical notation for interpreting a processes as a labelled transition system: The meaning of a process is a set of possible traces : on  off  on  off  on  off  on  off  on... SWITCH = (on -> off-> SWITCH). 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.5 FSP Summary Action prefix (x->P)Parallel composition (P||Q) Choice(x->P|y->Q)Replicatorforall [I:1..N] P(I) Guarded Action (when B x->P|y->Q)Process labellinga:P Alphabet extension P + SProcess sharing{a 1,...,a n }::P ConditionalIf B then P else QPriority High||C=(P||Q)<<{a 1,…,a n } Relabelling/{new 1 /old 1,…}Priority Low||C=(P||Q)>>{a 1,…,a n } Hiding\{a 1,…,a n }Safety propertyproperty P 1,…,a n }Progress propertyprogress P = {a 1,…,a n } We will encounter and use these features in the lectures to come …

© Oscar Nierstrasz CP — Java and Concurrency CP 2.6 FSP — Action Prefix If x is an action and P a process then (x-> P) is a process that initially engages in the action x and then behaves like P. Convention: Processes start with UPPERCASE, actions start with lowercase. A terminating process ONESHOT = (once -> STOP). 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.7 FSP — Recursion Repetitive behaviour uses recursion: SWITCH= OFF, OFF= (on -> ON), ON= (off-> OFF). SWITCH= OFF, OFF= (on -> ON), ON= (off-> OFF).

© Oscar Nierstrasz CP — Java and Concurrency CP 2.8 FSP — Choice If x and y are actions then (x->P | y->Q) is a process which initially engages in either of the actions x or y. If x occurs, the process then behaves like P; otherwise, if y occurs, it behaves like Q. What are the possible traces of DRINKS? DRINKS =( red -> coffee-> DRINKS | blue-> tea-> DRINKS ). DRINKS =( red -> coffee-> DRINKS | blue-> tea-> DRINKS ). 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.9 FSP — Non-determinism (x->P | x->Q) performs x and then behaves as either P or Q. COIN =( toss-> heads-> COIN | toss-> tails-> COIN ). COIN =( toss-> heads-> COIN | toss-> tails-> COIN ). 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.10 FSP — Guarded actions (when B x->P | y->Q) means that when the guard B is true then either x or y may be chosen; otherwise if B is false then only y may be chosen. COUNT (N=3)= COUNT[0], COUNT[i:0..N]=( when(i COUNT[i+1] | when(i>0) dec->COUNT[i-1] ). COUNT (N=3)= COUNT[0], COUNT[i:0..N]=( when(i COUNT[i+1] | when(i>0) dec->COUNT[i-1] ). 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.11 Java  Concurrency model based on monitors —synchronized keyword —wait() and notify() methods —Thread class and Runnable interface  java.util.concurrency package (Java 1.5) —Implements many common concurrency idioms

© Oscar Nierstrasz CP — Java and Concurrency CP 2.12 Threads A Java Thread has a run method defining its behaviour: class SimpleThread extends Thread { public static void main (String[] args) { … } public SimpleThread(String str) { super(str); // Call Thread constructor } public void run() {// What the thread does for (int i=0; i<5; i++) { System.out.println(i + " " + getName()); try { sleep((int)(Math.random()*1000)); } catch (InterruptedException e) { } } System.out.println("DONE! " + getName()); } class SimpleThread extends Thread { public static void main (String[] args) { … } public SimpleThread(String str) { super(str); // Call Thread constructor } public void run() {// What the thread does for (int i=0; i<5; i++) { System.out.println(i + " " + getName()); try { sleep((int)(Math.random()*1000)); } catch (InterruptedException e) { } } System.out.println("DONE! " + getName()); }

© Oscar Nierstrasz CP — Java and Concurrency CP 2.13 SimpleThread FSP SimpleThread can be modelled as a single, sequential, finite state process: Or, more generically: const N=5 Simple= Print[1], Print[n:1..N]=( when(n Print[n+1] | when(n==N) done -> STOP). const N=5 Simple= Print[1], Print[n:1..N]=( when(n Print[n+1] | when(n==N) done -> STOP). Simple = ([1]->[2]->[3]->[4]-> done-> STOP). 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.14 Multiple Threads... A Thread’s run method is never called directly but is executed when the Thread is started: class SimpleThread { public static void main (String[] args) { // Instantiate a Thread, then start it: new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } … } class SimpleThread { public static void main (String[] args) { // Instantiate a Thread, then start it: new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } … }

© Oscar Nierstrasz CP — Java and Concurrency CP 2.15 Running the TwoThreadsDemo In this implementation of Java, the execution of the two threads is interleaved. This is not guaranteed for all implementations! 0 Jamaica 0 Fiji 1 Jamaica 1 Fiji 2 Fiji 3 Fiji 2 Jamaica 4 Fiji 3 Jamaica DONE! Fiji 4 Jamaica DONE! Jamaica 0 Jamaica 0 Fiji 1 Jamaica 1 Fiji 2 Fiji 3 Fiji 2 Jamaica 4 Fiji 3 Jamaica DONE! Fiji 4 Jamaica DONE! Jamaica Why are the output lines never garbled? 0 Ja0 Fimajiica... Why are the output lines never garbled? 0 Ja0 Fimajiica...

© Oscar Nierstrasz CP — Java and Concurrency CP 2.16 FSP — Concurrency We can relabel the transitions of Simple and concurrently compose two copies of it: What are all the possible traces? ||TwoThreadsDemo =(fiji:Simple ||jamaica:Simple ). ||TwoThreadsDemo =(fiji:Simple ||jamaica:Simple ).

© Oscar Nierstrasz CP — Java and Concurrency CP 2.17 FSP — Composition If we restrict ourselves to two steps, the composition will have nine states: 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.18 Composition state space fiji[1] fiji.done jamaica.done jamaica.[1] The state space of two composed processes is (at most) the Cartesian product of the individual state spaces

© Oscar Nierstrasz CP — Java and Concurrency CP 2.19 java.lang.Thread (creation) A Java thread can either inherit from java.lang.Thread, or contain a Runnable object: public class java.lang.Thread extends java.lang.Object implements java.lang.Runnable { public Thread(); public Thread(Runnable target); public Thread(Runnable target, String name); public Thread(String name);... public class java.lang.Thread extends java.lang.Object implements java.lang.Runnable { public Thread(); public Thread(Runnable target); public Thread(Runnable target, String name); public Thread(String name);...

© Oscar Nierstrasz CP — Java and Concurrency CP 2.20 java.lang.Thread (methods) A thread must be created, and then started:... public void run(); public synchronized void start(); public static void sleep(long millis) throws InterruptedException; public static void yield(); public final String getName();... }... public void run(); public synchronized void start(); public static void sleep(long millis) throws InterruptedException; public static void yield(); public final String getName();... } NB: suspend(), resume() and stop() are now deprecated!

© Oscar Nierstrasz CP — Java and Concurrency CP 2.21 java.lang.Runnable Since Java does not support multiple inheritance, it is impossible to inherit from both Thread and another class. Instead, simply define: and instantiate: class MyStuff extends UsefulStuff implements Runnable... class MyStuff extends UsefulStuff implements Runnable... new Thread(new MyStuff).start(); public interface java.lang.Runnable { public abstract void run(); } public interface java.lang.Runnable { public abstract void run(); }

© Oscar Nierstrasz CP — Java and Concurrency CP 2.22 Transitions between Thread States

© Oscar Nierstrasz CP — Java and Concurrency CP 2.23 LTS for Threads Thread = ( start -> Runnable ), Runnable = ( yield -> Runnable | {sleep, wait, blockio} -> NotRunnable | stop -> STOP ), NotRunnable = ( {awake, notify, unblockio} -> Runnable ). Thread = ( start -> Runnable ), Runnable = ( yield -> Runnable | {sleep, wait, blockio} -> NotRunnable | stop -> STOP ), NotRunnable = ( {awake, notify, unblockio} -> Runnable ). 01

© Oscar Nierstrasz CP — Java and Concurrency CP 2.24 Creating Threads This Clock application uses a thread to update the time: public class Clock extends Canvas implements Runnable { private Thread clockThread = null; public Clock() { super(); if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } } … public class Clock extends Canvas implements Runnable { private Thread clockThread = null; public Clock() { super(); if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } } …

© Oscar Nierstrasz CP — Java and Concurrency CP 2.25 Creating Threads public void run() { // stops when clockThread is set to null while(Thread.currentThread()==clockThread) { repaint(); try {clockThread.sleep(1000); } catch (InterruptedException e){ } }... public void run() { // stops when clockThread is set to null while(Thread.currentThread()==clockThread) { repaint(); try {clockThread.sleep(1000); } catch (InterruptedException e){ } }...

© Oscar Nierstrasz CP — Java and Concurrency CP And stopping them... public void paint(Graphics g) { g.setFont(myFont()); Calendar now = Calendar.getInstance(); g.drawString(twoDigit(now.get(Calendar.HOUR_OF_DAY)) + ":" + twoDigit(now.get(Calendar.MINUTE)) + ":" + twoDigit(now.get(Calendar.SECOND)), 0, getSize().height-MARGIN); } // When the Frame closes, stop its thread public void stopThread() { clockThread = null; } …... public void paint(Graphics g) { g.setFont(myFont()); Calendar now = Calendar.getInstance(); g.drawString(twoDigit(now.get(Calendar.HOUR_OF_DAY)) + ":" + twoDigit(now.get(Calendar.MINUTE)) + ":" + twoDigit(now.get(Calendar.SECOND)), 0, getSize().height-MARGIN); } // When the Frame closes, stop its thread public void stopThread() { clockThread = null; } …

© Oscar Nierstrasz CP — Java and Concurrency CP 2.27 Synchronization Without synchronization, an arbitrary number of threads may run at any time within the methods of an object. —Class invariant may not hold when a method starts! —So can’t guarantee any post-condition! A solution: consider a method to be a critical section which locks access to the object while it is running. This works as long as methods cooperate in locking and unlocking access!

© Oscar Nierstrasz CP — Java and Concurrency CP 2.28 Synchronized methods Either: declare an entire method to be synchronized with other synchronized methods of an object: public class PrintStream extends FilterOutputStream {... public synchronized void println(String s); public synchronized void println(char c);... } public class PrintStream extends FilterOutputStream {... public synchronized void println(String s); public synchronized void println(char c);... }

© Oscar Nierstrasz CP — Java and Concurrency CP 2.29 Synchronized blocks Or: synchronize an individual block within a method with respect to some object: public Object aMethod() { // unsynchronized code... synchronized(resource) { // lock resource... } // unlock resource... } public Object aMethod() { // unsynchronized code... synchronized(resource) { // lock resource... } // unlock resource... }

© Oscar Nierstrasz CP — Java and Concurrency CP 2.30 wait and notify Synchronization must sometimes be interrupted: public class Account { int assets = 0; public synchronized void withdraw(int amount) { while (amount > assets) { try { wait(); } catch(InterruptedException e) { } } assets -= amount; } public synchronized void deposit(int amount) { assets += amount; notifyAll(); } public class Account { int assets = 0; public synchronized void withdraw(int amount) { while (amount > assets) { try { wait(); } catch(InterruptedException e) { } } assets -= amount; } public synchronized void deposit(int amount) { assets += amount; notifyAll(); } NB: you must either catch or throw InterruptedException

© Oscar Nierstrasz CP — Java and Concurrency CP 2.31 wait and notify in action … final Account myAccount = new Account(); new Thread() { public void run() { int amount = 100; System.out.println("Waiting to withdraw " + amount + " units..."); myAccount.withdraw(amount); System.out.println("I withdrew " + amount + " units!"); } }.start(); try { Thread.sleep(1000); } catch (InterruptedException e){ } new Thread() { public void run() { int amount = 200; System.out.println("Depositing " + amount + " units..."); myAccount.deposit(amount); System.out.println("I deposited " + amount + " units!"); } }.start(); final Account myAccount = new Account(); new Thread() { public void run() { int amount = 100; System.out.println("Waiting to withdraw " + amount + " units..."); myAccount.withdraw(amount); System.out.println("I withdrew " + amount + " units!"); } }.start(); try { Thread.sleep(1000); } catch (InterruptedException e){ } new Thread() { public void run() { int amount = 200; System.out.println("Depositing " + amount + " units..."); myAccount.deposit(amount); System.out.println("I deposited " + amount + " units!"); } }.start(); Waiting to withdraw 100 units... Depositing 200 units... I deposited 200 units! I withdrew 100 units! Waiting to withdraw 100 units... Depositing 200 units... I deposited 200 units! I withdrew 100 units!

© Oscar Nierstrasz CP — Java and Concurrency CP 2.32 java.lang.Object NB: wait() and notify() are methods rather than keywords: public class java.lang.Object {... public final void wait() throws InterruptedException; public final void notify(); public final void notifyAll();... } public class java.lang.Object {... public final void wait() throws InterruptedException; public final void notify(); public final void notifyAll();... }

© Oscar Nierstrasz CP — Java and Concurrency CP 2.33 What you should know!  What are finite state processes?  How are they used to model concurrency?  What are traces, and what do they model?  How can the same FSP have multiple traces?  How do you create a new thread in Java?  What states can a Java thread be in?  How can it change state?  What is the Runnable interface good for?  What is a critical section?  When should you declare a method to be synchronized?

© Oscar Nierstrasz CP — Java and Concurrency CP 2.34 Can you answer these questions?  How would you specify an FSP that repeatedly performs hello, but may stop at any time?  How many states and how many possible traces does the full TwoThreadsDemo FSP have?  When should you inherit from Thread?  How can concurrency invalidate a class invariant?  What happens if you call wait or notify outside a synchronized method or block?  When is it better to use synchronized blocks rather than methods?  How would you model synchronization in FSP?

© Oscar Nierstrasz CP — Java and Concurrency CP 2.35 License > Attribution-ShareAlike 2.5 You are free: to copy, distribute, display, and perform the work to make derivative works to make commercial use of the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. Attribution-ShareAlike 2.5 You are free: to copy, distribute, display, and perform the work to make derivative works to make commercial use of the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. For any reuse or distribution, you must make clear to others the license terms of this work. Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above.