473,324 Members | 2,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

why does my Java console program take up so much CPU time?

tekninja
I wrote a very simple instant messenger client but, unfortunately, since I am still a relatively new programmer I am not familiar with what causes a program to eat up so much CPU time. Currently at runtime my program takes up 11mb in memory and 90-100% cpu usage!!

Without posting all the code, what factors contribute to cpu usage? I am not really sure what information would help others troubleshoot my program, so please let me know which specific details would be useful to you and I will provide them.

Thank you very much for any help.
Sep 11 '07 #1
12 6086
kreagan
153 100+
I wrote a very simple instant messenger client but, unfortunately, since I am still a relatively new programmer I am not familiar with what causes a program to eat up so much CPU time. Currently at runtime my program takes up 11mb in memory and 90-100% cpu usage!!

Without posting all the code, what factors contribute to cpu usage? I am not really sure what information would help others troubleshoot my program, so please let me know which specific details would be useful to you and I will provide them.

Thank you very much for any help.
I experienced high CPU usage in very long for loops or never ending loops.

Because your program takes up so much memory, are you creating many objects? Like MANY objects? Many BIG objects? Let me give you an example. I had 1 project run out of memory (Java has a cap on how much memory is used). We had to store a graph of 100,000 nodes. Yes, 100,000 huge objects.

I also created a Sudoku solver that used large objects too - 89 of them. This program didn't take much memory.

Does anyone know if a stack will cause a memory increase?
Sep 11 '07 #2
There are several objects... mainly objects used to deal with network connectivity and IO.

However the program is basically one recurring loop (until the user quits the chat client). This is unavoidable since it must be constantly looping and dealing with asynchronous network input as well as user keyboard input...

I am guessing then it is this loop that causes the high CPU usage? Are there any strategies for minimizing CPU usage?
Sep 11 '07 #3
JosAH
11,448 Expert 8TB
There are several objects... mainly objects used to deal with network connectivity and IO.

However the program is basically one recurring loop (until the user quits the chat client). This is unavoidable since it must be constantly looping and dealing with asynchronous network input as well as user keyboard input...

I am guessing then it is this loop that causes the high CPU usage? Are there any strategies for minimizing CPU usage?
Are you actively waiting/checking whether or not some data is coming in from
the client(s)? If so, my bet would be on that for the high cpu utilization.

Better use separate threads per open socket and let them block in a read
method request. If the read blocks (because of no input) the thread will
relinguish the cpu and other threads will have a chance. Most of the time
none of them will be active.

kind regards,

Jos
Sep 12 '07 #4
kreagan
153 100+
If the read blocks (because of no input) the thread will
relinguish the cpu and other threads will have a chance.
Though that will definately need to be done for multiple clients, you can also block without threading.

I'm assuming you are using BufferReader.
Expand|Select|Wrap|Line Numbers
  1. while ((userInput = stdIn.readLine()) != null) { 
  2.   // do stuff
  3. }
This while loop will block also.
Sep 12 '07 #5
JosAH
11,448 Expert 8TB
Though that will definately need to be done for multiple clients, you can also block without threading.

This while loop will block also.
Sure, if a thread has compadres it doesn't suddenly start to behave differently;
reads will block if there's no incoming data available. The op should made his/her
threads block (read: relinguish control) when no data is available), whether there's
one thread or more of them.

kind regards,

Jos
Sep 12 '07 #6
kreagan
153 100+
The op should made his/her threads block (read: relinguish control) when no data is available), whether there's one thread or more of them.
Actually, I made this same mistake before.
Expand|Select|Wrap|Line Numbers
  1. while ( userInput == null ){
  2.         userInput = stdln.readLine();
  3. }
If I remember correctly (this was 2 years ago) the above code will never block; you must use the while condition I posted above.
Sep 12 '07 #7
Are you actively waiting/checking whether or not some data is coming in from
the client(s)? If so, my bet would be on that for the high cpu utilization.

