100% CPU Usage!!!!!!!

Hi,
When I start my program the CPU Usage shoots up to 100%. I ran the java profiler (java -Xprof myprog).
These were the results:

Flat profile of 0.60 secs (38 total ticks): main

Interpreted + native Method
12.5% 0 + 4 java.io.WinNTFileSystem.canonicalizeWithPrefix0
6.3% 2 + 0 sun.nio.cs.ISO_8859_1$Decoder.decodeArrayLoop
6.3% 0 + 2 java.io.FileInputStream.open
6.3% 2 + 0 java.util.Arrays.copyOfRange
6.3% 0 + 2 sun.awt.Win32GraphicsEnvironment.initDisplay
3.1% 0 + 1 sun.awt.windows.WWindowPeer.setFocusableWindow
3.1% 0 + 1 java.lang.ClassLoader$NativeLibrary.load
3.1% 0 + 1 java.io.RandomAccessFile.open
3.1% 0 + 1 sun.nio.ch.FileDispatcher.read0
3.1% 0 + 1 java.lang.ClassLoader.findBootstrapClass
3.1% 1 + 0 java.lang.Character.valueOf
3.1% 1 + 0 java.util.HashSet.add
3.1% 1 + 0 sun.java2d.loops.GraphicsPrimitive.makeUniqueID
3.1% 1 + 0 java.awt.Dialog.
3.1% 1 + 0 javax.swing.plaf.basic.BasicTextUI.installKeyboardActio
ns
3.1% 1 + 0 sun.java2d.loops.GraphicsPrimitiveMgr.registerGeneral
3.1% 0 + 1 sun.awt.windows.WDesktopProperties.init
3.1% 1 + 0 javax.swing.JComponent.setUI
3.1% 1 + 0 javax.swing.plaf.metal.DefaultMetalTheme.getUserTextFon
t
3.1% 1 + 0 java.io.BufferedReader.readLine
3.1% 1 + 0 sun.font.CMap$CMapFormat4.
3.1% 1 + 0 java.lang.String.toLowerCase
3.1% 1 + 0 java.util.Properties$LineReader.readLine
93.8% 16 + 14 Total interpreted

Thread-local ticks:
15.8% 6 Blocked (of total)
6.3% 2 Class loader

Flat profile of 6.55 secs (5 total ticks): Image Fetcher 0

Interpreted + native Method
33.3% 1 + 0 java.util.StringTokenizer.nextToken
33.3% 1 + 0 sun.util.calendar.ZoneInfo.getOffsets
33.3% 1 + 0 sun.awt.image.GifImageDecoder.parseImage
100.0% 3 + 0 Total interpreted

Thread-local ticks:
40.0% 2 Blocked (of total)

After this it just hung, so I had to close it.
Please help me find the problem that is making my program use all of the CPU!
Thanks.

infinite loop

How do I get rid of this infinite loop?

Pause it in the debugger and find out where it is, first.

Cas :slight_smile:

Or… if you got a command window… press ctrl+break there (does this only work with windows?).

This came up when I pressed Ctrl + Break:

2007-11-29 16:25:08
Full thread dump Java HotSpot™ Client VM (1.6.0_03-b05 mixed mode, sharing):

“DestroyJavaVM” prio=6 tid=0x00296000 nid=0x600 waiting on condition [0x00000000
…0x0090fd4c]
java.lang.Thread.State: RUNNABLE

“Thread-2” prio=6 tid=0x0306cc00 nid=0x9a8 runnable [0x033cf000…0x033cfd14]
java.lang.Thread.State: RUNNABLE
at java.awt.EventQueue.postEvent(Unknown Source)
at javax.swing.SystemEventQueueUtilities.queueComponentWorkRequest(Unkno
wn Source)
at javax.swing.SystemEventQueueUtilities.queueComponentWorkRequest(Unkno
wn Source)
at javax.swing.RepaintManager.addDirtyRegion0(Unknown Source)
at javax.swing.RepaintManager.addDirtyRegion(Unknown Source)
at javax.swing.JFrame.repaint(Unknown Source)
at java.awt.Component.repaint(Unknown Source)
at ronansautotyperuk.run(ronansautotyperuk.java:1477)
at java.lang.Thread.run(Unknown Source)

