Question

I'm using following code to get the Checksum of a file. It uses 50% of CPU during calculations.

MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("C:\\Temp\\Small\\Movie.mp4"); // Size 700 MB

byte [] buffer = new byte [blockSize];
int numRead;
do 
{
 numRead = is.read(buffer);
 if (numRead > 0) 
 {
  md.update(buffer, 0, numRead);
 }
} while (numRead != -1);

byte[] digest = md.digest();

What can be done to reduce the code from using maximum CPU other than Thread.sleep(ms)

regards, Kingsley Reuben J

Was it helpful?

Solution

You could use the Thread.setPriority(int newPriority) method to reduce the thread's priority. This will result in other higher-priority threads being executed more often. However, your MD5 will not be calculated as quickly as if you left the priority alone -- why wouldn't you want this calculation to complete as quickly as possible?

EDIT: Here is a "Fast MD5" implementation, which boasts a significant performance increase (26% faster on average) over Java's default java.security.MessageDigest implementation. See the author's page for detailed information, including code examples and benchmarks. The code is available under the GNU LGPL 2.1 license.

OTHER TIPS

I'd rather dedicate priority management to os, for windows you could start your app with

start /low your_executable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top