multithreading concepts

Download Multithreading Concepts

If you can't read please download the document

Upload: arvind-krishnaa

Post on 16-Apr-2017

4.024 views

Category:

Technology


0 download

TRANSCRIPT

ARVIND KRISHNAA J
CSE 'A' III YEAR

MULTITHREADING CONCEPTS

CONTENTS

Thread safe collections

Executors

Synchronizers

Threads and swing

THREAD SAFE COLLECTIONS

Multiple concurrently running threads modifying a data structure may possibly damage it.

Choices to avoid this are:Supplying a lock for the data structure

Choose a thread safe implementation of the data structure

AVAILABLE THREAD SAFE COLLECTIONS

BLOCKING QUEUES

EFFICIENT MAPS

SETS

BLOCKING QUEUES

WHERE CAN IT BE USED: Consider the case of the producer-consumer problem.

One thread insert items into the queue. Another removes an item.

FUNCTIONALITY: Causes a thread to block when an element is being added to a full queue (or) when an element is being removed from an empty queue.

BLOCKING QUEUES (contd)

Methods available: java.util.concurrent (1) Constructors available:Interface BlockingQueue

(i) ArrayBlockingQueue(int capacity)(ii) ArrayBlockingQueue(int capacity,boolean fair)fair - if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified.

(iii) LinkedBlockingQueue() LinkedBlockingDeque() LinkedBlockingQueue(int capacity) LinkedBlockingDeque(int capacity)

BLOCKING QUEUES(contd)

DelayQueue(): Creates a new unbounded blocking queue in which only those elements whose delay has expired can be removed from the queue.

PriorityBlockingQueue()

PriorityBlockingQueue(int initialcapacity)(initial capacity is 11 by default)

