Download Lecture 010, Concurrency in Java with Threads.

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Object-Oriented Software Engineering
Concurrent Programming
Contents
• Threads and Processes
• Race Conditions
• Deadlocks
• Extending Thread Class
• Overriding run ( )
• sleep ( )
• Using threads
• Interleaving
Threads vs. Processes
• A process is an independent flow of control
• There is no shared memory space among different processes
• Processes communicate between each other by specific
communication channels (not shared variables)
• e.g. Pipes in Unix, e.g.
ls | more
Threads vs. Processes
• A thread is a single flow of control within a program
• It performs one of the tasks that a program needs to perform
to achieve its goals
• If a program needs to perform several tasks, these could be
handled in different threads (and hence performed
concurrently)
• These threads will interact and cooperate through a shared
memory space
Threads vs. Processes
• Different threads can interact via shared variables and objects
• The execution of each thread may proceed independently of
the others
• In general, the relative ordering of execution of the different
threads is non-deterministic
• This can lead to safety and liveness problems
Race Conditions
A:Thread
Data:
B:Thread
A:Thread
Data:
B:Thread
set
get
get
set
a) We expect this to happen
b) Delay in A can cause wrong behavior
Deadlocks
Suppose we extend the File class to MyFile.
MyFile has copy method.
File
fle1.copy(fle2)
copies contents of fle1 to fle2.
MyFile
File copy(File file)
Deadlocks
fle1.copy(fle2)
1. obtains write lock for fle1
File
2. reads in contents of fle1
3. obtains write lock for fle2
4. writes contents to fle2
5. release all locks
Consider what could happen for separate
threads that execute:
Thread 1: fle1.copy(fle2)
Thread 2: fle2.copy(fle1)
MyFile
File copy(File file)
Deadlocks
object executing this code
fle1.copy(fle2) fle1: MyFile
get lock
read contents
get lock
write contents
release lock
release lock
fle2: MyFile
Deadlocks
Thread 1
fle1: MyFile
fle2: MyFile
get lock
read contents
Thread 2
get lock
read contents
get lock
get lock
Method calls will NOT return.
Both threads are waiting for the other to release
a lock before they can get the lock!
Two ways to have threads
Object
Thread
MyThread
void run( )
void interrupt( )
void join( )
String getName( )
boolean isAlive( )
........
<<interface>>
Runnable
MyThread
run( )
For all Thread methods see:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#method_summary
Extending Thread
public class SimpleThread extends Thread {
public static String destination = "";
public boolean notFinished = true;
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) { }
}
System.out.println("DONE! " + getName());
destination = getName(); //set CLASS field now finished
notFinished = false; //so this thread has finished
}
}
Complete code for this lecture available on web site for course
Overriding run( ) method
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) { }
}
sleep method causes
thread to suspend
while timer is running
must catch exception if
sleep is interrupted
System.out.println("DONE! " + getName());
destination = getName(); //set CLASS field now finished
notFinished = false; //so this thread has finished
}
For a thread to do anything interesting while being
executed must override the run( ) method.
sleep method
Thread can not be executed
for this amount of time
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) { }
}
System.out.println("DONE! " + getName());
destination = getName(); //set CLASS field now finished
notFinished = false; //so this thread has finished
Once sleep is over
}
this thread will take
turns at being executed
as before
sleep method
• sleep ( ) can be used to give threads
better chance of having fair share of
execution
• sleep ( ) can be used to delay thread
while it waits for resources to become
available
Using Threads
public class TwoThreadsDemo {
public static void main (String[ ] args) {
SimpleThread Jam = new SimpleThread("Jamaica");
SimpleThread Fij = new SimpleThread("Fiji");
Jam.start();
Fij.start();
Note start methods
are pre-defined
while ((Jam.notFinished) | (Fij.notFinished)) {
// do nothing big waste of time
}
JOptionPane.showMessageDialog(null,
Fij.destination,
"The winner is ",
JOptionPane.PLAIN_MESSAGE);
}
}
Interleaving threads
As the Java run time environment executes the TwoThreadsDemo
java application it starts each thread in turn.
Jam.start();
Fij.start();
This causes Java to execute the run methods for Jam and Fij.
Java sequentially executes the code in the run methods.
At each point in the execution Java randomly chooses
which thread to pick next.
After Java executes a single expression from one thread,
it then randomly chooses either:
1. to execute the next expression for Jam
2. or execute the next expression for Fij
At the same time the execution of TwoThreadsDemo continues
independently from the threads.
Threads, random interleaving
Java
TwoThreadsDemo
Jam thread
Fij thread
expression:2
expression:4
expression:1
expression:5
expression:6
expression:3
expression:8
expression:7
expression:9
Interleaving Fairness
• Java chooses randomly between threads
• Does not have to be fair
• That is one thread may be executed more often than
another
• Java will always execute the expressions in a thread
eventually
Warning about expressions
expression:1
expression:2
for (int i = 0; i < 10; i++) {
// and so on
}
expression:3
• Each of these expressions may be interleaved between
those from other threads during execution.
• Don't assume that a single line of code is a single expression
that will be executed all in one go!
Expression interleaving
Fij: i < 10
Jam: int i = 0
Fij: // and so on
Fij: i++
Jam: i < 10
Fij: i < 10
Traces from interleaving threads
Thread_1
Thread_2
public void run( ) {
a;
b;
c;
}
public void run( ) {
x;
y;
z;
}
All possible traces from Thread 1 and Thread 2
Thread_1.start();
Thread_2.start();
0
x
4
y
8
z
12
a
13
Paths from top
to bottom give all
traces from interleaving.
20 in total
5
y
9
14
b
b
10
15
11
c
x
c
y
c
z
c
2
x
6
y
b
z
b
1
x
a
a
z
a
7
3