Search code examples
androidencryptionaesjitbouncycastle

Bouncycastle AES 256 multithreading decryption speed degradation because of JIT


I am writing application that encrypts photos and though it need decrypt and show thumbnails in gallery like activity. Then of course you can click and see full sized image in different activity. I am using AES/CBC/PKCS7Padding cipher with 256 bit key. I derive cipher key using PBEWithSHA256And256BitAES-CBC-BC and store it into memory. Then all threads that need to make encryption/decryption is using that key from memory initializing Cipher object with it.

So here is my problem. When I decrypt many images simultaneously (let's say I need to show up gallery) and after I try to decrypt full sized image, it's extremely slow. On the other hand if I decrypt just one image (no matter what size), then go to gallery then decrypt full size image it is very fast.

I am really confused.

So what I am doing wrong? Maybe Bouncy Castle Crypto library is not thread safe?

UPDATE: I've found out this problem is related to JIT. Disabling JIT totally eliminates any processing speed difference. Can anyone help to understand how to optimize code to force JIT compile right part of the code when decrypting photos with multithreading to gain same speed as if decrypting only one photo at the beginning?


Solution

  • From our discussion above, a likely culprit in the performance degradation is the high number of worker threads. One possible method for limiting the number of threads is to use a fixed (or capped) thread pool, using the classes found in java.util.concurrent.

    You could create a fixed thread pool execution service using a suitable Executors static factory method. Then, you can create asychronous tasks for decrypting individual thumbnails and populating the GridView cells using the returned ExecutorService instance's submit() method.

    Another possibility may be the new Loaders API (developer.android.com), but I am not sure. I am reading about them right now for my own use. So you may want to check the documentation.

    Yet another alternative is in this answer (stackoverflow.com).