This month, I have a project to make a kind of bot application. It's a console application that run on a server. This application doesn't have any heavy algorithm but just check a database periodically and run some simple function. When I run this application, the CPU usage of my server is increasing into 100%. I was thinking that it's caused by the function which run periodically. I don't have any idea about this.
But, one of my friend in my laboratory said that it's caused by while function which doesn't use any kind of usleep function. He said, in C programming, if we make an application using while function for forever (e.g. using while(1){<some source code>}), it will cause a high CPU usage.
After that, I looked for a kind of usleep function in Java because my application is a Java console application. I found that we can use sleep function from Thread class. I made a simple program to check the differences. This is the program.
public static void main(String[] args) throws InterruptedException {
int i=0;
while(true)
{
i++;
}
}
}
When I checked my CPU usage using Windows Task Manager I got this.
Then, I added a sleep function into my source code. It's just sleep for 10ms.
public class Testsleep {
public static void main(String[] args) throws InterruptedException {
int i=0;
while(true)
{
i++;
Thread.sleep(10)
}
}
}
The result was like this.
After that, I fixed my project application and got the desired result. I hope this information can be useful for you.
keren mang! hahaha
ReplyDeletesmoga bermanfaat pi, haha..
Delete