“AWT-EventQueue-0” prio=6 tid=0x03056400 nid=0x4b0 runnable [0x02fce000…0x02fcf
a14]
java.lang.Thread.State: RUNNABLE
at sun.java2d.loops.DrawGlyphListLCD.DrawGlyphListLCD(Native Method)
at sun.java2d.pipe.LCDTextRenderer.drawGlyphList(Unknown Source)
at sun.java2d.pipe.GlyphListPipe.drawString(Unknown Source)
at sun.java2d.pipe.ValidatePipe.drawString(Unknown Source)
at sun.java2d.SunGraphics2D.drawString(Unknown Source)
at sun.swing.SwingUtilities2.drawString(Unknown Source)
at sun.swing.SwingUtilities2.drawStringUnderlineCharAt(Unknown Source)
at javax.swing.plaf.metal.MetalButtonUI.paintText(Unknown Source)
at javax.swing.plaf.basic.BasicButtonUI.paintText(Unknown Source)
at javax.swing.plaf.basic.BasicButtonUI.paint(Unknown Source)
at javax.swing.plaf.metal.MetalButtonUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
- locked <0x22ea14b8> (a java.awt.Component$AWTTreeLock)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
- locked <0x22ea14b8> (a java.awt.Component$AWTTreeLock)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JLayeredPane.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
- locked <0x22ea14b8> (a java.awt.Component$AWTTreeLock)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
at java.awt.Container.paint(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
n Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

“AWT-Windows” daemon prio=6 tid=0x02a8a800 nid=0xd84 runnable [0x02f0f000…0x02f
0fa94]
java.lang.Thread.State: RUNNABLE
at sun.awt.windows.WToolkit.eventLoop(Native Method)
at sun.awt.windows.WToolkit.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

“AWT-Shutdown” prio=6 tid=0x02a89c00 nid=0xa80 in Object.wait() [0x02ebf000…0x0
2ebfb14]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x22ea1718> (a java.lang.Object)
at java.lang.Object.wait(Object.java:485)
at sun.awt.AWTAutoShutdown.run(Unknown Source)
- locked <0x22ea1718> (a java.lang.Object)
at java.lang.Thread.run(Unknown Source)

“Java2D Disposer” daemon prio=10 tid=0x02a88400 nid=0xfb0 in Object.wait() [0x02
e6f000…0x02e6fb94]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x22ea17b0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(Unknown Source)
- locked <0x22ea17b0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(Unknown Source)
at sun.java2d.Disposer.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

“Low Memory Detector” daemon prio=6 tid=0x02a5c800 nid=0x7dc runnable [0x0000000
0…0x00000000]
java.lang.Thread.State: RUNNABLE

“CompilerThread0” daemon prio=10 tid=0x02a57c00 nid=0x364 waiting on condition [
0x00000000…0x02d0f61c]
java.lang.Thread.State: RUNNABLE

“Attach Listener” daemon prio=10 tid=0x02a56800 nid=0x98 runnable [0x00000000…0
x00000000]
java.lang.Thread.State: RUNNABLE

“Signal Dispatcher” daemon prio=10 tid=0x02a55400 nid=0xad8 waiting on condition
[0x00000000…0x00000000]
java.lang.Thread.State: RUNNABLE

“Finalizer” daemon prio=8 tid=0x02a51400 nid=0x314 in Object.wait() [0x02c1f000.
.0x02c1fa94]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x22ea1a08> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(Unknown Source)
- locked <0x22ea1a08> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(Unknown Source)
at java.lang.ref.Finalizer$FinalizerThread.run(Unknown Source)

“Reference Handler” daemon prio=10 tid=0x02a4cc00 nid=0x50c in Object.wait() [0x
02bcf000…0x02bcfb14]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x22ea14b0> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:485)
at java.lang.ref.Reference$ReferenceHandler.run(Unknown Source)
- locked <0x22ea14b0> (a java.lang.ref.Reference$Lock)

“VM Thread” prio=10 tid=0x02a4b800 nid=0xaf4 runnable

“VM Periodic Task Thread” prio=10 tid=0x02a77400 nid=0xeac waiting on condition

JNI global references: 1384

Heap
def new generation total 960K, used 262K [0x22960000, 0x22a60000, 0x22e40000)

eden space 896K, 28% used [0x22960000, 0x229a0ef0, 0x22a40000)
from space 64K, 4% used [0x22a40000, 0x22a40c58, 0x22a50000)
to space 64K, 0% used [0x22a50000, 0x22a50000, 0x22a60000)
tenured generation total 4096K, used 569K [0x22e40000, 0x23240000, 0x26960000
)
the space 4096K, 13% used [0x22e40000, 0x22ece670, 0x22ece800, 0x23240000)
compacting perm gen total 12288K, used 211K [0x26960000, 0x27560000, 0x2a96000
0)
the space 12288K, 1% used [0x26960000, 0x26994ca8, 0x26994e00, 0x27560000)
ro space 8192K, 62% used [0x2a960000, 0x2ae614a8, 0x2ae61600, 0x2b160000)
rw space 12288K, 52% used [0x2b160000, 0x2b7a7278, 0x2b7a7400, 0x2bd60000)

So Thread-2 is doing ronansautotyperuk.run(ronansautotyperuk.java:1477) and calling repaint() on some component over and over again. Let’s see the source to this bit.

Cas :slight_smile:

In the Run() method?

Here is the code:

import java.awt.*;
import java.awt.Robot.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.applet.AudioClip;
import java.net.*;

public class ronansautotyperuk extends JFrame implements Runnable, ActionListener
{
	JTextField comments = new JTextField("Enter your message to be typed here", 25);
	JTextField delaytime = new JTextField("Enter miliseconds between each letter press", 23);
	JButton starttyping = new JButton("Start Typing");
	JButton stoptyping = new JButton("Stop Typing");
	
