Download Concurrent Programming in Java

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Structured programming wikipedia , lookup

Design Patterns wikipedia , lookup

Falcon (programming language) wikipedia , lookup

Java (programming language) wikipedia , lookup

Go (programming language) wikipedia , lookup

Java performance wikipedia , lookup

Class (computer programming) wikipedia , lookup

Object-oriented programming wikipedia , lookup

Parallel computing wikipedia , lookup

Name mangling wikipedia , lookup

C++ wikipedia , lookup

Join-pattern wikipedia , lookup

C Sharp syntax wikipedia , lookup

Scheduling (computing) wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Thread (computing) wikipedia , lookup

Monitor (synchronization) wikipedia , lookup

Transcript
Concurrent Programming
in JAVA
Steve Pruett - Introduction
Jaime Mendez – Thread Creation
Adrian Garcia – Thread Management
Eric Orozco – Thread Safety and Liveness
Key Terminology
• Flow of Control - particular sequence of
actions that the CPU performs
• Process - individual program, representing
a larger and more complex flow of control
handled by the operating system
• Thread – specific, smaller flow of control
within a given process
• Multitasking - procedure that allows
threads or processes to share time on a
single processor by taking turns
Introduction
• Concurrent programming is the creation of
more than one flow of control, functioning
simultaneously, each with the ability to
communicate with other operating flows.
• This can be implemented in two ways:
– With a single program that contains
multiple threads which share the same
variables and object instances
– With multiple programs which run at the
same time and can pass messages to
each other
Graphical Example of
Flow of Control:
Sequential
Concurrent
Complex Concurrent
• When operating in sequence, one flow must be
completed before another can begin, but more
can be accomplished in the same time with
concurrently operating flows.
Pros & Cons of Concurrent
Programming
Pros:
a. Increased speed
b. Reduced idle time
c. Better usage of multiprocessor
machines
Cons: a. Harder to program
b. High memory usage due to
switching, instantiation, and
synchronization
c. Race condition
History
• The idea of simultaneously running
processes was originally implemented in
the 1960’s with independent input-output
device controllers, called channels.
• These channels acted as small computers,
which were individually programmable.
• Advancements such as semaphores,
message passing, multiple CPU’s, and the
like have brought concurrent
programming up to its current
functionality and popularity.
Examples of Concurrent
Programming
• Creating a more responsive application
that can readily accept user input even if
it is already involved in very intensive
computational procedures.
• It can be applied in a server to give
multiple clients simultaneous access to
that server.
• Reactive system - program that
continually checks collections of
information for any changes, and reacts to
those changes appropriately (autopilot
systems, patient monitoring systems, etc.)
Creating Threads
• Two basic approaches
– Extending the java.lang.Thread class
– Implementing the java.lang.Runnable
interface
Creating Threads
Thread
My Thread
Run()
Runnable
My Thread
Run()
Creating Threads
• Extending the Thread Class
– All threads are instances of the
Thread class
– Run() method must be overriden in
the subclass (Invoked indirectly)
Creating Threads
•Template for a new Thread class
public class MyThread extends Thread{
public void run(){
//the thread body
}
//other methods and fields
}
Creating Threads
• Extending Thread Example
– Simple Infinite Counter
Thread 1
Thread 2
Creating Threads
• Implementing a Runnable Interface
• Java only supports a single inheritance
among classes ( Ex: applets cannot also
extend Thread class at the same time)
Creating Threads
• Runnable Interface
public interface Runnable {
public abstract void run();
}
• Template for a new Thread implementing
the Runnable interface
public class MyThread extends AnotherClass Implements
Runnable {
public void run(){
//the thread body
}
//other methods and fields
}
Creating Threads
• Implementing the Runnable
Interface Example
– Simple Infinite Counter II
Thread 1
Thread 2
Thread Management
•Thread Life Cycle
–Thread State Changes
•Thread Manipulation Methods
–Thread Class
–Object Class
•Thread Priority & Scheduling
Thread Life Cycle
• Life Cycle Consists of Three States:
– New
– Alive
– Dead
• New State
– Thread is in this state after its
creation (new myThread();).
– Remains in New state until start()
method is invoked.
Thread Life Cycle
• Alive State
– Thread enters this state when start()
method is invoked
– State is divided into two sub-states
• Runnable – Threads in this state are
ready to run but may not necessarily be
running
• Blocked – Threads in this state have been
blocked and are not ready to run. Must
wait until a method call moves thread
back to Runnable state.
Thread Life Cycle
• Dead State
– Thread enters this state when run()
method has terminated and returned
– Once in this state, thread is
terminated
– Change is final and irreversible
• Threads cannot jump back to a previous
state. Threads are New, then Alive,
then Dead.
Thread Life Cycle
Thread Manipulation
Methods
• Thread’s state changes can be
manipulated through the use of
methods from two classes:
– Thread Class
– Object Class
• Methods from Thread Class
– start() – Thread should be in New state.
Method causes thread to enter Alive state
and begin execution.
Thread Manipulation
Methods
– sleep() – Thread should be in Runnable
state. Method causes thread to enter
Blocked state for a defined amount of time
after which it returns to Runnable state.
– join() – Thread should be in Runnable state.
Thread is blocked and waits until another
thread stops execution before it returns to
Runnable state.
– yield() – Remains in Runnable state but
gives other threads an opportunity to run.
Thread Manipulation
Methods
– interrupt() – If thread is in Runnable state,
interrupted flag will be set. If thread is in
Blocked state, it is awakened, enters
Runnable state.
– isAlive() – Returns true if thread is in Alive
state, false otherwise.
– isInterrupted() – Returns true if the
interrupted flag is set.
Thread Manipulation
Methods
• Object Class
– wait()
– notify()
– notifyAll()
• These methods are used to change a
thread’s state from Runnable to
Blocked.
Priority & Scheduling
• Threads have priority attributes.
• Highest priority executes first.
• Priority can be changed by programmer.
– setPriority(int newPriority)
• Possible for more than 1 thread to have
the same priority
– JVM determines which executes first.
Priority & Scheduling
• A thread with higher priority will
obstruct a thread of lower priority.
• Program correctness should not depend
on Priorities.
Thread Safety
• Safety Properties
• Problem
– Race Hazard (AKA Race Condition)
• Solution
– Synchronization – Creating Locks
Example of a Race Hazard
• The following piece of code can print either a 0 or a 1
depending on how the threads are scheduled.
public class DataRace {
static int a = 0;
public static void main() {
new MyThread().start();
a = 1;
}
public static class MyThread extends Thread {
public void run() {
System.out.println(a);
}
}
}
Examples of
Synchronization
Class MyClass{
synchronized public void aMethod(){
<do something>
}
}
Class MyClass{
public void aMethod(){
synchronized(this){
<do something>
}
}
}
Examples of
Synchronization
Synchronized(expression){
<do something>
}
Thread Cooperation using
Guarded Suspension
• What is guarded suspension?
– before a method is executed, the
guard (precondition) is tested
– execution continues only when the
guard is true
– execution is temporarily suspended
until the guard becomes true if
previously false
What Do We Use to
Implement Guarded
Suspension?
• The wait() Method
• The notify() Method
• The notifyAll() Method
The wait() Method
• wait() – The current thread is
temporarily blocked and placed in a
wait queue associated with the
receiving object. The receiving object’s
lock is temporarily released. The
thread will resume execution when it is
awakened by notify() or notifyAll().
The notify() Method
• notify() – One of the threads in the wait
queue will be awakened and removed
from the queue. The awakened thread
must re-obtain the lock before it can
resume at the point immediately after
the invocation of wait().
The notifyAll() Method
• notifyAll() – This method is the same as
notify(), except that every thread in the
wait queue associated with the
receiving object will be awakened and
removed from the queue.
When to use What
• The wait() method should be invoked
when a thread is temporarily unable to
continue and to allow other threads to
proceed
• The notify() or notifyAll() method
should be invoked to make a thread
notify other threads that they may
proceed
Liveness
• What is Liveness?
• Ensure Liveness by Preventing Liveness
Failures
– Contention
– Dormancy
– Deadlock
– Premature Termination
Liveness Failures
• Contention - occurs when a runnable
thread never gets a chance to run.
• Dormancy - occurs when a thread that
is blocked never becomes runnable.
• Deadlock - occurs when two or more
threads block each other and none can
make progress.
• Premature Termination - occurs when a
thread is terminated before it should be
and can result in impeding the progress
of other threads.
Conclusion
Concurrent programming is the
practice of using multiple flows of
control to achieve greater functionality
and performance from software.
It may require great caution when
practicing, however it may yield great
results.
Works Cited
•
Goetz, Brian. “Don't let the ‘this’ reference escape during construction.” Java
Theory and practice: Safe construction techniques. IBM. 11 April. 2005.
<http://www-106.ibm.com/developerworks/java/library/j-jtp0618.html>.
•
Hartley, Stephen J. Concurrent Programming. New York: Oxford University
Press, 1998
•
Java Technology. 10 April. 2005. Sun Microsystems. <http://java.sun.com/>.
•
Jia, Xiaoping. Object-Oriented Software Development Using Java. 2nd ed.
Boston: Addison Wesley, 2003.
•
Lea, Doug. Concurrent Programming In Java. 2nd ed. Massachusetts:
Addison-Wesley, 2000
•
Book