Better use separate threads per open socket and let them block in a read
method request. If the read blocks (because of no input) the thread will
relinguish the cpu and other threads will have a chance. Most of the time
none of them will be active.

kind regards,

Jos
Thanks for the replies guys... that is exactly what I am doing. Unfortunately the solutions above, while making some sense are a little confusing to me (quite the programming nub unfortunately).


The client is very simple ( and the server likewise) there is only one socket connection (ie one host:port )

right now I have methods checking for network input and/or keyboard input in the same while loop... in fact the method handling keyboard and/or net io is so simple I may as well post it:

Expand|Select|Wrap|Line Numbers
  1. try {
  2.  
  3. while (!exit) {
  4.     if (scanKB.hasNextLine()) {
  5.         kbInput = scanKB.nextLine();
  6.         if (kbInput.equals("/quit")) {
  7.             switch (imc.disconnect()) {
  8.                 case NO_ERRORS:
  9.                     System.out.println("\nSuccessfully logged off");
  10.                     break;
  11.                 case IO_ERROR:
  12.                     System.out.println("\nError while logging off");
  13.                     break;
  14.             }
  15.             exit = true;
  16.         } else {
  17.             imc.sendMsg(kbInput);
  18.         }
  19.     }
  20.     if (imc.scanNet.hasNextMessage()) {
  21.         System.out.println(imc.printMsg(imc.scanNet.nextMessage()));
  22.     }
  23. }
  24.  
  25. } catch (NextDoesNotExistException e) {
  26.     System.out.println("Error");
  27. } catch (NullPointerException e) {}
So even with your examples above, I really am not sure what I could do with the above code to decrease CPU usage time...

EDIT: Ok, for some reason I cannot fix line 21 in my code above... for some reason it is posting a space in the nextMessage() method... no matter what I do I can't get it to post that line correctly... so please just realize that there shouldn't be a space there...

Also out of curiousity, how are you getting your code to post as java code with syntax coloring? I tried [JAVA][/JAVA] in place of [code] but that didn't work

Thanks!
Sep 12 '07 #8
Nepomuk
3,112 Expert 2GB
Also out of curiousity, how are you getting your code to post as java code with syntax coloring? I tried [JAVA][/JAVA] in place of [code] but that didn't work

Thanks!
I guess, I'm not the right one to answer the question about multithreading, as it's something I've just started learning myself, but I can help you with your forum-related question: Just use [code=java] instead of [code] (but close it with the normal closing tag). That will also work with xml, html and many others... check the Code tag list to find all of them.

Greetings,
Nepomuk
Sep 12 '07 #9
JosAH
11,448 Expert 8TB
So even with your examples above, I really am not sure what I could do with the above code to decrease CPU usage time...
Basically, what that while loop does is this:

Expand|Select|Wrap|Line Numbers
  1. while (<some condition>) {
  2.    if (<input from keyboard>)
  3.       processKeyboardInput();
  4.    if (<input from socket>)
  5.       processSocketInput();
  6. }
  7.  
Suppose no keyboard input nor socket input are available, i.e. nothing happens.
Can you see that loop running around in, well, loops, doing totally nothing?
That's where your CPU load comes from.

If you had two threads instead, one watching (and blocking for) the keyboard and
the other doing the same with the socket both threads would simply block if
no input were available and CPU usage would be down to almost zero.

kind regards,

Jos
Sep 13 '07 #10
kreagan
153 100+
Thanks for the replies guys... that is exactly what I am doing. Unfortunately the solutions above, while making some sense are a little confusing to me (quite the programming nub unfortunately).


The client is very simple ( and the server likewise) there is only one socket connection (ie one host:port )

right now I have methods checking for network input and/or keyboard input in the same while loop... in fact the method handling keyboard and/or net io is so simple I may as well post it:

