NSMutableArray<Future<?>> childFutures = new NSMutableArray<Future<?>>();
// Create the new TaskInfo
TaskInfo taskInfo = ERXEOControlUtilities.createAndInsertObject(ec, TaskInfo.class);
// Task start time
taskInfo.setStartTime(new NSTimestamp(startTime));
taskInfo.setStartNumber(_startNumber);
taskInfo.setDuration(_taskDuration);
ec.saveChanges();
_resultGid = ec.globalIDForObject(taskInfo);
_parentTaskPrimaryKey = (Integer) taskInfo.rawPrimaryKey();
// Initialize loop variables
long childTaskStartNumber = _startNumber;
int incrementQuantity = _childBatchBaseQuantity + Utilities.sharedRandom().nextInt(_childBatchBaseQuantity);
long childTaskEndNumber = childTaskStartNumber + incrementQuantity;
// Loop for a period of time
while (_elapsedTime < _taskDuration && !_isStopped) {
ChildPrimeTask childTask = new ChildPrimeTask(_nextChildIDValue, _resultGid, childTaskStartNumber, childTaskEndNumber);
_nextChildIDValue++;
boolean isRejected = true;
while (isRejected && !ChildTaskPool.EXECUTOR_SERVICE.isShutdown() && !_isStopped) {
try {
Future<?> future = ChildTaskPool.EXECUTOR_SERVICE.submit(childTask);
if (log.isInfoEnabled())
log.info("Submitted task corresponding to " + future);
isRejected = false;
childFutures.add(future);
// For the sake of demo, we assume all child tasks complete their work.
_endNumber = childTaskEndNumber;
} catch (RejectedExecutionException e) {
try {
Thread.sleep(2000);
removeCompletedFutures(childFutures);
} catch (InterruptedException e1) {
stop();
}
}
}
childTaskStartNumber = childTaskEndNumber + 1;
incrementQuantity = _childBatchBaseQuantity + Utilities.sharedRandom().nextInt(_childBatchBaseQuantity * 2);
childTaskEndNumber = childTaskStartNumber + incrementQuantity;
_elapsedTime = System.currentTimeMillis() - startTime;
// Update progress variables
_percentComplete = (double)(_elapsedTime) / (double)_taskDuration;
_status = wholeNumberFormatter.format(_count) + " numbers checked for prime qualification";
}
if (_isStopped) {
_status = "Stopped";
}
// Wait for all child tasks to finish
while (childFutures.count() > 0) {
removeCompletedFutures(childFutures);
Thread.sleep(1000);
}
// Complete the stats
// Refresh it since the object has been already updated (its relationship) and saved on ChildThreads
ERXEOControlUtilities.refreshObject(taskInfo);
taskInfo.setEndNumber(_endNumber);
taskInfo.setEndTime(new NSTimestamp());
taskInfo.setWorkflowState(TaskInfo.WORKFLOW_PRIME_CHECKED);
ec.saveChanges();
_resultGid = ec.globalIDForObject(taskInfo);