Java Threads and high cpu usage - java

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!

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();
}

160% CPU usage is relative to a single core of your machine -- that is, the maximum possible on your machine is 200%, because it has two cores. You're not melting your processor.

There's no point starting another thread if all you're going to do afterward is make the current thread wait for the other one to finish. You might as well just run the algorithm in the thread you already have; either way, you won't proceeed to updateInterface() until the algorithm is done.
As others have pointed out, after the algorithm finishes and you update the UI, you're only waiting 60 milliseconds before starting the algorithm again. It sounds like your program is spending most of its time running the algorithm. That's fine if you need it to update the screen that quickly, but you might consider using a longer delay otherwise.
Also, you're starting a new thread each time through the loop. Does that thread run the algorithm once and then terminate, or does it run the algorithm in a loop? If you have a loop starting threads that are each long-running CPU-intensive loops, you might be accidentally running many copies of the algorithm at once. If you expect the algorithm thread to terminate after it signals you, you should join() it to make sure.

How much wait do you want? If you want to wait for 60 seconds, you should use 60000L, as the time is specified in milliseconds.

Related

thread parallel to other process java

i have periodic thread that runs every one second and refers the application. the problem is when the thread is running cpu usage goes up and program respond very bad it seems CPU fan is working with full power. maybe there is a problem with using a infinite while here. is there any other way for doing it?
Runnable r1 = new Runnable() {
public void run() {
try {
while (connect.isDisable()){
refresher(rx);
Thread.sleep(1000L);
}
} catch (InterruptedException iex) {}
}
};
Thread thr1 = new Thread(r1);
thr1.start();
if there an alternate way that thhis sets of functions run every one secounds parallel to other process and event handlers respond just like normal?
To begin with, thread is a sequence of execution of statements or code in a program and is nothing hardware. It is a flow of execution which takes place.
A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.
And yes, multiple threads may run at the same time if your CPU has more than one core. This will of course increase the CPU usage because multiple processes or sequence of codes are running at the same time. You are asking the CPU to perform 2 or more things at the same time and therefore, over usage is an obvious consequence.
About the fan, may be designed to run faster when CPU usage is higher so that the excess heat generated is driven out efficiently.

Heartbeat in Java: timerTask or thread.sleep()?

I want to implement a very simple client to server heartbeat in java. The most simple approach seems to be through sleep. Consider the metacode below.
class MyClass
Thread heartbeatThread = new Thread();
public void() startHeartBeat{
Thread.sleep(4000);
sock.write("H");
}
Is this an adequate solution, or are there pitfalls I'm not considering?
I've also considered using the java.util.Timer.scheduleAtFixedRate approach. Would this be more robust/reliable? If so, why? Here's an example (it's not as clean IMO):
class HeartBeat
{
Timer timer=new Timer();
public void scheduleHeartBeat(int delay, int period) {
timer.scheduleAtFixedRate( new HeartBeatTask(), delay, period);
}
}
class HeartBeatTaskextends TimerTask {
public void run() {
sock.write("H");
}
Will the second approach be granted higher priority?
Firstly, your Thread-based idiom will not schedule at fixed rate without an infinite loop.
That's one disadvantage too: you probably want to set some condition to exit the loop.
You also need to catch InterruptedException when invoking static Thread.sleep.
Another popular idiom for scheduled execution is by using a ScheduledExecutorService.
Find the 3 alternatives below:
Timer
// says "foo" every half second
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
System.out.println("foo");
}
}, 0, 500);
Pros: simple
Cons:
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up."
Docs here.
Infinite loop
new Thread() {
#Override
public void run() {
while (true) {
// Says "blah" every half second
System.out.println("blah");
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
// nope
}
}
}
}.start();
Pros: super simple. You can vary your recurring delay programmatically.
Cons: Thread.sleep is still
subject to the precision and accuracy of system timers and schedulers.
... and requires catching InterruptedException.
Docs here.
Also:
your infinite loop might require a (somehow potentially cumbersome) breaking condition
no initial delay setting unless applied manually before infinite loop, which would require another try / catch.
Executors
ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
es.scheduleAtFixedRate(
new Runnable() {
#Override
public void run() {
// Says "bar" every half second
System.out.println("bar");
}
},
0, 500, TimeUnit.MILLISECONDS);
Pros: this is the most recent feature of the 3. Very simple and elegant - you can also schedule Callables (not at fixed rate though) and re-use the ExecutorService. The documentation for java.util.Timer actually mentions ScheduledThreadPoolExecutor (implementing the ScheduledExecutorService interface) as a "more versatile replacement for the Timer/TimerTask combination".
Cons as documented:
If any execution of this task takes longer than its period, then subsequent executions may start late,
Docs here.
Yes, I don't know how timers are implemented internally, but what I do understand here is, if you use sleep, you will have to handle InterruptedException, and eating up that exception may not be a good practice. moreover timer tasks would be running within its thread space, and you have better control over it.
You can stop the timer any time if you want, In this case, you may not be able to do that
If you use the sleep approach, there are some issues to consider.
One is that the sleep time isn't exact, and you could have drift over time (maybe while your thread is sleeping another application hogs CPU and it takes longer than expected for your thread to send its heartbeat, now the next time the thread sends a heartbeat is delayed), your sleep time will be augmented by various things incrementally (you won't sleep for less than your sleep time but may frequently sleep for a bit more), and those increments will add up over time.
Another is that you could have a problem with the socket, you would have to write code to handle making a new connection.
The thread would need to be well-behaved and respond to interruption, or else be a daemon thread. If it had to share data across threads you'd need to be aware of memory visibility issues.
Using a timer would mean each launching of a task would have a fresh start and you wouldn't be vulnerable to accumulated delays or stale network connections.

