Threads in Java

Download Report

Transcript Threads in Java

Threads in Java
History


Process is a program in execution


Multiuser operating systems since the sixties









Has stack/heap memory
Has a program counter
OS schedules process A
Process A runs until it is interrupted
OS saves process A’s state
OS schedules process B
Process A has what is necessary to execute
 OS interrupts process B, saving its state
 OS schedules process A
Most programming languages do not have techniques to permit the user to specify
concurrent activities
User wanting to program concurrently used operating system calls
ADA, developed for defense applications, was the first language to permit user-level
concurrency
Java has tools that permit concurrency


threads, so-called lightweight processes (because they lack their own address space)
These are portable across platforms
Uses
 Single-threaded applications can lead to long delays
 E.g., a process waiting for i/o must get what it needs until it can
resume
 While that process is waiting, no other process can run
 Example
 User is downloading an audio clip
 If single threaded, user must wait for the clip to be downloaded
before he/she can listen.
 If multi-threaded, one thread does download another plays back.
The threads are synchronized so that listening does not begin
until there is something to listen to.
 Multithreading is difficult and error-prone.
Thread States
 New: thread has been created
 Runnable: executing its task
 Waiting: waiting for another thread to
perform a task
 Timed Waiting: sleeping for a specific
amount of time
 Blocked: waiting for resources
 Terminated: thread is complete
Examples
 Timed Waiting
 Word processor that periodically saves work
 If thread did not sleep, it would have to be in a
continuous loop, asking the main process if it’s time to
back up consumes resources
 Blocked
 Thread issues i/o request.
 Thread cannot resume until the request has been
fulfilled.
 Runnable
 Collapses two o/s states: ready and running
Scheduling
 The JVM schedules threads by priority
 The scheduling algorithm used depends
on the os
 All multiuser os support some form of
time-slicing
 Many possibilities
 Round robin
 Multi-level priority queue (p. 1049)
Implementing Threads Directly
 Implement the Runnable interface
 Method run() contains the code that the
thread will execute
 Examples: ThreadCreator/PrintTask
Using the Executor/Service
Interfaces
 Executor
 Manages the execution of Runnable objects
 Collects a group of threads into a thread pool
 Reuses existing threads to eliminate the overhead
involved in creating threads
 Optimizes the number of threads to ensure that
processor stays busy
 ExecutorService
 Interface that extends Executor and adds additional
methods to manage thread lifecycle
 Examples: TaskExecutor/PrintTask
Synchronization
 Issue
 Multiple threads of control
 Single Address space
 Imagine that we have two control structures
 Parbegin initializes parallel processing
 Parendends parallel processing
 Look at the following scenario
ATM Example
Withdraw()
{
Record acctRec;
parbegin
{
paulProc();
heidiProc();
}
}
Parallel Processes
paulProc()
{
read request;
if (acctRec.bal >= request)
{
issue request;
acctRec.bal -= request;
}
}
paulProc()
{
read request;
if (acctRec.bal >= request)
{
issue request;
acctRec.bal -= request;
}
}
Critical Section
 The part of the program where shared
memory is accessed
Race Condition
 Two or more processes/threads
reading/writing shared data
 Result depends on who gets there first
Mutual Exclusion
 Mechanism to prevent more than one
process from entering its critical section
 Need for such a mechanism was
recognized in the sixties
 Most languages do not provide programlevel mutual exclusion facilities
 Programmer must rely on operating
system calls
Monitor
 Java’s solution to the mutual exclusion problem
 Every object has a monitor and a monitor lock
 Monitor ensures that its object’s lock is held by a
maximum of one thread at a time.
 If a thread holds a lock, other threads trying to
access the same object will be blocked until the
thread is released.
High Level
 Synchronized statement
 Specifies that a thread must hold a monitor lock to
execute the synchronized statements.
 Monitor allows only one thread at a time to execute
statements within a synchronized block
 When a thread finishes executing the synchronized
statements, the lock is released.
Synchronized ( object )
{
statements
}
Producer/Consumer Problem
 Class IPC problem
 There is a buffer shared by
 A producer who produces objects
 A producer who consumes objects
 Simplest approach: strict alternation
 Consumer must not consume before producer
produces
 Producer must not produce object B before
object A has been consumed