Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Multithreading Concepts

4,232 views

Published on

Published in: Technology, Education
  • Be the first to comment

Multithreading Concepts

  1. 1. ARVIND KRISHNAA J CSE 'A' III YEAR MULTITHREADING CONCEPTS
  2. 2. CONTENTS <ul><li>Thread safe collections
  3. 3. Executors
  4. 4. Synchronizers
  5. 5. Threads and swing </li></ul>
  6. 6. THREAD SAFE COLLECTIONS <ul><li>Multiple concurrently running threads modifying a data structure may possibly damage it.
  7. 7. Choices to avoid this are: </li><ul><li>Supplying a lock for the data structure
  8. 8. Choose a thread safe implementation of the data structure </li></ul></ul>
  9. 9. AVAILABLE THREAD SAFE COLLECTIONS <ul><li>BLOCKING QUEUES
  10. 10. EFFICIENT MAPS
  11. 11. SETS </li></ul>
  12. 12. BLOCKING QUEUES <ul><li>WHERE CAN IT BE USED : Consider the case of the producer-consumer problem.
  13. 13. One thread insert items into the queue. Another removes an item.
  14. 14. 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. </li></ul>
  15. 15. BLOCKING QUEUES (contd) <ul><li>Methods available : java.util.concurrent
  16. 16. (1) Constructors available : </li><ul><ul><li>Interface BlockingQueue<E> </li></ul><li>(i) ArrayBlockingQueue(int capacity)
  17. 17. (ii) ArrayBlockingQueue(int capacity,boolean fair) </li><ul><li>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. </li></ul><li>(iii) LinkedBlockingQueue()
  18. 18. LinkedBlockingDeque()
  19. 19. LinkedBlockingQueue(int capacity)
  20. 20. LinkedBlockingDeque(int capacity) </li></ul></ul>
  21. 21. BLOCKING QUEUES(contd) <ul><ul><li>DelayQueue(): Creates a new unbounded blocking queue in which only those elements whose delay has expired can be removed from the queue.
  22. 22. PriorityBlockingQueue()
  23. 23. PriorityBlockingQueue(int initialcapacity)
  24. 24. (initial capacity is 11 by default)
  25. 25. PriorityBlockingQueue(int initialcapacity,Comparator <? super E> comparator> </li></ul></ul>
  26. 26. Important Methods <ul><li>Blocking queues can be used as
  27. 27. (a) Thread management tool
  28. 28. (b) Synchronization tool
  29. 29. (c) Simple data structure
  30. 30. Methods :
  31. 31. (i) boolean add(E o) throws IllegalStateException: Adds the specified element to the queue
  32. 32. (ii)E remove() throws NoSuchElementException: Deletes an element from the queue </li></ul>
  33. 33. BLOCKING QUEUES(contd) <ul><li>boolean offer(E o)
  34. 34. boolean offer(E o , long timeOut,TimeUnit unit)
  35. 35. 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.
  36. 36. boolean poll()
  37. 37. boolean poll(long timeOut,Timeunit unit)
  38. 38. Tries for ”timeOut” time units to remove an element from the head of the queue. If not possible returns with an error. </li></ul>
  39. 39. BLOCKING QUEUES (contd) <ul><li>void put(E o): Adds an element to the queue. Blocks if the queue is full.
  40. 40. E take(): Removes and returns the header element. Blocks if the queue is empty.
  41. 41. E element() throws NoSuchElementException: Returns the header element.
  42. 42. E peek(): Returns the header element. Returns null if queue is empty. </li></ul>
  43. 43. Other thread safe collections (overview) <ul><li>ConcurrentHashMap: Atomic operations on a set of associations.
  44. 44. Supports a large number of readers and writers
  45. 45. Methods:
  46. 46. (a) putIfAbsent(key,value)
  47. 47. (b) remove(key,value)
  48. 48. (c) replace(key,oldvalue,newvalue) </li></ul>
  49. 49. (contd) <ul>Constructors: (i) ConcurrentHashMap<K,V> () (ii) ConcurrentHashMap<K,V>(int initialcapacity) (iii) ConcurrentHashMap<K,V>(int initialcapacity,float loadfactor,int concurrencylevel) </ul>
  50. 50. (contd) <ul><li>ConcurrentSkipList : Sorted hash map
  51. 51. ConcurrentLinkedQueue : Unbounded non-blocking queue that can be safely accessed by multiple threads.
  52. 52. CopyOnWriteArrayList and CopyOnWriteArraySet
  53. 53. Useful if the number of iterators on the base array outnumber the number of mutators.
  54. 54. Each iterator has a reference to the old array. </li></ul>
  55. 55. Older Thread Safe Collections <ul><li>Java SE 1.2
  56. 56. (a) Vector
  57. 57. (b) Hashtable
  58. 58. Synchronization Wrapper
  59. 59. List <E> syncharraylist=Collections.synchronizedList(new ArrayList <E> ());
  60. 60. Map<K,V> synchHashMap=Collections.synchronizedMap(new HashMap <K,V> ()); </li></ul>
  61. 61. EXECUTORS <ul><li>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.
  62. 62. Methods :
  63. 63. (a) newCachedThreadPool() : Constructs a thread pool that executes each task immediately.using an existing idle thread when available and creating a new thread otherwise.
  64. 64. (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
  65. 65. (c) newSingleThreadExecutor() : A ”pool” with a single thread that executes the submitted tasks sequentially. </li></ul>
  66. 66. Thread Pools (contd) <ul>The above three methods return an object of the ThreadPoolExecutor class that implements the ExecutorService interface. <li>Submitting a task to the Thread pool
  67. 67. A runnable task can be submitted to the thread pool to execute its run() method.
  68. 68. (i) Future<?> submit(Runnable task)
  69. 69. (ii) Future<T> submit(Runnable task,T result)
  70. 70. (iii) Future<T> submit(Callable <T> task) </li></ul>
  71. 71. Using the Thread Pool <ul><li>Call the static newCachedThreadPool or newFixedThreadPool method of the Executors class.
  72. 72. Call submit to submit Runnable or Callable objects
  73. 73. To manipulate the tasks use the returned Future objects
  74. 74. Call shutdown when no more tasks need to be submitted </li></ul>
  75. 75. Scheduled Execution <ul>The ScheduledExecutorService interface has methods for scheduled or repeated executions of tasks. <li>Methods:
  76. 76. (a) newScheduledThreadPool(int threads): Returns a thread pool that uses the given number of threads to schedule tasks.
  77. 77. (b) newSingleThreadScheduledExecutor(): Returns an executor that schedules tasks in a single thread. </li></ul>
  78. 78. Scheduling threads <ul><li>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.
  79. 79. Methods:
  80. 80. ScheduledFuture<V> schedule(Callable <V> task,long time,TimeUnit unit)
  81. 81. ScheduledFuture<?>schedule(Runnable task,long time,TimeUnit unit)
  82. 82. ScheduledFuture<?>scheduleAtFixedRate(Runnable task,long initialDelay,long period,TimeUnit unit)
  83. 83. ScheduledFuture<?> scheduleWithFixedDelay(Runnable task,long initialDelay,long delay,TimeUnit unit) </li></ul>
  84. 84. Controlling Group of Tasks <ul><li>An executor can be used to control a group of tasks
  85. 85. Methods available:
  86. 86. T invokeAny(Collection <Callable<T>> tasks)
  87. 87. T invokeAny(Collection <Callable<T>> tasks,long timeout,Timeunit unit)
  88. 88. List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
  89. 89. List<Future<T>> invokeAll(Collection<Callable<T>> tasks,long timeOut,TimeUnit unit) </li></ul>
  90. 90. Other methods <ul><li>ExecutorCompletionService(Executor e)
  91. 91. Constructs an executor completion service that collects the results of the given executor
  92. 92. Future<T> submit(Callable<T> task)
  93. 93. Future<T> submit(Runnable task,T result):
  94. 94. Submits a task to the underlying executor
  95. 95. Future<T> take() : Removes the next completed result,blocking if no completed results are available.
  96. 96. Future<T> poll()
  97. 97. Future<T> poll(long time,TimeUnit unit) : removes the next completed result or null if no completed results are available. </li></ul>
  98. 98. Synchronizers <ul><li>Synchronizers : Predefined classes that manage a set of collaborating threads. </li></ul>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
  99. 99. 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
  100. 100. Methods <ul><li>CyclicBarrier :
  101. 101. (1)CylicBarrier(int parties)
  102. 102. (2)CyclicBarrier(int parties,Runnable barrierAction)
  103. 103. (3)int await()
  104. 104. (4) int await(long time, TimeUnit unit):
  105. 105. 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. </li></ul>
  106. 106. CountDownLatch <ul>(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. </ul>
  107. 107. Exchanger <ul>(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. </ul>
  108. 108. SynchronousQueue <ul>(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. </ul>
  109. 109. Semaphore <ul>(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. </ul>
  110. 110. Threads and Swing <ul><li>Threads can be used to perform some time-consuming work while user interacts with the interface
  111. 111. Swing is not ”thread safe”
  112. 112. If user interface elements are manipulated from multiple threads then the user interface can become corrupted
  113. 113. Running time consuming tasks:
  114. 114. (a) If an action takes a long time , do it in a separate worker thread and never in the event dispatch thread
  115. 115. (b) Do not touch Swing components in any thread other than the event dispatch thread
  116. 116. Use the invokeLater() or the invokeAndWait() methods to update swing components when needed. </li></ul>
  117. 117. EventQueue methods <ul>(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. </ul>
  118. 118. Thread Safe Swing components <ul><li>Safely add and remove event listeners in any thread. The listener methods wil be invoked in the event dispatch thread
  119. 119. Small number of Swing methods are thread safe
  120. 120. (a) JtextComponent.setText
  121. 121. (b) JtextArea.insert
  122. 122. (c) JtextArea.append
  123. 123. (d) JtextArea.replaceRange
  124. 124. (e) Jcomponent.repaint
  125. 125. (f) Jcomponent.revalidate </li></ul>

×