	Thread runner;
	Boolean gameover = false;
	Boolean running = true;
	Boolean istyping = false;
	int pausefor;
	int realpausefor = 7;
	int numb = 0;
	String stringOfCharsToType;
	String delayfor;
	int delayforint;
	Image icon;
	
	public ronansautotyperuk()
	{
		super("Ronan's Autotyper UK - Version 1.0");
		setSize(800, 75);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setDefaultLookAndFeelDecorated(true);
		setVisible(true);
		setResizable(false);
		Container contentArea = getContentPane();
		contentArea.setBackground(Color.red);
		FlowLayout flowManager = new FlowLayout();
		contentArea.setLayout(flowManager);
		
		contentArea.add(comments);
		contentArea.add(delaytime);
		contentArea.add(starttyping);
		contentArea.add(stoptyping);
		starttyping.addActionListener(this);
		stoptyping.addActionListener(this);
		setContentPane(contentArea);
		
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		icon = toolkit.getImage( getClass().getResource("icon.gif") );
		MediaTracker mediatracker = new MediaTracker(this);
		mediatracker.addImage(icon, 0);
		try
		{
			mediatracker.waitForID(0);
		}
		catch(InterruptedException interruptedexception)
		{
			System.out.println("Download Error");
		}
		setIconImage(icon);
		start();
	}
	
	public void actionPerformed(ActionEvent event)
	{
		if(event.getSource() == starttyping) starttypingnow();
		if(event.getSource() == stoptyping) stoptypingnow();
	}
	
	public void start()
	{
		setVisible(true);
		requestFocus();
		running = true;
		runner = new Thread(this);
		runner.start();
	}
	
	public void stopgame()
	{
		if(running != null)
		running = null;
	}
	
	public void destroy()
	{
		
	}
	
	public void starttypingnow()
	{
		pausefor = 2000;
		istyping = false;
		stringOfCharsToType = comments.getText();
		delayfor = delaytime.getText();
		delayforint = Integer.parseInt(delayfor);
	}
	
	public void stoptypingnow()
	{
		istyping = false;
		numb = 0;
	}
	
	public void typenow()
	{
		if(numb < stringOfCharsToType.length() && istyping)
		{
			char thing = stringOfCharsToType.charAt(numb);
			numb++;
			if(thing == 'a')
			{
				try
				{
					Robot bot = new Robot();
					bot.keyPress(KeyEvent.VK_A);
					bot.keyRelease(KeyEvent.VK_A);
				}
				catch(Exception exc)
				{
					System.out.println(exc);
				}
			}
		}
		if(numb >= stringOfCharsToType.length())
		{
			try
			{
				Robot bot = new Robot();
				bot.keyPress(KeyEvent.VK_ENTER);
				bot.keyRelease(KeyEvent.VK_ENTER);
			}
			catch(Exception exc)
			{
				System.out.println(exc);
			}
			numb = 0;
		}
	}
	
	public void gameupdate()
	{
		if(!gameover)
		{
			if(istyping)
			{
				typenow();
			}
		}
	}
	
	public void run()
	{
		while (running)
		{
			repaint();
			gameupdate();
			try
			{
				if(pausefor != 2000)
				{
					pausefor = delayforint;
					Thread.sleep(pausefor);
				}
				if(pausefor == 2000)
				{
					Thread.sleep(pausefor);
					pausefor = realpausefor;
					istyping = true;
				}
			}
			catch(InterruptedException e) {}
		}
	}

	public static void main (String[] args)
	{
		ronansautotyperuk eg = new ronansautotyperuk();
	}
}

Instead of this :

Toolkit toolkit = Toolkit.getDefaultToolkit();
icon = toolkit.getImage( getClass().getResource(“icon.gif”) );
MediaTracker mediatracker = new MediaTracker(this);
mediatracker.addImage(icon, 0);
try
{
mediatracker.waitForID(0);
}
catch(InterruptedException interruptedexception)
{
System.out.println(“Download Error”);
}
setIconImage(icon);

do this :
icon = new ImageIcon( getClass().getResource(“icon.gif”) ).getImage();

Do I still do this bit?

setIconImage(icon);

Still 100% CPU usage!

You are doing some messy stuff with your timing variables. :o

Your problem might be, that two of your variables (pausefor, delayforint) are not initialized to a sensible value and will default to 0. Also realpausefor is only set to 7. So your Thread.sleep() will either sleep 0ms or 7ms, which is both way too small to prevent your loop from taking 100% CPU time.

But the sleep time is set by the user, this will define on how fast the program will do Robot.press()
How else could I do it to stop 100% CPU usage?

This is a known bug in Windows JFileChooser as described in the bug database with id : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6578753
Getting back to Java release 5 does solve this problematic issue. :slight_smile:

Nah, the JFileChooser bug is totally unrelated and is not even used here ::slight_smile:

I’m also suspecting something with the timing. Could you try sleeping with a hardcoded value of 100 or something?

But the sleep time is set by the user, this will define on how fast the program will do Robot.press()
How else could I do it to stop 100% CPU usage?

.
Yeah, but it is 0 BY DEFAULT before the user choose the sleep time. Set it to 100 by default and specify a minimum for the value the user can enter

Thanks!!! You solved it!