PriorityBlockingQueue(int initialcapacity,Comparator submit(Runnable task)(ii) Future submit(Runnable task,T result)(iii) Future submit(Callable task)

Using the Thread Pool

Call the static newCachedThreadPool or newFixedThreadPool method of the Executors class.

Call submit to submit Runnable or Callable objects

To manipulate the tasks use the returned Future objects

Call shutdown when no more tasks need to be submitted

Scheduled Execution

The ScheduledExecutorService interface has methods for scheduled or repeated executions of tasks.Methods: (a) newScheduledThreadPool(int threads): Returns a thread pool that uses the given number of threads to schedule tasks.(b) newSingleThreadScheduledExecutor(): Returns an executor that schedules tasks in a single thread.

Scheduling threads

A Runnable or Callable object can be passed to any of the following methods. They can be scheduled to run once after an initial delay or run periodically.Methods:

ScheduledFuture schedule(Callable task,long time,TimeUnit unit)

ScheduledFutureschedule(Runnable task,long time,TimeUnit unit)

ScheduledFuturescheduleAtFixedRate(Runnable task,long initialDelay,long period,TimeUnit unit)

ScheduledFuture scheduleWithFixedDelay(Runnable task,long initialDelay,long delay,TimeUnit unit)

Controlling Group of Tasks

An executor can be used to control a group of tasksMethods available:

T invokeAny(Collection tasks)

T invokeAny(Collection tasks,long timeout,Timeunit unit)

List invokeAll(Collection tasks)

List invokeAll(Collection tasks,long timeOut,TimeUnit unit)

Other methods

ExecutorCompletionService(Executor e)Constructs an executor completion service that collects the results of the given executor

Future submit(Callable task)

Future submit(Runnable task,T result):Submits a task to the underlying executor

Future take() : Removes the next completed result,blocking if no completed results are available.

Future poll()

Future poll(long time,TimeUnit unit) : removes the next completed result or null if no completed results are available.

Synchronizers

Synchronizers: Predefined classes that manage a set of collaborating threads.

ClassWhat it doesWhen to use

CyclicBarrierAllows a set of threads to wait until a predefined count of them has reached a common barrier and then optionally execute a barrier actionWhen a number of threads need to complete before their results can be used.

CountDownLatchAllows a set of threads to wait until a count has been decremented to 0When one or more threads need to wait until a specified number of events have occurred

Synchronizers (contd)

ExchangerAllows two threads to exchange objects when both are ready for the exchange.When two threads work on two instances of the same data structure , one by filling an instance and other by emptying the others

SemaphoreAllows a set of threads to wait until permits are available fot proceedingTo restrict the total number of threads that can access a resource. If permit count is one , use to block threads until another thread gives permission

SynchronousQueueAllows a thread to hand off an object to another threadTo send an object from one thread to another when both are ready,without explicit synchronization

Methods

CyclicBarrier:(1)CylicBarrier(int parties)(2)CyclicBarrier(int parties,Runnable barrierAction)(3)int await()(4) int await(long time, TimeUnit unit):Waits until all parties have called await on the barrier or until the timeout has been reached, in which case a TimeoutException is thrown. Upon success, returns the arrival index of this party. The first party has index parties - 1, and the last party has index 0.

CountDownLatch

(1) CountdownLatch(int count) : Constructs a countdown latch with the given count.(2) void await(): waits for this latch to count down to 0.(3) boolean await(long time, TimeUnit unit): Waits for this latch to count down to 0 or for the timeout to elapse. Returns true if the count is 0, false if the timeout elapsed(4) public void countDown(): counts down the counter of this latch.

Exchanger

(1) V exchange(V item)(2) V exchange(V item, long time, TimeUnit unit)Blocks until another thread calls this method, and then exchanges the item with the other thread and returns the other threads item. The second method throws a TimeoutException after the timeout has elapsed.

SynchronousQueue

(1) SynchronousQueue()(2) SynchronousQueue(boolean fair)Constructs a synchronous queue that allows threads to hand off items. If fair is true, the queue favors the longest-waiting threads.(3) void put(V item) : Blocks until another thread calls take to take this item.(4) V take(): blocks until another thread calls put. Returns the item that the other thread provided.

Semaphore

(1)Semaphore(int permits)(2)Semaphore(int permits, boolean fair)constructs a semaphore with the given maximum number of permits. If fair is true, the queue favors the longest-waiting threads.(3) void acquire() : Waits to acquire a permit.(4) boolean tryAcquire(): Tries to acquire a permit; returns false if none is available.(5) boolean tryAcquire(long time, TimeUnit unit): Tries to acquire a permit within the given time; returns false if none is available.(6) void release() : Releases a permit.

Threads and Swing

Threads can be used to perform some time-consuming work while user interacts with the interface

Swing is not thread safe

If user interface elements are manipulated from multiple threads then the user interface can become corruptedRunning time consuming tasks:(a) If an action takes a long time , do it in a separate worker thread and never in the event dispatch thread(b) Do not touch Swing components in any thread other than the event dispatch thread

Use the invokeLater() or the invokeAndWait() methods to update swing components when needed.

EventQueue methods

(1) static void invokeLater(Runnable runnable) causes the run method of the runnable object to be executed in the event dispatch thread after pending events have been processed.(2) static void invokeAndWait(Runnable runnable) causes the run method of the runnable object to be executed in the event dispatch thread after pending events have been processed. This call blocks until the run method has terminated.(3) static boolean isDispatchThread() returns true if the thread executing this method is the event dispatch thread.

Thread Safe Swing components

Safely add and remove event listeners in any thread. The listener methods wil be invoked in the event dispatch thread

Small number of Swing methods are thread safe(a) JtextComponent.setText(b) JtextArea.insert(c) JtextArea.append(d) JtextArea.replaceRange(e) Jcomponent.repaint(f) Jcomponent.revalidate

Muokkaa otsikon tekstimuotoa napsauttamalla

Muokkaa jsennyksen tekstimuotoa napsauttamallaToinen jsennystasoKolmas jsennystasoNeljs jsennystasoViides jsennystasoKuudes jsennystasoSeitsems jsennystasoKahdeksas jsennystasoYhdekss jsennystaso