SlideShare a Scribd company logo
Reliable and Concurrent Software
Reliable and Concurrent Software
Java
Java
PDEEC
2009/2010
1
Context
Context
 A project called "Oak“, started by James Gosling at Sun in 1991.
 Goals:
◦ to implement a virtual machine
◦ and a language that had a familiar C-like notation
◦ but with greater simplicity than C/C++.
◦ Borrowed a lot from UCSD Pascal
 The first public implementation was Java 1.0 in 1995. It made the promise of
"Write Once, Run Anywhere", with free runtimes on popular platforms.
 First targeted for embedded systems!, but never catch up there.
 Web browsers soon incorporated it into their standard configurations in a
"applet" configuration.That became quickly popular, due to platform
independence.
 It was fairly secure and its security was configurable, allowing for network and
file access to be limited.
 New versions for large and small platforms (J2EE and J2ME) soon were
designed with the advent of "Java 2“, and then 3, 4, 5, 6 and 7.
2
Threads
Threads
 Predefined class java.lang.Thread
◦ Alternative mechanism interface Runnable
◦ Thread code is provided by extending or
implementing the run method
◦ Threads do not begin their execution until
the start method in the Thread class is
called
3
Threads
Threads
class CountDown extends Thread{
public void run(){
for(int i = 10;i>0;i--){
System.out.println(this.getName()+ " Count "+
i);
Thread.yield(); }
}
}
public class CountDownApp {
public static void main(String[] args){
Thread count1 = new CountDown();
Thread count2 = new CountDown();
count1.start();
count2.start();
}
}
4
Threads
Threads
 The run method should not be called directly by the
application.The system calls it.
 If the run method is called explicitly by the application
then the code is executed sequentially not concurrently
 When the run method exits, the thread is no longer
executable and it can be considered terminated (Java
calls this the dead state)
 The thread remains in this state until it is garbage
collected
5
Threads
Threads
 If two or more threads have different priorities, the scheduler
executes (hopefully) highest priority first.
 Two or more threads of the same priority may execute round-
robin
 A thread can’t yield to a thread with lower priority.
 Thread scheduling relies on the underlying system, the final result
may vary depending on the platform.
 One thread can interrupt another thread by calling thread’s
interrupt method.
 A thread must frequently check its isInterrupted method to see if it
has been interrupted.
 If a thread is interrupted while it is sleeping, InterruptedException
is thrown. In this case, the isInterrupted method won’t indicate that
the thread has been interrupted.
6
Threads
Threads
class Counter extends Thread{
public void run(){
int count = 0;
while(!isInterrupted()){
System.out.println(this.getName()+" count "+
count);
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException e){
break;
}
}
System.out.println("Counter interrupted!!");
}
}
7
Threads
Threads
 A Thread Terminates
◦ when it completes execution of its run method either normally
or as the result of an unhandled exception
◦ via a call to its stop method — the run method is stopped and
the thread class cleans up before terminating the thread
(releases locks and executes any finally clauses)
◦ the thread object is now eligible for garbage collection.
◦ stop is inherently unsafe as it releases locks on objects and can
leave those objects in inconsistent states; the method is now
deprecated and should not be used
◦ by its destroy method being called — destroy terminates the
thread without any cleanup (not provided by many JVMs, now
deprecated)
8
Communication and
Communication and
Synchronization
Synchronization
 Java provides simple Monitor style objects
 Objects also provide condition variables (to implement
condition synchronization) with three operations :
◦ wait: an unconditional suspension of the calling thread (the
thread is placed on a queue associated with the condition
variable)
◦ notify: one thread is taken from the queue and re-scheduled for
execution (it must reclaim the lock first)
◦ notifyAll: all suspended threads are re-scheduled
◦ A thread can wait and notify on a single anonymous
condition variable
9
Communication and Synchronization
Communication and Synchronization
 There is a mutual exclusion lock associated with each
object which cannot be accessed directly by the
application but is affected by
◦ the method modifier synchronized
◦ block synchronization
 When a method is labeled as synchronized, access to
the method can only proceed once the system has
obtained the lock
 Hence, synchronized methods have mutually exclusive
access to the data encapsulated by the object, if that
data is only accessed by other synchronized methods
 Non-synchronized methods do not require the lock
and, therefore, can be called at any time
10
Communication and
Communication and
Synchronization
Synchronization
 Example
