Java Concurrency
Java Concurrency
Java Concurrency
So#wareArchitecture
BertrandMeyer,MichelaPedroni
ETHZurich,FebruaryMay2010
Lecture 14: Designing for concurrency
(Material prepared by Sebastian Nanz)
Concurrent Processes
Multiprocessing
Until a few years ago: systems with one processing unit
werestandard
Today: most end-user systems have multiple processing
units in the form of multi-core processors
Process 1
CPU 1
Process 2
CPU 2
Instructions
Process 2
CPU
Instructions
Processes
A (sequential) program is a set of instructions
A process is an instance of a program that is being
executed
Concurrency
Both multiprocessing and multithreading are examples of
concurrent computation
The execution of processes or threads is said to be
concurrent if it is either parallel or interleaved
Vomputation
To perform a computation is
To apply certain actions
To certain objects
Using certain processors
Actions
Objects
Processor
10
Global data
Program
counter
Register
values
Heap
Stack
The scheduler
A system program called the scheduler controls which
processes are running; it sets the process states:
Running: instructions are being executed.
Blocked: currently waiting for an event.
Ready: ready to be executed, but has not been
assigned a processor yet.
blocked
running
ready
Context switch
P1
Context
Registers
P2
CPU
Sequential execution:
CPU 2
CPU 1
CPU 2
task 1
n
m+n
task 2
CPU 1
task 2
task 1
Concurrent execution:
max(m, n)
Processes vs threads
Process:
Has its own (virtual) memory space (in O-O programming, its
own objects)
Sharing of data (objects) with another process:
Is explicit (good for reliability, security, readability)
Is heavy (bad for ease of programming)
Switching to another process: expensive (needs to back up
one full context and restore another
Thread:
Shares memory with other threads
Sharing of data is straightforward
Simple go program (good)
Risks of confusion and errors: data races (bad)
Switching to another thread: cheap
16
Concurrent Programming:
The Java Threads approach
void compute() {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
Joining threads
Often the final results of thread executions need to be
combined:
return t1.getResult() + t2.getResult();
Java Threads
Mutual exclusion
x.setValue(0);
x.increment();
int i = x.getValue();
Thread 2:
x.setValue(2);
x.setValue(0)
x.setValue(2)
x.increment()
int i = x.getValue()
x.setValue(0)
x.increment()
x.setValue(2)
int i = x.getValue()
x.setValue(0)
x.increment()
int i = x.getValue()
x.setValue(2)
i == 1
x.value == ?
i == 3
x.value == ?
i == 2
x.value == ?
i == 1
x.value == ?
x.setValue(0)
x.setValue(2)
x.increment()
int i = x.getValue()
x.setValue(0)
x.increment()
x.setValue(2)
int i = x.getValue()
x.setValue(0)
x.increment()
int i = x.getValue()
x.setValue(2)
i == 1
x.value == 1
i == 3
x.value == 3
i == 2
x.value == 2
i == 1
x.value == 2
Synchronization
To avoid data races, threads (or processes) must
synchronize with each other, i.e. communicate to agree on
the appropriate sequence of actions
How to communicate:
By reading and writing to shared sections of memory
(shared memory synchronization)
In the example, threads should agree that at any one
time at most one of them can access the resource
explicit exchange of information (message passing
synchronization)
By
Mutual exclusion
Mutual exclusion (or mutex) is a form of synchronization
that avoids the simultaneous use of a shared resource
type m(args) {
synchronized (this) {
// body
}
}
synchronized (lock) {
x.setValue(2);
}
27
Java Threads
Condition synchronization
Condition synchronization
The producer-consumer problem requires that processes
access the buffer properly:
Consumers must wait if the buffer is empty
Producers must wait if the buffer is full
32
33
JavaThreads
Deadlocks
}}
36
Dining philosophers
37
Liveness:
38
2
6 years
Apache
Mozilla
OpenOffice
Server
Client
GUI
Mainly C
C++
C++
0.3
7 years
10 years 8 years
40
MySQL
Apache
Mozilla
OpenOffice
Total
Non-deadlock
14
13
41
74
Deadlock
16
31
Pattern
Thread 1 Thread 2
Order violation
Thread 1 Thread 2
The desired order between
X
two (sets of) accesses is flipped
Others
Implications
50
We should focus on
40
OpenOffice
30
atomicity violation
and order violation
Mozilla
Apache
20
MySQL
10
0
AtomicityOrder Other
*There are 3-bug overlap between Atomicity and Order
OK
Woops!
two threads
Concurrent Programming:
The SCOOP approach
Concurrent programming:
Used to be messy
Used to be messy
Still messy
Example: threading models in
most popular approaches
Development level: sixties/
seventies
Only understandable through
operational reasoning
48
SCOOP mechanism
Simple Concurrent Object-Oriented Programming
Evolved through the last two decades
Comm. ACM paper (1993)
Chap. 30 of Object-Oriented Software Construction,
2nd edition, 1997
Piotr Nienaltowskis ETH thesis, 2008
Current work by Sebastian Nanz, Benjamin Morandi,
Scott West and other at ETH
Implementation available as part of EVE (research
version of EiffelStudio)
49
Object-oriented computation
To perform a computation is
To apply certain actions
To certain objects
Using certain processors
Actions
Objects
Processor
50
Actions
Objects
Processor
51
x.r (a)
Client
Supplier
previous
r (x : A)
do
end
x.r (a)
next
Processor
52
Client
previous
Supplier
next
r (x : A)
do
end
Clients handler
Suppliers handler
x.r (a)
53
Fundamental semantic rule: x r (a) waits for nonseparate x, doesnt wait for separate x.
54
nonsep : T
sep : separate T
Traitor!
nonsep := sep
nonsep p (a)
55
Wait by necessity
No explicit mechanism needed for client to
resynchronize with supplier after separate call.
The client will wait only when it needs to:
x .f
x.g (a)
y.f
value:=x.some_query
Wait here!
SCOOP
Mutual exclusion
59
Wait rule
Dining philosophers
class PHILOSOPHER inherit
PROCESS
rename
setup as getup
redefine step end
feature {BUTLER}
step
do
think ; eat (left, right)
end
end
61
62
SCOOP
Condition synchronization
Condition synchronization
SCOOP has an elegant way of expressing condition
synchronization by reinterpreting preconditions as wait
conditions
Completed wait rule:
64
Contracts
put (buf : separate QUEUE [INTEGER ] ; v : INTEGER)
-- Store v into buffer.
require
not buf.is_full
v>0
do
buf.put (v)
ensure
not buf.is_empty
end
Precondition becomes
wait condition
...
put (my_buffer, 10 )
67
SCOOP
Deadlocks
Deadlocks
Deadlocks are still possible in SCOOP. Work for deadlock
prevention, based on locking orders, is underway
class C
feature
a : separate A
b : separate A
make (x : separate A, y : separate A)
do
a := x
b := y
end
f do g (a) end
g (x : separate A) do h (b) end
h (y : separate A) do ... end
end
For more
Several concurrency courses in the ETH curriculum,
including our (Bertrand Meyer, Sebastian Nanz) Concepts
of Concurrent Computation (Spring semester)
Good textbooks:
Kramer
Herlihy
70