Expand|Select|Wrap|Line Numbers
  1. try {
  2.  
  3. while (!exit) {
  4.     if (scanKB.hasNextLine()) {
  5.         kbInput = scanKB.nextLine();
  6.         if (kbInput.equals("/quit")) {
  7.             switch (imc.disconnect()) {
  8.                 case NO_ERRORS:
  9.                     System.out.println("\nSuccessfully logged off");
  10.                     break;
  11.                 case IO_ERROR:
  12.                     System.out.println("\nError while logging off");
  13.                     break;
  14.             }
  15.             exit = true;
  16.         } else {
  17.             imc.sendMsg(kbInput);
  18.         }
  19.     }
  20.     if (imc.scanNet.hasNextMessage()) {
  21.         System.out.println(imc.printMsg(imc.scanNet.nextMessage()));
  22.     }
  23. }
  24.  
  25. } catch (NextDoesNotExistException e) {
  26.     System.out.println("Error");
  27. } catch (NullPointerException e) {}
So even with your examples above, I really am not sure what I could do with the above code to decrease CPU usage time...


Thanks!
The quickest way to fix your program: Place the nextLine() in the while loop condition.

Expand|Select|Wrap|Line Numbers
  1. while ( ( (kbInput = scanKB.nextLine()) != null ) ||
  2.           ( (imcInput = imc.scanNet.nextMessage()) != null) ){
  3.                       if (kbInput.equals("/quit")) {
  4.             .... //finish code. 
I would suggest reading this tutorial Sockets but focus on the last section - Supporting Multiple Clients. This is a great example of threads.
Sep 13 '07 #11
JosAH
11,448 Expert 8TB
Actually, I made this same mistake before.
Expand|Select|Wrap|Line Numbers
  1. while ( userInput == null ){
  2.         userInput = stdln.readLine();
  3. }
If I remember correctly (this was 2 years ago) the above code will never block; you must use the while condition I posted above.
That most certainly isn't true; a readLine() method invocation will block when there
is no new line available. Your loop is exactly the same (functionally) as the loop
you don't like.

kind regards,

Jos
Sep 13 '07 #12
kreagan
153 100+
That most certainly isn't true; a readLine() method invocation will block when there
is no new line available. Your loop is exactly the same (functionally) as the loop
you don't like.

kind regards,

Jos
Thanks for fixing my confusion.
Sep 13 '07 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

13
by: BlackHawke | last post by:
Our program, game program Andromeda Online (www.andromedaonline.net) uses two programs- one to play the game, another to patch the game as updates come out. Players actually launch the updater...
4
by: Warrick Wilson | last post by:
I've got a web page that uses frames. One of the frames loads an HTML page that redirects to a 3rd HTML page. This third page loads a Java applet - ProScroll.class - that runs a "news ticker"...
133
by: Gaurav | last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250 Any comments? Thanks Gaurav
1
by: Cris | last post by:
My question in a nutshell: Can a C header file be converted into a C# interface? Details for why I want this below... I am trying to use C# in lieu of C/C++ to build some libraries that java...
14
by: Anoop | last post by:
Hi, I am new to this newsgroup and need help in the following questions. 1. I am workin' on a GUI application. Does C# provides Layout Managers the way Java does to design GUI? I know that it...
10
by: Mythmon | last post by:
I am trying to make a program that will basically simulate a chess clock in python. To do this I have two threads running, one that updates the currently running clock, and one that watches for a...
6
by: =?Utf-8?B?VkIgSm9ubmll?= | last post by:
ASP.NET 2.0 / Visual Studio 2005 / VB.Net 2.0 I have a web interface that needs to launch a java application. What a long strange trip it has been... I am using Process.Start process start...
1
by: MimiMi | last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for. I think I am using the same type of...
2
by: MimiMi | last post by:
I'm trying to decrypt a byte array in java that was encrypted in C#. I don't get any error messages, just a result that's completely not what I was hoping for. I think I am using the same type of...
318
by: King Raz | last post by:
The shootout site has benchmarks comparing different languages. It includes C# Mono vs Java but not C# .NET vs Java. So I went through all the benchmark on the site ... ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.