11
public class SharedCoordinate {
public SharedCoordinate(int initX, int initY) {
x = initX;
y = initY;
}
public synchronized void write(int newX, int newY){
x = newX;
y = newY;
}
...
private int x, y;
}
Communication and
Communication and
Synchronization
Synchronization
 Block synchronization
◦ A mechanism where a block can be labeled as synchronized -The
synchronized keyword takes as a parameter an object whose lock the
system needs to obtain before it can continue
◦ Used in its full generality, the synchronized block can undermine one of
the advantages of monitor-like mechanisms, that of encapsulating
synchronization constraints associate with an object into a single place
in the program
 This is because it is not possible to understand the synchronization associated with a
particular object by just looking at the object itself when other objects can name that
object in a synchronized statement
 However with careful use, this facility augments the basic model and allows more
expressive synchronization constraints to be programmed
12
public int read() {
synchronized(otherObj) {
return theData;
}
}
Communication and
Communication and
Synchronization
Synchronization
 A buffer
13
public class BoundedBuffer {
private int buffer[];
private int first;
private int last;
private int numberInBuffer = 0;
private int size;
public BoundedBuffer(int length) {
size = length;
buffer = new int[size];
last = 0;
first = 0;
}
Communication and
Communication and
Synchronization
Synchronization
14
public synchronized void put(int item) throws InterruptedException {
while (numberInBuffer == size)
wait();
last = (last + 1) % size ;
numberInBuffer++;
buffer[last] = item;
notifyAll();
}
public synchronized int get() throws InterruptedException {
while (numberInBuffer == 0)
wait();
first = (first + 1) % size ;
numberInBuffer--;
notifyAll();
return buffer[first];
}
Communication and
Communication and
Synchronization
Synchronization
 The notify method wakes up one waiting thread - the
one woken is not defined by the Java language
 notify does not release the lock; hence the woken
thread must wait until it can obtain the lock before
proceeding
 To wake up all waiting threads requires use of the
notifyAll method
 If no thread is waiting, then notify and notifyAll have no
effect
 The wait method always blocks the calling thread and
releases the lock associated with the object.
 A waiting thread can also be awoken if it is
interrupted by another thread.
◦ In this case the InterruptedException is thrown.
15
Communication and
Communication and
Synchronization
Synchronization
 There are no explicit condition variables in Java
◦ When a thread is awoken, it cannot assume that its condition is
true, as all threads are potentially awoken irrespective of what
conditions they were waiting on
◦ For some algorithms this limitation is not a problem, as the
conditions under which tasks are waiting are mutually exclusive
◦ E.g., the bounded buffer traditionally has two condition variables:
BufferNotFull and BufferNotEmpty
◦ If a thread is waiting for one condition, no other thread can be
waiting for the other condition
◦ One would expect that the thread can assume that when it
wakes, the buffer is in the appropriate state
16
Communication and
Communication and
Synchronization
Synchronization
 This is not always the case; Java makes no
guarantee that a thread woken from a
wait will gain immediate access to lock
◦ Another thread could call the put method,
find that the buffer has space and inserted
data into the buffer
◦ When the woken thread eventually gains
access to the lock, the buffer will again be full
◦ Hence, it is usually essential for threads to re-
evaluate their guards
17
Example
Example
 Readers and writers
18
public class ReadersWriters {
private int readers = 0;
private int waitingWriters = 0;
private boolean writing = false;
public synchronized void StartWrite() throws InterruptedException {
while(readers > 0 || writing) {
waitingWriters++;
wait();
waitingWriters--;
}
writing = true;
}
public synchronized void StopWrite() {
writing = false;
notifyAll();
}
Example
Example
 There are different variations on this scheme
◦ the one considered here is where priority is always
given to waiting writers
◦ Hence, as soon as a writer is available, all new readers
will be blocked until all writers have finished
◦ Of course, in extreme situations this may lead to
starvation of readers.
19
public synchronized void StartRead() throws InterruptedException {
while(writing || waitingWriters > 0)
wait();
readers++;
}
public synchronized void StopRead() {
readers--;
if(readers == 0) notifyAll();
}
Example
Example
 Events
20
public enum EventState {UP, DOWN};
public class Event {
protected EventState value;
public Event(EventState initial) {
value = initial;
}
public Event() {
value = EventState.DOWN;
}
public synchronized void await(int state) throws InterruptedException {
while(value != state) wait();
}
Example
Example
 Events
21
public synchronized void set() {
value = EventState.UP;
notifyAll();
}
public synchronized void reset() {
value = EventState.DOWN;
notifyAll();
}
public synchronized void toggle() {
if(value == EventState.DOWN)
value = EventState.UP;
else
value = EventState.DOWN;
notifyAll();
}
public synchronized int state() {
return value;
} }
Concurrency
Concurrency
 Since version 5, Java has comprehensive support for
general-purpose concurrent programming
 The support is partitioned into three packages:
◦ java.util.concurrent - this provides various classes to
support common concurrent programming paradigms, e.g.,
bounded buffers, sets and maps, thread pools, etc
◦ java.util.concurrent.atomic - this provides support for lock-
free thread-safe programming on simple variables such as
atomic integers, atomic booleans, etc.
◦ java.util.concurrent.locks - this provides a framework for
various locking algorithms that augment the Java language
mechanisms, e.g., read -write locks and condition variables
22
Locks
Locks
 Since Java 5 it is possible to explicitly lock some
code in a more flexible way than the one
provided by synchronized.
 The Lock interface defines a number of abstract
locking operations.
 Lock offers a choice of (un)conditional polled,
timed, and interruptible lock acquisition, and all
lock and unlock operations are explicit.
23
public interface Lock {
void lock();
void lockInterruptibly() throws InterruptedException;
Condition newCondition();
boolean tryLock();
boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException;
void unlock();
}
Locks
Locks
 Reentrancy
◦ When a thread requests a lock that is already held by another
thread, the requesting thread blocks.
◦ But because intrinsic locks are reentrant, if a thread tries to
acquire a lock that it already holds, the request succeeds.
◦ Reentrancy means that locks are acquired on a per-thread
rather than per-invocation basis.
◦ Reentrancy is implemented by associating with each lock an
acquisition count and an owning thread.When the count is zero,
the lock is considered unheld.When a thread acquires a
previously unheld lock, the JVM records the owner and sets the
acquisition count to one.
◦ If that same thread acquires the lock again, the count is
incremented, and when the owning thread exits the
synchronized block, the count is decremented.When the count
reaches zero, the lock is released.
24
Locks
Locks
 Reentrancy
◦ Without it the following code would deadlock
25
public class Widget {
public synchronized void doSomething() {
...
}
}
public class LoggingWidget extends Widget {
public synchronized void doSomething() {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}
Locks
Locks
 Conditional lock acquisition
◦ The timed and polled lock-acquisition modes provided by
tryLock allow more sophisticated error recovery than
unconditional acquisition
◦ With intrinsic locks, a deadlock is fatal - the only way to recover
is to restart the application.
◦ Using timed or polled lock acquisition lets you regain control if
you cannot acquire all the required locks.
◦ Timed locks are also useful in implementing activities that
manage a time budget.
◦ When an activity with a time budget calls a blocking method, it
can supply a timeout corresponding to the remaining time in the
budget.This lets activities terminate early if they cannot deliver a
result within the desired time.
◦ With intrinsic locks, there is no way to cancel a lock acquisition
once it is started
26
Locks
Locks
 Example
27
public void transferMoney(Account fromAccount, Account toAccount,
EuroAmount amount) throws InsufficientFundsException {
synchronized (fromAccount) {
synchronized (toAccount) {
if (fromAccount.getBalance().compareTo(amount) < 0)
throw new InsufficientFundsException();
else {
fromAccount.debit(amount);
toAccount.credit(amount);
}
}
}
}
Deadlock
Thread_A: transferMoney(X, Y, 10);
Thread_B: transferMoney(Y, X, 20);
Locks
Locks
 Common way to avoid is using timeouts
◦ We use tryLock to attempt to acquire both
locks;
◦ But back off and retry if they cannot both be
acquired.
◦ The sleep time has a fixed component and a
random component to reduce the likelihood of
livelock.
◦ If the locks cannot be acquired within the
specified time, transferMoney returns a failure
status so that the operation can fail gracefully.
28
Locks
Locks
 Common way to avoid is using timeouts
29
long fixedDelay = ... ; long randMod = ... ;
long stopTime = System.nanoTime() + unit.toNanos(timeout);
while (true) {
if (fromAcct.lock.tryLock()) {
try {
if (toAcct.lock.tryLock()) {
try {
if (fromAcct.getBalance().compareTo(amount) < 0)
throw new InsufficientFundsException();
else {
fromAcct.debit(amount);
toAcct.credit(amount);
return true;
}
} finally {
toAcct.lock.unlock();
}
}
} finally {
fromAcct.lock.unlock();
}
}
if (System.nanoTime() > stopTime) return false;
NANOSECONDS.sleep(fixedDelay + rnd.nextLong() % randMod);
}
Conditions
Conditions
30
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
Conclusion
Conclusion
 Powerful, but low level, concurrency model
◦ Explicit management of locks (it shows that it is a late
add-on)
 Flexibility as a fundamental language design
property
◦ Safety comes afterwards
 Real-Time as a later add-on
◦ Poor priority support
◦ Almost no absolute time
◦ Poor semantics of scheduling and task queue handling
31

More Related Content

PPT
Java Multithreading and Concurrency
PPT
Programming - Java-Threads-and-Synchronization.ppt
PPTX
Multi-threaded Programming in JAVA
PPTX
04 threads-pbl-2-slots
PPTX
04 threads-pbl-2-slots
PPTX
econtent thread in java.pptx
PPTX
Thread syncronization
PPTX
Module 4 - Part 4 - Multithreaded Programming.pptx
Java Multithreading and Concurrency
Programming - Java-Threads-and-Synchronization.ppt
Multi-threaded Programming in JAVA
04 threads-pbl-2-slots
04 threads-pbl-2-slots
econtent thread in java.pptx
Thread syncronization
Module 4 - Part 4 - Multithreaded Programming.pptx

Similar to Reliable and Concurrent Software - Java language (20)

PPTX
Concurrency with java
PPTX
Concurrency with java
PPTX
Concurrency with java
PPTX
Concurrency with java
PPTX
Concurrency with java
PPTX
Concurrency with java
PPTX
Concurrency with java
PDF
CS844 U1 Individual Project
PPTX
PPTX
Java Concurrency and Asynchronous
PPTX
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
PPT
Threads in java
PPT
Thread 1
ODP
Java Concurrency, Memory Model, and Trends
PPT
04 threads
PPTX
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
PPTX
Thread priorities in java
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
PPTX
advanced java ppt
PPT
Threads in java, Multitasking and Multithreading
Concurrency with java
Concurrency with java
Concurrency with java
Concurrency with java
Concurrency with java
Concurrency with java
Concurrency with java
CS844 U1 Individual Project
Java Concurrency and Asynchronous
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Threads in java
Thread 1
Java Concurrency, Memory Model, and Trends
04 threads
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
Thread priorities in java
MSBTE Computer Engineering JPR java. multi. threading.pptx
advanced java ppt
Threads in java, Multitasking and Multithreading
Ad

Recently uploaded (20)

PDF
Well-logging-methods_new................
PPTX
Construction Project Organization Group 2.pptx
PPT
Project quality management in manufacturing
PPTX
additive manufacturing of ss316l using mig welding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Sustainable Sites - Green Building Construction
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
Well-logging-methods_new................
Construction Project Organization Group 2.pptx
Project quality management in manufacturing
additive manufacturing of ss316l using mig welding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
R24 SURVEYING LAB MANUAL for civil enggi
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Sustainable Sites - Green Building Construction
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
bas. eng. economics group 4 presentation 1.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
CH1 Production IntroductoryConcepts.pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Ad

Reliable and Concurrent Software - Java language

