David Evans http://www.cs.virginia.edu/ ~evans CS201j: Engineering Software University of Virginia Computer Science Lecture 13: Concurring Concurrentl y
Jan 15, 2016
David Evanshttp://www.cs.virginia.edu/~evans
CS201j: Engineering SoftwareUniversity of VirginiaComputer Science
Lecture 13: Concurring Concurrently
17 October 2002 CS 201J Fall 2002 2
Menu
• Subtyping Rules Review– Overriding and Overloading
• Concurrency
17 October 2002 CS 201J Fall 2002 3
Substitution Principle… (in client code)MysteryType1 mt1;MysteryType2 mt2;MysteryType3 mt3;… (anything could be here)mt1 = mt2.m (mt3);
If the Java compiler is happy with this code, which of these are guaranteedto be true:a. The apparent type of mt2 is MysteryType2b. At the last statement, the actual type of mt2 is MysteryType2c. MysteryType2 has a method named md. The MysteryType2.m method takes a parameter of type MysteryType3e. The MysteryType2.m method returns a subtype of MysteryType1f. After the last statement, the actual type of mt1 is MysteryType1
17 October 2002 CS 201J Fall 2002 4
… (in client code)MysteryType1 mt1;MysteryType2 mt2;MysteryType3 mt3;… (anything could be here)mt1 = mt2.m (mt3);
If the Java compiler is happy with this code, which of these are guaranteedto be true:a. The apparent type of mt2 is MysteryType2
b. At the last statement, the actual type of mt2 is MysteryType2
c. MysteryType2 has a method named m
d. The MysteryType2.m method takes a parameter of type MysteryType3
e. The MysteryType2.m method returns a subtype of MysteryType1
f. After the last statement, the actual type of mt1 is MysteryType1
TRUE: the apparent type is obvious from the declaration.
FALSE: we only know the actual type <= MysteryType2
TRUE
FALSE: we only know it takes a parameter >= MysteryType3
TRUE: the assignment type checking depends on this
FALSE: we only know that the actual type <= MysteryType1
17 October 2002 CS 201J Fall 2002 5
Subtyping Rules
class A { public RA m (PA p) ;}
… (in client code)MysteryType1 mt1;MysteryType2 mt2;MysteryType3 mt3;…mt1 = mt2.m (mt3);
RA must be a subtype of MysteryType1:
RA <= MysteryType1MysteryType3 must be a subtype of PA:
PA >= MysteryType3
If A is MysteryType2, what do we know about RA and PA?
17 October 2002 CS 201J Fall 2002 6
Subtyping Rulesclass A { public RA m (PA p) ;}class B extends A { public RB m (PB a);}
… (in client code)MysteryType1 mt1;MysteryType2 mt2;MysteryType3 mt3;…mt1 = mt2.m (mt3);
RB must be a subtype of RA: RB <= RAPA must be a subtype of PB: PB >= PA
If B <= A, what do we know about RB and PB?
17 October 2002 CS 201J Fall 2002 7
Substitution Principleclass A { public RA m (PA p) ;}class B extends A { public RB m (PB a);}
… (in client code)MysteryType1 mt1;MysteryType2 mt2;MysteryType3 mt3;…mt1 = mt2.m (mt3);
Substitution Principle:Parameters PB >= PAPreconditions pre_A pre_B
Result RB <= RAPostconditions post_B post_A
17 October 2002 CS 201J Fall 2002 8
Substitution Principle / Eiffelclass A { public RA m (PA p) ;}class B extends A { public RB m (PB a);}
… (in client code)MysteryType1 mt1;MysteryType2 mt2;MysteryType3 mt3;…mt1 = mt2.m (mt3);
Substitution Principle EiffelParameters PB >= PA PB <= PAPreconditions pre_A pre_B pre_B pre_A
Result RB <= RA RB <= RAPostconditions post_B post_A post_B post_A
17 October 2002 CS 201J Fall 2002 9
Overloading and Overriding
• Overriding: replacing a supertype’s method in a subtype – Dynamic dispatch finds method of actual type
• Overloading: providing two methods with the same name but different parameter types– Statically select most specific matching
method of apparent type
17 October 2002 CS 201J Fall 2002 10
Overloading Examplepublic class Overloaded extends Object { public int tryMe (Object o) { return 17; }
public int tryMe (String s) { return 23; }
public boolean equals (String s) { return true; }}
public boolean equals (Object) is inherited from Object
17 October 2002 CS 201J Fall 2002 11
Overloading public class Overloaded { public int tryMe (Object o) { return 17; } public int tryMe (String s) { return 23; } public boolean equals (String s) { return true; }}
static public void main (String args[]) { Overloaded over = new Overloaded (); System.err.println (over.tryMe (over)); System.err.println (over.tryMe (new String ("test")));
Object obj = new String ("test"); System.err.println (over.tryMe (obj)); System.err.println (over.equals (new String ("test"))); System.err.println (over.equals (obj));
Object obj2 = over; System.err.println (obj2.equals (new String ("test"))); }
172317truefalsefalse
17 October 2002 CS 201J Fall 2002 12
Overkill
• Overloading and overriding together can be overwhelming!
• Avoid overloading whenever possible: names are cheap and plentiful
• One place you can’t easily avoid it: constructors (they all have to have the same name)
17 October 2002 CS 201J Fall 2002 13
My Favorite C++ Program#include<stdio.h>
class A { public: void other () { printf("is an empty func in A\n"); }; virtual void other (class A *a) { printf("In A\n"); }};class B: public A { public: void other (class B *b) { printf("In B\n"); } };class C: public A { public: void other (class C *c) { printf("In C\n"); } };void main(void) { A a; B b; C c; A *aPtr = &a; B *bPtr = &b; C *cPtr = &c; aPtr = bPtr; aPtr->other(bPtr); bPtr->other(); }
(On notes, for experts only)
17 October 2002 CS 201J Fall 2002 14
Concurrency
17 October 2002 CS 201J Fall 2002 15
Our computer can only do one instruction at a time, why would we want to program pretending it can do many things at once?
17 October 2002 CS 201J Fall 2002 16
Concurrent Programming
• Some problems are clearer to program concurrently:– Modularity
• Don’t have to explicitly interleave code for different abstractions (especially: user interfaces)
• High-level interactions – synchronization, communication
– Modeling• Closer map to real world problems: things in the
real world aren’t sequential
17 October 2002 CS 201J Fall 2002 17
Concurrency in Javapublic class Thread implements Runnable { // OVERVIEW: A thread is a thread of execution in a program. // The Java Virtual Machine allows an application to have // multiple threads of execution running concurrently.
public Thread (Runnable target) // Creates a new Thread object that will run the target.
public void start () // Starts a new thread of execution.
… many other methods}
17 October 2002 CS 201J Fall 2002 18
Making a Thread
// from PS5 Grid class:public void startObjects() // EFFECTS: Start all object threads. { Enumeration els = simobjects.elements ();
while (els.hasMoreElements ()) { SimObject current = (SimObject) els.nextElement (); Thread simObjectThread = new Thread (current); simObjectThread.start (); } }
public class Thread implements Runnable { public Thread (Runnable target) public void start () … many other methods}
What do you know about SimObject type?
17 October 2002 CS 201J Fall 2002 19
Runnable
public interface Runnable { public void run()
When an object implementing interface Runnable isused to create a thread, starting the thread causes
theobject's run method to be called in that separatelyexecuting thread. The general contract of the method run is that it may take any actionwhatsoever.
}So, to be a subtype of Runnable, SimObject must have a method void run () with no preconditions and any postconditions it wants.
17 October 2002 CS 201J Fall 2002 20
Making a Runnableabstract public class SimObject implements Runnable { … public void run () // EFFECTS: Executes one turn by calling the // executeTurn method, and sleeps for a time // and repeats. { while (true) { executeTurn (); delay (TURN_DELAY + random.nextInt(TURN_RANDOM)); } }
17 October 2002 CS 201J Fall 2002 21
Actually…abstract public class SimObject implements Runnable { … public void run () // REQUIRES: this has been initialized //@also_requires isInitialized // EFFECTS: Executes one turn by calling the // executeTurn method, and sleeps for a time // and repeats. {
… }
We are violating the substitution principle!SimObject.run() has a stronger preconditionthan Runnable.run().
17 October 2002 CS 201J Fall 2002 22
Concurrency
• Making a concurrent Java program is easy:
Make a subtype R of Runnable
new Thread (new R ()).start ()
• Making a concurrent Java program that behaves correctly is really, really hard!
17 October 2002 CS 201J Fall 2002 23
Scheduling Meetings
• Alice wants to schedule a meeting with Bob and Colleen
Bob Alice Colleen“When can you meet Friday?”
“When can you meet Friday?”
“11am or 3pm”“9am or 11am”
“Let’s meet at 11am”
“Let’s meet at 11am”
Reserves 11amfor meeting
Reserves 11amfor meeting
Picks meeting time
17 October 2002 CS 201J Fall 2002 24
Partial Ordering of Events• Sequential programs give use a total
ordering of events: everything happens in a determined order
• Concurrency gives us a partial ordering of events: we know some things happen before other things, but not total order
Alice asks to schedule meeting before Bob repliesAlice asks to schedule meeting before Colleen repliesBob and Colleen both reply before Alice picks meeting timeAlice picks meeting time before Bob reserves time on calendar
17 October 2002 CS 201J Fall 2002 25
Race Condition
Bob Alice Colleen“When can you meet Friday?”
“When can you meet Friday?”
“9, 11am or 3pm”“9am or 11am”
“Let’s meet at 11am”
“Let’s meet at 11am”
Picks meeting time
Doug
“When can you meet Friday?”
“9, 11am or 3pm”
“Let’s meet at 11am”
Reserves 11amfor Doug
“I’m busy then…”
17 October 2002 CS 201J Fall 2002 26
Preventing Race Conditions
• Use locks to impose ordering constraints
• After responding to Alice, Bob reserves all the times in his response until he hears back (and then frees the other times)
17 October 2002 CS 201J Fall 2002 27
LockingBob Alice Colleen“When can
you meet Friday?”
“When can you meet Friday?”
“9, 11am or 3pm”“9am or 11am”
“Let’s meet at 11am”
“Let’s meet at 11am”
Picks meeting time
Doug
“When can you meet Friday?”
“3pm”
“Let’s meet at 3”
Locks calendar
17 October 2002 CS 201J Fall 2002 28
DeadlocksBob Alice Colleen
“When can you meet Friday?”
“When can you meet Friday?”
“9, 11am or 3pm”
Doug“When can you meet Friday?”
Locks calendarfor Alice, can’t respond to Doug
“When can you meet Friday?”
Locks calendarfor Doug, can’t respond to Alice
Can’t schedulemeeting, noresponse fromBob
Can’t schedulemeeting, noresponse fromColleen
17 October 2002 CS 201J Fall 2002 29
Why are threads hard?• Too few ordering constraints: race conditions• Too many ordering constraints: deadlocks• Hard/impossible to reason modularly
– If an object is accessible to multiple threads, need to think about what any of those threads could do at any time!
• Testing is even more impossible than it is for sequential code– Even if you test all the inputs, don’t know it will work if
threads run in different order
17 October 2002 CS 201J Fall 2002 30
Charge• Computers are single-threaded machines
that provide their owner the illusion of multiple threads.
• Brains are multi-threaded machines that provide their owner with the illusion of a single thread.
• Practice with races/deadlocks on Tuesday, no class on Thursday
• Return exams