# Presentation: 373035

## Threading and ConcurrentProgramming in Java

- Introduction and Definitions
- D.W. Denbo

- Java Threads

- 2006-08-02

## Overview

- We will be covering both the tools, classes and interfaces available within JDK 5.0, and the concepts necessary to develop robust multithreaded applications.
- Multithreading is necessary to create applications, both GUI and client-server, that are both responsive to the user and provide a high level of control.

- Java Threads

- 2006-08-02

## Outline

- What are Threads?
- Advantages
- Limitations
- Java concurrency support
- Interrupting Threads
- Thread States

- Java Threads

- 2006-08-02

## What are Threads?

- A *thread*, short for thread of control, enables multitasking within a single program.  While processes has a complete set of its own variables, threads share the same data.
- Multithreading changed dramatically in JDK 5.0, with the addition of a large number of specialty classes and interfaces that support threading.
- Warning: multithreading can get very complex!

- Java Threads

- 2006-08-02

## Advantages

- Reactive programming
- Availability
- Controllability
- Active objects
- Asynchronous messages
- Parallelism
- Required concurrency

- Java Threads

- 2006-08-02

## Reactive Programming

- Some programs are required to do more than one thing at a time.  While it is possible to program such systems in a single-threaded manner by manually interleaving the different activities, this is complicated, fragile, and error-prone.  Reactive programs are easier to design and implement using threads.

- Java Threads

- 2006-08-02

## Availability

- Concurrency allows you to maintain high availability of services.  For example, you can have one object serve as a gateway interface to a service, handling each request by constructing a new thread to asynchronously perform the associated

- Java Threads

- 2006-08-02

## Controllability

- Activities can be suspended, resumed, and stopped by other objects.  *(NOTE: don’t use the stop, suspend, or resume methods.) * This is done by setting flags or raising exceptions within the thread.

- Java Threads

- 2006-08-02

## Active Objects

- Software objects often model read objects. Most real objects display independent, autonomous behavior.

- Java Threads

- 2006-08-02

## Asynchronous Messages

- When one object sends a message to another, the sender doesn’t always care when the resulting action is performed.  Threads allow the first object to continue its own activity without waiting.

- Java Threads

- 2006-08-02

## Parallelism

- Multiple CPUs can be can be used to exploit available computing power.  Even without multiple CPUs, interleaving activities in threads avoids delays, for example, waiting for remote connection and data transfer.

- Java Threads

- 2006-08-02

## Required Concurrency

- Some Java features require threaded applications.  For example, audio clips and proper updating of graphics during animations and status information updating.

- Java Threads

- 2006-08-02

## Limitations

- Safety
- Liveness
- Nondeterminism
- Threads versus method calls
- Objects versus activities
- Thread construction overhead
- Context-switching overhead
- Synchronization overhead
- Threads versus processes

- Java Threads

- 2006-08-02

## Safety

- When multiple threads are not completely independent, each can be involved in sending messages to other objects that may also be involved in other threads.  These objects must use synchronization mechanisms to maintain consistent state.  Using multiple threads involving objects designed to work only in sequential settings can lead to hard to debug inconsistencies.

- Java Threads

- 2006-08-02

## Liveness

- Activities within concurrent programs may fail to be *live*.  One or more activities can simply stop for any number of reasons, for example, deadlocking, resource limitations, and uncaught exceptions.

- Java Threads

- 2006-08-02

## Nondeterminism

- Multithreaded activities can be arbitrarily interleaved.  No two executions of the same program need be identical.

- Java Threads

- 2006-08-02

## Threads versus Method Calls

- Threads are not very useful for request/reply-style programming.  When one object must logically wait for a reply from another in order to continue, the same thread should be used to implement the entrire request-execute-reply sequence.

- Java Threads

- 2006-08-02

## Objects versus Activities

- There are many fewer asynchronously executing concurrent activities than objects.  It makes sense to create a new thread only when an invocation actually generates a new asynchronous activity, not automatically whenever constructing a new object that may or may not engage in asynchronous activities.

- Java Threads

- 2006-08-02

## Thread Construction Overhead

- Constructing a thread and setting it in motion is typically slower and more memory- intensive than constructing a normal object or invoking a method on it.  If an activity is short, then it is much faster to just invoke it rather than to use threads.

- Java Threads

- 2006-08-02

## Context-switching Overhead

- When there are more active threads than there are CPUs, the Java run-time system occasionally switches from running one activity to running another, which also entails *scheduling* -- figuring out witch thread to run next.

- Java Threads

- 2006-08-02

## Synchronization Overhead

- Java methods employing synchronizations can be slower than those that do not provide proper concurrency protection.  Between thread and synchronization overhead, concurrent programs can run more slowly than sequential ones.

- Java Threads

- 2006-08-02

## Threads versus Processes

- Activities that are intrinsically self-contained and sufficiently heavy may be simpler to encapsulate into standalone programs.  Standalone programs can be accessed via system-level execution facilities ore remote invocation mechanisms rather than as multithreaded components of a single process.

- Java Threads

- 2006-08-02

## JDK 5.0 Concurrency Support

- Java.lang.Thread
- Keywords - synchronized and volatile
- Methods - wait, notify, and notifyAll
- Blocking Queues
- Thread-safe collections
- Callables and Futures
- Executors
- Synchronizers

- Java Threads

- 2006-08-02

**Notes:**
Thread - 

Keywords - 

Methods - 

Blocking queues - A queue is a data structure with two basic operations: add an element to the tail of the queue and remove an element from the head.  A blocking queue causes a thread to block when you try to add an element to a queue that is full or remove an element from one that is empty.

Thread-safe collections - java.util.concurrent package contains queues and hashtable that can support a large number of readers and writers.  

Callables and Futures - 

Executors - 

Synchronizers - 

## Interrupting Threads

- A thread terminates when its *run* method returns.  In JDK 1.0, there also was a *stop* method, however, that method is now deprecated.
- There is no longer a way to *force* a thread to terminate.  However, the *interrupt*  method can be used to *request*  termination of a thread.

- Java Threads

- 2006-08-02

- while (!Thread.currentThread().isInterrupted()) {
-    // do more work
- }

- Java Threads

- 2006-08-02

- public void run() {
- 	try {
- 		while(!Thread.currentThread().isInterrupted()) {
-        // do more work
- 		}
- 	} catch(InterruptedException ie) {
- 		// thread was interrupted during sleep or wait
- 	}finally {
- 		// cleanup, if required
- 	}
- 	// exiting the run method terminates the thread
- }

- Java Threads

- 2006-08-02

## Thread States

- New - When a thread is created with the new operator - the thread is not yet running.  It is in the *new* state.
- Runnable - Once the start method has been invoked the thread is *runnable*.

- Java Threads

- 2006-08-02

## Thread States (cont)

- Blocked - A thread enters the *blocked* state:
- By calling the sleep method
- Thread calls an operations that is *blocking on I/O*
- Thread tries to acquire a lock
- Thread waits for a condition
- Suspend method is invoked.  (deprecated)

- Java Threads

- 2006-08-02

## Thread States (cont)

- Dead - a thread is dead when
- It dies a natural death because the run method exits normally.
- It dies abruptly because of an uncaught exception.

- Java Threads

- 2006-08-02

## Slide 30

- Java Threads

- 2006-08-02