• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Multithreading Concepts

Multithreading Concepts






Total Views
Views on SlideShare
Embed Views



2 Embeds 8

http://www.linkedin.com 6
https://www.linkedin.com 2



Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Multithreading Concepts Multithreading Concepts Presentation Transcript

      • Thread safe collections
      • Executors
      • Synchronizers
      • Threads and swing
      • 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
      • SETS
      • 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<E>
        • (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 <? super E> comparator>
    • Important Methods
      • Blocking queues can be used as
      • (a) Thread management tool
      • (b) Synchronization tool
      • (c) Simple data structure
      • Methods :
      • (i) boolean add(E o) throws IllegalStateException: Adds the specified element to the queue
      • (ii)E remove() throws NoSuchElementException: Deletes an element from the queue
    • BLOCKING QUEUES(contd)
      • boolean offer(E o)
      • boolean offer(E o , long timeOut,TimeUnit unit)
      • Tries for ”timeOut” time units to insert an element into the tail of the queue. If not possible returns with an error instead of throwing an exception.
      • boolean poll()
      • boolean poll(long timeOut,Timeunit unit)
      • Tries for ”timeOut” time units to remove an element from the head of the queue. If not possible returns with an error.
    • BLOCKING QUEUES (contd)
      • void put(E o): Adds an element to the queue. Blocks if the queue is full.
      • E take(): Removes and returns the header element. Blocks if the queue is empty.
      • E element() throws NoSuchElementException: Returns the header element.
      • E peek(): Returns the header element. Returns null if queue is empty.
    • Other thread safe collections (overview)
      • ConcurrentHashMap: Atomic operations on a set of associations.
      • Supports a large number of readers and writers
      • Methods:
      • (a) putIfAbsent(key,value)
      • (b) remove(key,value)
      • (c) replace(key,oldvalue,newvalue)
    • (contd)
        Constructors: (i) ConcurrentHashMap<K,V> () (ii) ConcurrentHashMap<K,V>(int initialcapacity) (iii) ConcurrentHashMap<K,V>(int initialcapacity,float loadfactor,int concurrencylevel)
    • (contd)
      • ConcurrentSkipList : Sorted hash map
      • ConcurrentLinkedQueue : Unbounded non-blocking queue that can be safely accessed by multiple threads.
      • CopyOnWriteArrayList and CopyOnWriteArraySet
      • Useful if the number of iterators on the base array outnumber the number of mutators.
      • Each iterator has a reference to the old array.
    • Older Thread Safe Collections
      • Java SE 1.2
      • (a) Vector
      • (b) Hashtable
      • Synchronization Wrapper
      • List <E> syncharraylist=Collections.synchronizedList(new ArrayList <E> ());
      • Map<K,V> synchHashMap=Collections.synchronizedMap(new HashMap <K,V> ());
      • Thread Pool: Contains a number of idle threads that are ready to run. Easier and less expensive to use a thread pool than continuously creating new threads.
      • Methods :
      • (a) newCachedThreadPool() : Constructs a thread pool that executes each task immediately.using an existing idle thread when available and creating a new thread otherwise.
      • (b) newFixedThreadPool() : Constructs a thread pool with a fixed size. If more tasks are submitted than available threads the unserved tasks are placed on a queue
      • (c) newSingleThreadExecutor() : A ”pool” with a single thread that executes the submitted tasks sequentially.
    • Thread Pools (contd)
        The above three methods return an object of the ThreadPoolExecutor class that implements the ExecutorService interface.
      • Submitting a task to the Thread pool
      • A runnable task can be submitted to the thread pool to execute its run() method.
      • (i) Future<?> submit(Runnable task)
      • (ii) Future<T> submit(Runnable task,T result)
      • (iii) Future<T> submit(Callable <T> 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<V> schedule(Callable <V> task,long time,TimeUnit unit)
      • ScheduledFuture<?>schedule(Runnable task,long time,TimeUnit unit)
      • ScheduledFuture<?>scheduleAtFixedRate(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 tasks
      • Methods available:
      • T invokeAny(Collection <Callable<T>> tasks)
      • T invokeAny(Collection <Callable<T>> tasks,long timeout,Timeunit unit)
      • List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
      • List<Future<T>> invokeAll(Collection<Callable<T>> tasks,long timeOut,TimeUnit unit)
    • Other methods
      • ExecutorCompletionService(Executor e)
      • Constructs an executor completion service that collects the results of the given executor
      • Future<T> submit(Callable<T> task)
      • Future<T> submit(Runnable task,T result):
      • Submits a task to the underlying executor
      • Future<T> take() : Removes the next completed result,blocking if no completed results are available.
      • Future<T> poll()
      • Future<T> 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.
      Class What it does When to use CyclicBarrier Allows a set of threads to wait until a predefined count of them has reached a common barrier and then optionally execute a barrier action When a number of threads need to complete before their results can be used. CountDownLatch Allows a set of threads to wait until a count has been decremented to 0 When one or more threads need to wait until a specified number of events have occurred
    • Synchronizers (contd) Exchanger Allows 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 Semaphore Allows a set of threads to wait until permits are available fot proceeding To 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 SynchronousQueue Allows a thread to hand off an object to another thread To 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 thread’s 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 corrupted
      • Running 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