Runnable, Callable, FutureTask, CyclicBarrier and CountDownLatch in Java

Difference between interfaces Runnable and Callable

  • The Runnable interface was introduced in Java 1.0, and the Callable interface was introduced in Java 5.0 as part of the java.util.concurrent library;
  • Classes that implement the Runnable interface must implement the run() method to complete the task. Classes that implement the Callable interface - the call() method;
  • Runnable.run() method does not return any value, Callable.call() returns a Future object that can contain the result of calculations;
  • The run() method cannot throw checked exceptions, while the call() method can.

FutureTask

FutureTask is a cancelable asynchronous computation in a parallel Java application. This class provides the underlying Future implementation, with methods for starting and stopping the calculation, methods for querying the status of the calculation, and retrieving the results. The result can only be obtained when the computation is complete; the getter will block if the computation is not yet complete. FutureTask objects can be used to wrap Callable and Runnable objects. Since FutureTask implements Runnable, it can be passed to Executor for execution.

Differences between CyclicBarrier and CountDownLatch

CountDownLatch allows any number of threads in a block of code to wait until a certain number of operations in other threads have completed before they are "released" to continue their activity. The CountDownLatch(int count) constructor must pass the number of operations that must be performed in order for the lock to "release" blocked threads.

An example of a CountDownLatch from life is the gathering of an excursion group: until a certain number of people are gathered, the excursion will not start.

CyclicBarrier implements the Barrier sync pattern. A circular barrier is a synchronization point at which a specified number of concurrent threads meet and block. Once all streams have arrived, the optional action is taken (or not performed if the barrier was initialized without it), and after it is completed, the barrier breaks and the waiting streams are "released". The barrier constructors CyclicBarrier(int parties) and CyclicBarrier(int parties, Runnable barrierAction) must be passed the number of parties that must "meet", and, optionally, the action that must occur when the parties meet, but before they are "released".

CyclicBarrier is an alternative to the join() method, which "collects" threads only after they have run.

CyclicBarrier is similar to CountDownLatch, but the main difference between them is that you can use the "lock" only once - after its counter reaches zero, and the "barrier" can be used repeatedly, even after it "breaks".


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed