So I am trying to delete a list having n number of objects and thereby I divided the list in 4 parts and let it to be deleted in parallel. The intention here is to do it in parallel so as to make it fast rather than sequential. deleteObject(x) can be assumed as an API which finally deletes an object has the code to take care of concurrency. It returns true on successful delete and false otherwise
I have few question here
- So as I have 4 parallel method which I am executing though invokeAll and there are 4 threads declared by Executors.newFixedThreadPool(4) would there always be 1 thread be assigned to 1 method?
- Do I need to synchronize and use volatile for iterator 'i' in the for loop of parallelDeleteOperation() method. The reason I am asking this is supposing if 1st thread has not completed its task (deleting listDir1 and the for loop has not completed) and supposing in midway it got context switch and 2nd thread starts executing the same task(deleting listDir1). Just wondering if 2nd thread can get IndexOutOfBound exception in this case.
- Is there any advantage of dividing list in 4 parts and executing this rather than having multiple threads executing delete operation on a very big list.
If one of the operation of ExecutorService returns false then on the whole deleteMain() API would return false
public boolean deleteMain(List<Integer> listDir) { if(listDir.size()<4){ return parallelDeleteOperation(listDir); } final List<Integer> listDir1 = listDir.subList(0, listDir.size() / 4); final List<Integer> listDir2 = listDir.subList(listDir.size() / 4, listDir.size() / 2); final List<Integer> listDir3 = listDir.subList(listDir.size() / 2, (listDir.size()/ 4) *3); final List<Integer> listDir4 = listDir.subList((listDir.size()/ 4)*3, listDir.size());` Set<Callable<Boolean>> callables = new HashSet<Callable<Boolean>>(); callables.add(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return parallelDeleteOperation(listDir1); } }); callables.add(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return parallelDeleteOperation(listDir2); } }); callables.add(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return parallelDeleteOperation(listDir3); } }); callables.add(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return parallelDeleteOperation(listDir4); } }); ExecutorService service = Executors.newFixedThreadPool(4); try { List<Future<Boolean>> futures = service.invokeAll(callables); for(Future<Boolean> future : futures){ if( future.get() != true) return future.get(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }finally{ service.shutdown(); } return true; } public boolean parallelDeleteOperation(List<Integer> listDir) { for (int i = 0; i < listDir.size(); i++) { int x = listDir.get(i); deleteObject(x); if(deleteObject(x)!=true) return false; } return true; }