Java: Recursive Thread Creation for a Thread Pool -> How to detect completion

I'm working on a program to play TicTac toe.
It will use a game tree search. However, first I need to assemble the game tree.
I want to parallelize this process, since it basically involves checking the current position, generating all the legal moves, and attaching these as nodes to the current node.
This is my first real foray into multithreading, and I keep running into problems.
Here is my move generation code:
#Override
public void run() {
for (int i = 1; i < 10; i++) { // try all cells
if (isMoveLegal(i)) {
Node newnode = new Node(currentNode,
Game.convertMoveToBin(i - 1));
currentNode.addChild(newnode);
if (Game.evaluateBoards(newnode.getBoards()) == 2) {
executor.submit(new MoveGenerationThread(currentNode,
newnode));
}
}
}
executor.shutdown();
}}
I have a static thread pool executor:
public static final ExecutorService executor = Executors.newFixedThreadPool(THREADS);
I tried using transient thread pools, but the program went beserk and ran out of threads.
Basically, what is happening is that a task is being run in the thread pool, and then each task is generating more tasks to run in separate threads.
The problem is knowing when everything finishes. I am not just running a simple loop where I can wait till the tasks are done, this is being done recursively. I've tried various methods of detecting completion including a CountDownLatch (doesn't work, I don't know how many tasks there are going to be), wait() (crashes, doesn't seem to be applicable to this situation), and shutdown(), which doesn't work either (I don't want to stop more tasks from being submitted).
I am a bit bewildered here, any ideas?
I think the answer might have something to do with Fork/Join, but I am not sure how to go about this.
Try java.util.concurrent.Phaser.
Use register() to increment the count as each task is created. At the end of each task, call arriveAndDeregister().

How to ensure a Thread won't delay in Java?

I wrote a multi threading programme, which have two to four thread at the same time.
One of the thread is time critical thread, it will be called every 500 milliseconds, it is not allow to delay more than 10 milliseconds. But when other thread have more loading, I find that some delay, around two millisecond is occurred. (Print the timestamp to show it) So, I worry that after running for a long time it will delay more than 10 milliseconds, except from check the timestamp, and adjust the looping interval to make sure the time is not delay more than 10 milliseconds, is there any way to make it safe?
Thanks.
Sounds like you need Real-Time Java
If timing is critical, I use a busy wait on a core which is dedicated to that thread. This can give you << 10 micro-second jitter most of the time. Its a bit extreme and will result in the logical thread not being used for anything else.
This is the library I use. You can use it to reserve a logical thread or a whole core. https://github.com/peter-lawrey/Java-Thread-Affinity
By using isolcpus= in grub.conf on Linux you can ensure that the logical thread or core is not used for any else (except the 100 Hz timer and power management which are relatively small and < 2 us delay)
You can set your threads priorities:
myCriticalThread.setPriority(Thread.MAX_PRIORITY);
otherThread.setPriority(Thread.NORM_PRIORITY); // the default
yetAnotherThread.setPriority(Thread.MIN_PRIORITY);
It won't really guarantee anything though.
There is no guarantee that your thread isn't delayed, because the OS may decide to give other processes precedence (unless you put effort in setting up a complete real-time system including a modified OS). That being said, for basic tasks, you should use a ScheduledExecutorService like this:
class A {
private final ScheduledExecutorService exe = Executors.newScheduledThreadPool(1);
public void startCriticalAction(Runnable command) {
this.exe.scheduleAtFixedRate(command, 100, 100, TimeUnit.MILLISECONDS);
}
public void shutdown() {
this.exe.shutdown();
}
}
The executor service will do its best to execute the task every 100ms. You should not develop this functionality yourself, because a lot of things can go wrong.
Creep up on the timeout:
waitFor(int timeout)
{
dateTime wallTimeEnd;
wallTimeEnd=now()+(msToDateTime(timeout));
int interval=timeout/2;
while(true){
if(interval>10){
sleep(interval);
interval=dateTimeToMs(wallTimeEnd-now()) / 2;
}
else
{
do{
sleep(0);
interval=dateTimeToMs(wallTimeEnd-now());
}while(interval>0);
}
}
This only wastes a core for 5-10ms

Constantly checking a port without a while loop

In a program (Java) I'm making I need to check for a specific pin in the parallel port. Whenever that pin goes from logical 0 to 1 (a positive edge clock) I have to read the data on the port and save it. This happens about every 10ms but can vary a little.
To do this I made a separate thread with a while loop that is constantly checking the port, but this makes the processor go nuts and I know it's because of the while loop. My question is, how can I constantly scan the port without using a processor intensive while loop? The program doesn't know precisely when a pin change will happen, only that it happens around every 10ms.
Fire a thread which is scheduled to execute the given Runnable at a fixed rate. You can use Timer#scheduleAtFixedRate() or ScheduledExecutorService#scheduleAtFixedRate() for this. The last one is preferred.
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new PortScanner(), 0, 10, TimeUnit.MILLISECONDS); // Run every 10 ms.
Where PortScanner can look like this:
public class PortScanner implements Runnable {
#Override
public void run() {
// Scan port here.
}
}
Don't forget to call scheduler.shutdown() at the moment your application exits, else the thread may hang.
There might be a better solution, but worst case you could just Thread.sleep for 1-2ms every iteration of the while loop.
It is really tricky to catch hardware interrupts when your code is not running as a part of operating system. What you can do is to put Thread.Sleep ( 5 ). This will sleep for 10 milliseconds, and will let the other threads run or just keep CPU idle and cool. Having 5 ms delay should be enough to ensure won't miss any clock ticks.
This would work when your clock is alternating between 10 ms high and 10 ms low. For other patterns you have to adjust the parameter accordingly.

Categories

Resources