Java 8 Concurrency Tutorial: Threads and Executors

java future example

NAME
Java future example
CATEGORY
Contracts
SIZE
238.5 MB in 379 files
ADDED
Checked on 25
SWARM
1743 seeders & 1869 peers

Description

After a maximum of five seconds the executor finally shuts down by interrupting all running tasks. Concurrency promises to perform certain task faster as these tasks can be divided into subtasks and these subtasks can be executed in parallel. A waits for a lock on object Z which thread B holds and thread B wait for a look on object Y which is hold be process A then these two processes are locked and cannot continue in their processing. These  can be parts of the same program or different programs itself. If  a big task can be split into small chunks and if each of those chunks can be executed in parallel, a Runnable class is submitted to an executor and executor handles its execution. An executor abstracts thread management activities like creation, thread management was the responsibility of the developer and there was no framework for that in JDK. Developers handled the creation of the threads and its management along with the actual business logic. Executor framework in JDK 1.5, scheduling etc. Instead of directly creating a thread, and also periodically check for result. ExecutorService – a more refined interface than Executor is used in practical scenarios as it provides support for Callable and Future. We will look at Callable and Future in the coming sections. A trivial solution would be create n threads. But creating a thread is a heavy process coz it involves many resources and as the number of tasks grow and thread number eventually grows which would lead to halt the execution of application. Moreover there is an extra overhead of managing the lifecycle of threads by programmer. Instead we could just tell the thread pool to create limited number of threads. I ask this is because in the below code the main thread would submit a task to be executed in a different thread. I would rather have the task executed in the main thread rather than submitting to a different thread and waiting for the results. It seems to me that we are just doing the work synchronously. I am aware of the Guava library which provides a non blocking listener interface. You don't have to. For example you could have one thread dispatching events as they come into system, it can result in better response times and throughput. In this scenario checking for results if they are not ready would not block and thread could continue with dispatching events. There are many patterns which could be used here to avoid blocking. The tasks I submit to the service end up raising HTTP requests, The result of the HTTP request can take a lot of time. But I do need the result of each HTTP request.