  • 1. Reliable and Concurrent Software Reliable and Concurrent Software Java Java PDEEC 2009/2010 1
  • 2. Context Context  A project called "Oak“, started by James Gosling at Sun in 1991.  Goals: ◦ to implement a virtual machine ◦ and a language that had a familiar C-like notation ◦ but with greater simplicity than C/C++. ◦ Borrowed a lot from UCSD Pascal  The first public implementation was Java 1.0 in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms.  First targeted for embedded systems!, but never catch up there.  Web browsers soon incorporated it into their standard configurations in a "applet" configuration.That became quickly popular, due to platform independence.  It was fairly secure and its security was configurable, allowing for network and file access to be limited.  New versions for large and small platforms (J2EE and J2ME) soon were designed with the advent of "Java 2“, and then 3, 4, 5, 6 and 7. 2
  • 3. Threads Threads  Predefined class java.lang.Thread ◦ Alternative mechanism interface Runnable ◦ Thread code is provided by extending or implementing the run method ◦ Threads do not begin their execution until the start method in the Thread class is called 3
  • 4. Threads Threads class CountDown extends Thread{ public void run(){ for(int i = 10;i>0;i--){ System.out.println(this.getName()+ " Count "+ i); Thread.yield(); } } } public class CountDownApp { public static void main(String[] args){ Thread count1 = new CountDown(); Thread count2 = new CountDown(); count1.start(); count2.start(); } } 4
  • 5. Threads Threads  The run method should not be called directly by the application.The system calls it.  If the run method is called explicitly by the application then the code is executed sequentially not concurrently  When the run method exits, the thread is no longer executable and it can be considered terminated (Java calls this the dead state)  The thread remains in this state until it is garbage collected 5
  • 6. Threads Threads  If two or more threads have different priorities, the scheduler executes (hopefully) highest priority first.  Two or more threads of the same priority may execute round- robin  A thread can’t yield to a thread with lower priority.  Thread scheduling relies on the underlying system, the final result may vary depending on the platform.  One thread can interrupt another thread by calling thread’s interrupt method.  A thread must frequently check its isInterrupted method to see if it has been interrupted.  If a thread is interrupted while it is sleeping, InterruptedException is thrown. In this case, the isInterrupted method won’t indicate that the thread has been interrupted. 6
  • 7. Threads Threads class Counter extends Thread{ public void run(){ int count = 0; while(!isInterrupted()){ System.out.println(this.getName()+" count "+ count); count++; try { Thread.sleep(1000); } catch (InterruptedException e){ break; } } System.out.println("Counter interrupted!!"); } } 7
  • 8. Threads Threads  A Thread Terminates ◦ when it completes execution of its run method either normally or as the result of an unhandled exception ◦ via a call to its stop method — the run method is stopped and the thread class cleans up before terminating the thread (releases locks and executes any finally clauses) ◦ the thread object is now eligible for garbage collection. ◦ stop is inherently unsafe as it releases locks on objects and can leave those objects in inconsistent states; the method is now deprecated and should not be used ◦ by its destroy method being called — destroy terminates the thread without any cleanup (not provided by many JVMs, now deprecated) 8
  • 9. Communication and Communication and Synchronization Synchronization  Java provides simple Monitor style objects  Objects also provide condition variables (to implement condition synchronization) with three operations : ◦ wait: an unconditional suspension of the calling thread (the thread is placed on a queue associated with the condition variable) ◦ notify: one thread is taken from the queue and re-scheduled for execution (it must reclaim the lock first) ◦ notifyAll: all suspended threads are re-scheduled ◦ A thread can wait and notify on a single anonymous condition variable 9
  • 10. Communication and Synchronization Communication and Synchronization  There is a mutual exclusion lock associated with each object which cannot be accessed directly by the application but is affected by ◦ the method modifier synchronized ◦ block synchronization  When a method is labeled as synchronized, access to the method can only proceed once the system has obtained the lock  Hence, synchronized methods have mutually exclusive access to the data encapsulated by the object, if that data is only accessed by other synchronized methods  Non-synchronized methods do not require the lock and, therefore, can be called at any time 10
  • 11. Communication and Communication and Synchronization Synchronization  Example 11 public class SharedCoordinate { public SharedCoordinate(int initX, int initY) { x = initX; y = initY; } public synchronized void write(int newX, int newY){ x = newX; y = newY; } ... private int x, y; }
  • 12. Communication and Communication and Synchronization Synchronization  Block synchronization ◦ A mechanism where a block can be labeled as synchronized -The synchronized keyword takes as a parameter an object whose lock the system needs to obtain before it can continue ◦ Used in its full generality, the synchronized block can undermine one of the advantages of monitor-like mechanisms, that of encapsulating synchronization constraints associate with an object into a single place in the program  This is because it is not possible to understand the synchronization associated with a particular object by just looking at the object itself when other objects can name that object in a synchronized statement  However with careful use, this facility augments the basic model and allows more expressive synchronization constraints to be programmed 12 public int read() { synchronized(otherObj) { return theData; } }
  • 13. Communication and Communication and Synchronization Synchronization  A buffer 13 public class BoundedBuffer { private int buffer[]; private int first; private int last; private int numberInBuffer = 0; private int size; public BoundedBuffer(int length) { size = length; buffer = new int[size]; last = 0; first = 0; }
  • 14. Communication and Communication and Synchronization Synchronization 14 public synchronized void put(int item) throws InterruptedException { while (numberInBuffer == size) wait(); last = (last + 1) % size ; numberInBuffer++; buffer[last] = item; notifyAll(); } public synchronized int get() throws InterruptedException { while (numberInBuffer == 0) wait(); first = (first + 1) % size ; numberInBuffer--; notifyAll(); return buffer[first]; }
  • 15. Communication and Communication and Synchronization Synchronization  The notify method wakes up one waiting thread - the one woken is not defined by the Java language  notify does not release the lock; hence the woken thread must wait until it can obtain the lock before proceeding  To wake up all waiting threads requires use of the notifyAll method  If no thread is waiting, then notify and notifyAll have no effect  The wait method always blocks the calling thread and releases the lock associated with the object.  A waiting thread can also be awoken if it is interrupted by another thread. ◦ In this case the InterruptedException is thrown. 15
  • 16. Communication and Communication and Synchronization Synchronization  There are no explicit condition variables in Java ◦ When a thread is awoken, it cannot assume that its condition is true, as all threads are potentially awoken irrespective of what conditions they were waiting on ◦ For some algorithms this limitation is not a problem, as the conditions under which tasks are waiting are mutually exclusive ◦ E.g., the bounded buffer traditionally has two condition variables: BufferNotFull and BufferNotEmpty ◦ If a thread is waiting for one condition, no other thread can be waiting for the other condition ◦ One would expect that the thread can assume that when it wakes, the buffer is in the appropriate state 16
  • 17. Communication and Communication and Synchronization Synchronization  This is not always the case; Java makes no guarantee that a thread woken from a wait will gain immediate access to lock ◦ Another thread could call the put method, find that the buffer has space and inserted data into the buffer ◦ When the woken thread eventually gains access to the lock, the buffer will again be full ◦ Hence, it is usually essential for threads to re- evaluate their guards 17
  • 18. Example Example  Readers and writers 18 public class ReadersWriters { private int readers = 0; private int waitingWriters = 0; private boolean writing = false; public synchronized void StartWrite() throws InterruptedException { while(readers > 0 || writing) { waitingWriters++; wait(); waitingWriters--; } writing = true; } public synchronized void StopWrite() { writing = false; notifyAll(); }
  • 19. Example Example  There are different variations on this scheme ◦ the one considered here is where priority is always given to waiting writers ◦ Hence, as soon as a writer is available, all new readers will be blocked until all writers have finished ◦ Of course, in extreme situations this may lead to starvation of readers. 19 public synchronized void StartRead() throws InterruptedException { while(writing || waitingWriters > 0) wait(); readers++; } public synchronized void StopRead() { readers--; if(readers == 0) notifyAll(); }
  • 20. Example Example  Events 20 public enum EventState {UP, DOWN}; public class Event { protected EventState value; public Event(EventState initial) { value = initial; } public Event() { value = EventState.DOWN; } public synchronized void await(int state) throws InterruptedException { while(value != state) wait(); }
  • 21. Example Example  Events 21 public synchronized void set() { value = EventState.UP; notifyAll(); } public synchronized void reset() { value = EventState.DOWN; notifyAll(); } public synchronized void toggle() { if(value == EventState.DOWN) value = EventState.UP; else value = EventState.DOWN; notifyAll(); } public synchronized int state() { return value; } }
  • 22. Concurrency Concurrency  Since version 5, Java has comprehensive support for general-purpose concurrent programming  The support is partitioned into three packages: ◦ java.util.concurrent - this provides various classes to support common concurrent programming paradigms, e.g., bounded buffers, sets and maps, thread pools, etc ◦ java.util.concurrent.atomic - this provides support for lock- free thread-safe programming on simple variables such as atomic integers, atomic booleans, etc. ◦ java.util.concurrent.locks - this provides a framework for various locking algorithms that augment the Java language mechanisms, e.g., read -write locks and condition variables 22
  • 23. Locks Locks  Since Java 5 it is possible to explicitly lock some code in a more flexible way than the one provided by synchronized.  The Lock interface defines a number of abstract locking operations.  Lock offers a choice of (un)conditional polled, timed, and interruptible lock acquisition, and all lock and unlock operations are explicit. 23 public interface Lock { void lock(); void lockInterruptibly() throws InterruptedException; Condition newCondition(); boolean tryLock(); boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException; void unlock(); }
  • 24. Locks Locks  Reentrancy ◦ When a thread requests a lock that is already held by another thread, the requesting thread blocks. ◦ But because intrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds. ◦ Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis. ◦ Reentrancy is implemented by associating with each lock an acquisition count and an owning thread.When the count is zero, the lock is considered unheld.When a thread acquires a previously unheld lock, the JVM records the owner and sets the acquisition count to one. ◦ If that same thread acquires the lock again, the count is incremented, and when the owning thread exits the synchronized block, the count is decremented.When the count reaches zero, the lock is released. 24
  • 25. Locks Locks  Reentrancy ◦ Without it the following code would deadlock 25 public class Widget { public synchronized void doSomething() { ... } } public class LoggingWidget extends Widget { public synchronized void doSomething() { System.out.println(toString() + ": calling doSomething"); super.doSomething(); } }
  • 26. Locks Locks  Conditional lock acquisition ◦ The timed and polled lock-acquisition modes provided by tryLock allow more sophisticated error recovery than unconditional acquisition ◦ With intrinsic locks, a deadlock is fatal - the only way to recover is to restart the application. ◦ Using timed or polled lock acquisition lets you regain control if you cannot acquire all the required locks. ◦ Timed locks are also useful in implementing activities that manage a time budget. ◦ When an activity with a time budget calls a blocking method, it can supply a timeout corresponding to the remaining time in the budget.This lets activities terminate early if they cannot deliver a result within the desired time. ◦ With intrinsic locks, there is no way to cancel a lock acquisition once it is started 26
  • 27. Locks Locks  Example 27 public void transferMoney(Account fromAccount, Account toAccount, EuroAmount amount) throws InsufficientFundsException { synchronized (fromAccount) { synchronized (toAccount) { if (fromAccount.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(); else { fromAccount.debit(amount); toAccount.credit(amount); } } } } Deadlock Thread_A: transferMoney(X, Y, 10); Thread_B: transferMoney(Y, X, 20);
  • 28. Locks Locks  Common way to avoid is using timeouts ◦ We use tryLock to attempt to acquire both locks; ◦ But back off and retry if they cannot both be acquired. ◦ The sleep time has a fixed component and a random component to reduce the likelihood of livelock. ◦ If the locks cannot be acquired within the specified time, transferMoney returns a failure status so that the operation can fail gracefully. 28
  • 29. Locks Locks  Common way to avoid is using timeouts 29 long fixedDelay = ... ; long randMod = ... ; long stopTime = System.nanoTime() + unit.toNanos(timeout); while (true) { if (fromAcct.lock.tryLock()) { try { if (toAcct.lock.tryLock()) { try { if (fromAcct.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(); else { fromAcct.debit(amount); toAcct.credit(amount); return true; } } finally { toAcct.lock.unlock(); } } } finally { fromAcct.lock.unlock(); } } if (System.nanoTime() > stopTime) return false; NANOSECONDS.sleep(fixedDelay + rnd.nextLong() % randMod); }
  • 30. Conditions Conditions 30 class BoundedBuffer { final Lock lock = new ReentrantLock(); final Condition notFull = lock.newCondition(); final Condition notEmpty = lock.newCondition(); final Object[] items = new Object[100]; int putptr, takeptr, count; public void put(Object x) throws InterruptedException { lock.lock(); try { while (count == items.length) notFull.await(); items[putptr] = x; if (++putptr == items.length) putptr = 0; ++count; notEmpty.signal(); } finally { lock.unlock(); } }
  • 31. Conclusion Conclusion  Powerful, but low level, concurrency model ◦ Explicit management of locks (it shows that it is a late add-on)  Flexibility as a fundamental language design property ◦ Safety comes afterwards  Real-Time as a later add-on ◦ Poor priority support ◦ Almost no absolute time ◦ Poor semantics of scheduling and task queue handling 31