1 threads sequential execution: here statements are executed one after the other.they consider only...

26
1 Threads Sequential Execution: Here statements are executed one after the other.They consider only a single thread of execution , where thread is an individual sequential actvity.

Upload: gervais-george

Post on 03-Jan-2016

224 views

Category:

Documents


1 download

TRANSCRIPT

1

ThreadsSequential Execution:

Here statements are executed one after the other.They consider only a single thread of execution , where thread is an individual sequential actvity.

2

Java program may execute several threads concurrently.

e.g one part of program may continue computing while another part is blocked waiting for input.

Java.lang.Thread is fundamental thread class.

3

The Main Thread

When a java program starts up, one thread begins running immediately.This is called the main thread of the program.

From the main thread all other child threads will be spawned.

The main thread is the last thread to finish the execution

4

There are two ways to define a Thread. 1) To subclass Thread , override the run() method and then

instantiate the subclass and call start() method. 2) To define a class that implements a Runnable ( it defines run()

method ) and then pass instance of this object to Thread constructor and then call start() method

In either case result is a thread object, where the run() method is the body of the thread.

When we call start method of the thread object, the interpreter creates a new thread to execute the run() method.This new thread continues to run until the run() method exits.Meanwhile , the original thread continues running itself , starting with the statement following the start() method.

5

Thread Life Cycle

A thread can be in one of six states.These states are represented by enumerated data type

Thread.State. Thread State can be obtained by getState() method.

NEW : The thread has been created but its start

method has not yet been called. RUNNABLE: Thread is executing in the JVM

6

BLOCKED:

The thread is not running as it is waiting to acquire a lock so that it can enter a synchronized method or block.

WAITING:

The thread is not running as it has called one of the following method.

7

»Object.wait with no timeout »Thread.join with no timeout : It

waits for thread to die(eg. Let u be a thread ,u.join(): It waits for thread u to die )

8

TIMED WAITING : The thread is not running as it has called Thread.sleep() or has called Object.wait() or Thread.join() with a timeout value.

TERMINATED : The thread has completed execution.Its

run() method has exited normally or by throwing an exception.

9

Thread Priorities: Threads can run at different priority levels.A thread at given priority level can not run if threads having higher priority

are waiting to run. Thread.MAX_PRIORITY : 10 Thread.MIN_PRIORITY : 1 Thread.NORM_PRIORITY : 5 All threads are examined and highest priority thread that is ready to run is given

the CPU. A thread can be preempted by higher priority thread.( Preemptive Multitasking)

10

We can get and set priority by using getPriority() and setPriority().

we need repetitive tasks at fixed intervals.

11

Locks and Synchronization

Threads are executed concurrently ,so when multiple concurrent threads access the same data ,data inconsistency may arise.

To avoid this thread should synchronize the access in shared state.A single lock is associated with every object.A lock can be held by atmost one thread at a time on an object.

A thread may explictly request the lock on an object by executing synchronized statement.

At a time only one thread can execute synchronized block

12

syntax: synchronized( expression) block statement

The expression must have reference type.The expression must evaluate to a non null reference say Obj.

After the evaluation of an expression thread becomes locking on the object

Obj.

When thread obtains the lock on object Obj, it becomes enabled and may be running so the block statement is executed.

When block statement terminates or is exited by return or break or by throwing an exception , the lock on o is released.

If static method is declared synchronized , the thread obtains the lock on the class.

13

• Class Buffer {• • private int item;• private boolean empty=true;• public int get(){• synchronized(this){• while(empty)• try{ this.wait();} catch(InterruptedException e){};• empty=true;• this.notify();• return item;• • }// end of syn block• }• public void put( int i){• synchronized(this){• • while(!empty)• try{ this.wait();}catch(InterruptedException e){};• empty=false• item=i;• this.notify();• }• }• }

14

The Collection, Set ,Map, List implementation do not have synchronized

methods. Synchronized wrapper objects.

eg.

List Synlist=Collections.synchronizedList(list);

Map Synmap=Collections.synchronizedMap(map);

15

A Lock Object If we use synchronized statements ,the lock we acquire

is block scoped.

Java 5.0 provides an alternative :A Lock object that we can explictly lock and unlock.

package java.util.concurrent.locks has interfaces and classes for this implementation

Interface lock has two mehtods:lock() and unlock which explictly locks or unlocks the objects

16

Deadlock :- It occurs when two threads end up

waiting for each other to release the lock they need.Here neither can proceed as neither can release the lock, so both threads stop running.

The following code is likely to create Deadlock.

17

• DeadLock Detection:

lock () method of the lock interface is able to detect Deadlock circumstances and throws unchecked exception.

18

The Executor and Executor Service

• Before Java 5.0, Threads' execution cycles are tied to the code they actually perform.

• Executor interface defines a means of supplying threads to an object (which implements the Executor interface), and letting that object deal with timing and running of the threads.

• we need to add Runnable objects to the Executor (which generally adds them to an internal queue), and the Executor then uses its own threads to peel off the objects and run them.

19

Executor Service

• It extends the Executor and adds the ability to execute Callable objects.

• Callable is something like Runnable.It puts code in call() instead of run().

• Here we have to submit the task which returns the future object that is parameterized with the type of result.

20

Blocking Queues New feature in Java 5.0 Defines put() and take() methods.

ArrayBlocking Queue : -Fixed capacity LinkedBlocking Queue: -bsaed on linked list data structure. -default size :unbounded PriorityBlockingQueue: -unbounded -not a FIFO queue, it orders its elements based on a

comparator object.

21

• DelayedQueue: -It implements Delayed interface. -It orders the elements by how long they

are delayed. -elements can not be removed until their

delay has elapsed.SynchronousQueue: -zero capacity queue. -each put must wait for a take, and vice versa

22

Atomic Variables

It support lock-free thread-safe programming on single variables.

Problems with locking: With locking, if one thread attempts to acquire a lock that is

already held by another thread, the thread will block until the lock becomes available.

Lock has some other hazards as well, such as deadlock (which can happen when multiple locks are acquired in an inconsistent order).

Locks are simply a relatively "heavyweight" for managing a simple operation such as incrementing a counter. It would be nice if there were a finer-grained mechanism for reliably managing concurrent updates to individual variables.

23

Hardware Synchronization

most modern processors include support for multiprocessing.They have instruction set supporting the multiprocessing.

CAS(compare and swap):mem location, expected value , new value

CAS allows an algorithm to execute without fear of another thread modifying the variable in the meantime, because if another thread did modify the variable, the CAS would detect it (and fail) and the algorithm could retry the operation.

24

a lock-free algorithm requires only that some thread always make progress.

The atomic variable classes all expose a compare-and-set primitive (similar to compare-and-swap), which is implemented using the fastest native construct available on the platform (compare-and-swap).

if ten threads each execute some operation once, in the worst case each thread will have to retry at most nine times.

25

• public class Counters{

AtomicInteger count=new AtomicInteger(5); public int getCount(){ int result; do{ result=count.get(); } while(!count.compareAndSet(result,result+1) ); return result;}}

26