Database Reference
In-Depth Information
TotalSegments
variable decides the number of segments as well as the number of
worker threads to be created for this parallel scan request. Inside the
for
loop, we instan-
tiate the
ParallelScanner
class (created by us for parallel scanning) by calling the
parameterized constructor with the parameters we will discuss later. The last two paramet-
ers are of much importance; the
totalSegments
variable has been discussed already.
The variable segment is used to provide information to the
ParallelScanner
thread,
to which the worker thread that does this scan result belongs.
After this, we call the execute method of the
ExecutorService
class by passing the
ParallelScanner
instance. This will invoke the run method of the
Paral-
lelScanner
class. Since the instance is also passed while calling the execute method,
this operation is thread-safe.
After initializing all the three worker threads, we will check whether the thread has fin-
ished its operation (and waiting for termination) or any exception occurred. In both the
cases, we kill all the threads using the
shutdownNow
method of the
ExecutorSer-
vice
class. Take a look at the following code:
private static void parallelScan() {
int scanItemLimit = 100;
int totalSegments = 3;
ExecutorService executor = Executors
.newFixedThreadPool(totalSegments);
for (int segment = 0; segment < totalSegments; segment++)
{
ParallelScanner scanTask = new ParallelScanner(client,
scanItemLimit, totalSegments, segment);
// Execute the task
executor.execute(scanTask);
}
try {
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();