Object-Oriented Design & Patterns

Cay S. Horstmann

Chapter 9

Concurrent Programming

Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.

Chapter Topics

Threads

Running Tasks

Concurrent Tasks Example

Concurrent Task Example

Callables

Futures

Application: How Many Long Words?

Waiting For Completion of First Task

Interrupting Threads

Sensing Interruptions

Sensing Interruptions

public class MyRunnable implements Runnable
{
   public void run()
   {
      try
      {
         while (...)
         {
            do work            
            Thread.sleep(...);
         }
      }
      catch (InterruptedException e)
      {
         // terminate thread
      }
   }
}

Thread Synchronization

Producer Thread

for (int i = 0; i < repetitions; i++)
   queue.add(greeting);

Consumer Thread

int count1 = 0;
int count2 = 0;
for (int i = 0; i < repetitions; i++)
{
   String greeting = queue.remove();
   if (greeting1.equals(greeting)) count1++;
   else if (greeting2.equals(greeting)) count2++;
}
System.out.println(greeting1 + ": " + count1);
System.out.println(greeting2 + ": " + count2);

Main Method

public static void main(String[] args)
{
   int n = 1000;
   BoundedQueue<String> q = new BoundedQueue<>(2 * n);
   ExecutorService service = Executors.newCachedThreadPool();
   Runnable p1 = producer("Hello", q, n);
   Runnable p2 = producer("Goodbye", q, n);
   Runnable c = consumer("Hello", "Goodbye", q, 2 * n);
   service.execute(p1);
   service.execute(p2);
   service.execute(c);
   service.shutdown();
}

Expected and Actual Behavior

Clicker Question

Why is the program corrupted?

Race Condition Scenario

Race Condition Scenario

.

Locks

Reentrant Locks

aLock = new ReentrantLock();
. . .
aLock.lock();
try
{
   protected code
}
finally
{
   aLock.unlock();
}

Scenario with Locks

  1. First thread calls add and acquires lock, then executes elements[tail] = anObject;
  2. Second thread calls add and tries to acquire lock, but it is blocked
  3. First thread executes tail++;
  4. First thread completes add, releases lock
  5. Second thread unblocked
  6. Second thread acquires lock, starts executing protected code

Deadlocks

Avoiding Deadlocks

Avoiding Deadlocks

Visualizing Locks

Visualizing Locks

.

Object Locks

Object Locks

Synchronized Blocks

Threadsafe Queues in the Standard Library

Example: Unique Long Words

.jpg

Example: Unique Long Words

Algorithm Animation

Algorithm Animation

Pausing and Running the Animation