I have a long-running task of creating a bitmap saving it and recreating more bitmaps which I was doing on a single background thread
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(() -> {...bitmap work ...}
But it's taking really long time to process all the bitmaps so I created a thread pool to use multithreading to speed up the task.
private final int cores = Runtime.getRuntime().availableProcessors();
private final ExecutorService executor = Executors.newFixedThreadPool(cores + 1);
for (int i = 0; i < totalPage; i++) {
Runnable runnable = () -> {...bitmap work ...}
executor.submit(runnable);
}
But whenever I am using more than 1 thread it gets stuck randomly on some task(say 7 out of 127) there is no error or anything it just doesn't process any more tasks. I can view the pending task in the executor queue. But If I changed the thread pool to use 1 thread, it works without any problem and processes all tasks.
Here is the full actual code
ExecutorService executor = Executors.newFixedThreadPool(cores + 1);
List<Future<?>> futureList = new ArrayList<>();
boolean allDone = false;
try {
//Convert pdf to Bitmap
ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(new File(pdfFileName), ParcelFileDescriptor.MODE_READ_ONLY);
PdfRenderer pdfRenderer = new PdfRenderer(parcelFileDescriptor);
int totalPage = pdfRenderer.getPageCount();
final int[] counter = {1};
for (int i = 0; i < totalPage; i++) {
int finalI = i;
String finalOriginalPdfName = originalPdfName;
String finalGeneratedPdfName = generatedPdfName;
Runnable runnable = () -> {
//pd.setMessage("Processing page " + (finalI + 1) + " of " + totalPage);
PdfRenderer.Page page = pdfRenderer.openPage(finalI);
Bitmap pageBitmap = Bitmap.createBitmap((300 * page.getWidth()) / 72, (300 * page.getHeight()) / 72, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(pageBitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(pageBitmap, 0, 0, null);
page.render(pageBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
page.close();
//Crop bitmaps and temporarily store on app data directory
for (int k = 0; k < SlipBoundingBox.Y.length; k++) {
for (int j = 0; j < SlipBoundingBox.X.length; j++) {
Bitmap slipBitmap = Bitmap.createBitmap(pageBitmap, SlipBoundingBox.X[j], SlipBoundingBox.Y[k], SlipBoundingBox.WIDTH, SlipBoundingBox.HEIGHT);
//Filename formation originalPdfName_generatePdfName_pdfPageIndex_x_y.extension
File slip = new File(
getExternalFilesDir("slips")
+ "/"
+ finalOriginalPdfName
+ "_"
+ finalGeneratedPdfName
+ "_"
+ finalI +
"_"
+ SlipBoundingBox.X[j]
+ "_"
+ SlipBoundingBox.Y[k]
+ "_.jpg");
try (FileOutputStream out1 = new FileOutputStream(slip)) {
slipBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out1);
} catch (IOException e) {
e.printStackTrace();
}
slipBitmap.recycle();
}
}
pageBitmap.recycle();
pd.setMessage("Processed " + counter[0] + " of " + totalPage + " pages");
counter[0]++;
};
Future<?> future = executor.submit(runnable);
Log.d(TAG, "processPdf: " + future.isDone());
futureList.add(future);
}
//Todo close pdfrender on all page processed
//pdfRenderer.close();
} catch (Exception e) {
e.printStackTrace();
}