Fernando Fernando - 4 days ago 5
Java Question

Java Threads and high cpu usage

I've done some search here and couldn't find an answer, so I think it's better to ask.
I'm running a little bit expensive algorithm in a simple Java swing application. Let me describe the structure:

In my

JPanel
run()
method:

public void run() {
while(true) {
Algorithm alg = new Algorithm(signal);
new Thread(alg).start();

//Wait for algorithm to finish
signal.await(alg);

updateInterface();

Thread.sleep(60L);
}
}


Algorithm loops through the pixels of a .JPG file, then loops through another large Integer array (length ~ 12000) and returns. There are very no extra expensive calculationslot. I call
Thread.sleep(60L)
in the Algorithm
run()
method also.

The
udpateInterface()
method is very fast, just draw some
java.awt.Polygon
objects.

Even though I'm calling
Thread.sleep(60L)
, the CPU usage is about 160% on my Mac Book (2.4 GHz Intel Core 2 Duo, Mem 4GB 1067).

Is there a way I can run this without melting my computer? I'm using
CountDownLatch
as
a wait notify mechanism.

Thanks!

Answer

I would use the following pattern to schedule a repeating task.

private ScheduledExecutorService executorService = null;

public void start() {
    if (executorService != null && !executorService.isShutdown()) return;

    executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                Algorithm alg = new Algorithm(signal);
                alg.run();
                updateInterface();
            }
        }, 0, 60, TimeUnit.MILLISECONDS);
}

public void stop() {
    if (executorService != null)
        executorService.shutdown();
}
Comments