0

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

Kingsley Reuben
  • 145
  • 2
  • 12
  • 1
    50% on a single or dual core cpu?:) i'm guessing its on a dual core. – Quamis Dec 14 '10 at 14:12
  • @Quamis So the answer is to get more cores. – Tom Hawtin - tackline Dec 14 '10 at 14:16
  • i'm commenting on your question, the answers section is down the page. I'm trying to poing out that you might have posted wrong data. Your algorithm seems to calculate the md5sum of a file. This is a very intensive CPU+disk task. So i'm assuming your CPU should be 100%. You said 50%, which leads me to think that you have a dual core system, and the actual cpu(core) usage in this case would be 100% – Quamis Dec 14 '10 at 14:19
  • The machine has dual core processors. – Kingsley Reuben Dec 14 '10 at 14:35

2 Answers2

2

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.

Donut
  • 110,061
  • 20
  • 134
  • 146
  • This code is implemented in a Servlet to check the uploaded file's integrity. 50 to 100 files will be uploaded simultaneously to the server from a set of 10k files. – Kingsley Reuben Dec 14 '10 at 14:39
0

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

start /low your_executable
barti_ddu
  • 10,179
  • 1
  • 45
  • 53