Multithreading in Java
Date: Sep 2014
Level: Intermediate


Company: Apple
Question Title: Multithreading in Java
Language: Java

How can we divide a large file among multithreads to process it? If we are running a multithreaded application and input is a large file and we have to provide each thread a part of the file to make it fast. How we can achieve it in java?

Multithreading can be achieved using fork and join. Keep dividing the file based on lines and invoking the fork.

Some types of algorithms exist that require tasks to create subtasks and communicate with each other to complete. Those are the "divide and conquer" algorithms, which are also referred to as "map and reduce".The idea is to split the data space to be processed by an algorithm into smaller, independent chunks. That is the "map" phase. In turn, once a set of chunks has been processed, partial results can be collected to form the final result. This is the "reduce" phase.

ForkJoinTask objects support the creation of subtasks plus waiting for the subtasks to complete. With those clear semantics, the executor is able to dispatch tasks among its internal threads pool by "stealing" jobs when a task is waiting for another task to complete and there are pending tasks to be run.

ForkJoinTask objects feature two specific methods:
1. The fork() method allows a ForkJoinTask to be planned for asynchronous execution. This allows a new ForkJoinTask to be launched from an existing one.
2. In turn, the join() method allows a ForkJoinTask to wait for the completion of another one.

Cooperation among tasks happens through fork() and join().
All Questions