We help IT Professionals succeed at work.

CPU usage problem

acrxx
acrxx asked
on
527 Views
Last Modified: 2010-03-31
Hi everyone,

What happens within my program is that within about 10 seconds of running my prog, my CPU usage reaches 100 and stays there, making it close to impossible to continue running the program (or any other programs on my comp) normally.

My program basically uses one thread which is initialised explicitly. This is used to control the refreshing of a canvas object within a gui. All the main function is responsibke for is drawing the gui, initialising objects and then attaching actionlisteners to the buttons of the gui. The gui buttons are used to edit an object containing data for the graphical representation of a network, which is then plotted using an object drawing to a canvas which was previously added to the gui.

I have used JProfiler to try and see where the problem lies, here is what I found out about all the different threads:

What is happening is that the AWT - EventQueue-0 Thread becomes active from time to time even if I just leave the program running without using it.

The main thread terminates after about 12 seconds (as the only thing it actually does is it dreaws the GUI, initialises the different objects the program uses and then adds actionevents to buttons. It then terminates. Is a possible cause of the problem that the main thread terminates while a display which was generated by it is still running?

The other threads which seem to be present (but are waiting for almost the whole of the time) are Java2D Disposer, the thread resposible for the painting (which doesnt seem to do any thing at all, even thought the painting was actually done), AWTShutdown (which is waiting at all times too), DestroyJava VM (also always waiting), 2 Image fetchers which are only created for about 4 secs each and are only runnable for about 0.1 seconds and a Timer Queue thread (which is only initialised just before the 1st Image fetcher is terminated) which then keeps waiting forever.

Any help at all would be very useful,

Andy
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
>>
What is happening is that the AWT - EventQueue-0 Thread becomes active from time to time even if I just leave the program running without using it.
>>

Sounds like you may be accessing that thread for application processing, which shouldn't happen. Perhaps you'd better post the code...

Author

Commented:
u want all the classes? OK

Here is the graph class which draws to the canvas:

import java.awt.*;
import java.util.*;
import java.lang.*;
import java.lang.String.*;
import javax.swing.*;
/**
 *
 * @author  Andy
 */
public class Graph extends Canvas implements Runnable {
   
    private int coord[][];
    private Database data;
    private int maxx = -1;
    private int maxy = -1;
    private int originx = -1;
    private int originy = -1;
    private int radius = -1;
    private int numnodes = -1;
    private double angle = -1;
    private int maxnodes = -1;
    private int x = 0;
   
    //    public Thread drawing = new Thread(this);
   
   
    /** Creates a new instance of Graph */
    public Graph(Database d) {
        data = d;
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        maxx = (int) ((471/1024)* (-60 + (int) dim.getWidth()));
        maxy = (int) ((304/738)* (-90 + (int) dim.getHeight()));
        originx = (int) maxx/2;
        originy = (int) maxy/2;
        radius = maxy - 30;
        maxnodes = data.maxnodes();
       
       
        coord = new int[maxnodes][2]; // used to store the co-ordinates of the nodes
       
        for(int i=0;i<maxnodes;i++) {
            coord[i][0]=-1; // invalid co-ordinate
            coord[i][1]=-1; // invalid co-ordinate
           
        }
       
       
       
    }
   
    public void start() {
        Thread drawing = new Thread(this);
        System.out.println(drawing.getName());
        drawing.setName("PaintingThread");
        drawing.start();
    }
   
    public synchronized void refresh() {
        notify();
    }
   
   
    public void run() {
        while(true) {
            if(data.getdrawwait()==true) {  // flag set in anither thread
               
                synchronized (this) {
                    System.out.println("We are in synchronized");
                    try {
                        wait();
                    }
                    catch (Exception ex) {
                        System.out.println("Interrupted");
                    }
                }
                repaint();
                System.out.println("We are just after repaint");
                data.makewait(true);
            }
        }
    }
   
    public void paint(Graphics g) {
        double totangle = 0;
        numnodes = data.getnodes();
        maxnodes = data.maxnodes();
        angle = 360/numnodes;
       
        setForeground(Color.black);
        setBackground(Color.white);
       
        if(numnodes > 1) {
           
            System.out.println(numnodes);
            for(int i = 0; i!=numnodes; i++) {
               
                String j = String.valueOf(i);
                coord[i][0]=(int)((radius* Math.sin(totangle)) + originx);
                coord[i][1]=(int)((radius* Math.cos(totangle)) + originy);
                setForeground(Color.black);
                g.fillOval(coord[i][0]+100,coord[i][1]+100,20,20);
               // setForeground(Color.white);
                g.drawString(j, coord[i][0] + 100, coord[i][1] + 100);
                totangle = totangle+angle;
            }
        }
        else {
            setForeground(Color.white);
            g.fillOval(15,15,20,20);
        }
       
    }
   
}


Here is the segment of code whithin the Main class which uses the canvas thread:

        setGBagParameters(0, 2, 12, 9); /// this adds it to the gui
         add(graph, c);
         graph.start(); // calls the start fundtion of the class

...
...
...

  JButton generate = new JButton("Auto Generate");
         generate.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                 int n = JOptionPane.showConfirmDialog(
                 null, "This will destroy the current network.\n Are you sure you want to auto-generate \n a new network?",
                 "Confirmation",
                 JOptionPane.YES_NO_OPTION);
                 if (n == JOptionPane.YES_OPTION) {
                     database.generate_random_graph();

                     graph.refresh();
                   
                     
                 }
             }
         });


And finally here is the part of the database class which sores the variable used for deciding whether or not the instance of the canvas class needs to continue waiting or not:

   
    synchronized public void makewait(boolean r)
    {
        drawwait = r;
    }
   
    synchronized public boolean getdrawwait()
    {
        return drawwait;
    }

There we go that is all the code which has anything to do with threads.
CERTIFIED EXPERT
Top Expert 2016

Commented:
OK - i'll try to have a look at that in a few minutes. btw did you run that demo i posted in your previous q?
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> generate_random_graph();

What does this method do?

you may have a thread witha really tight loop.
Try adding a call to Thread.yield() to your loop.

Also how many nodes will the above be plotting?
CERTIFIED EXPERT
Top Expert 2016
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> What is happening is that the AWT - EventQueue-0 Thread becomes active from
> time to time even if I just leave the program running without using it.

That can be expected.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
>  database.generate_random_graph();

try moving that call inside your thread
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Won't fix the problem though.
I suspect your problem is perhaps inside that method (generate_random_graph)

Author

Commented:
database.generate_random_graph();

here is the code for it:

 public synchronized void generate_random_graph() {
       
        int correct = 0;  // used for validation. Changed to show state of
        // correctness
       
       
        while(correct == 0) {
            correct = 1;
            String nodes = JOptionPane.showInputDialog("How many nodes would you like \n the network to have (3-" + maxnodes + ")");
           
            try {
                num_nodes_target = Integer.parseInt(nodes);
            }
           
            catch(NumberFormatException nf) {
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, please only enter whole numbers.");
            }
           
            if(correct==1 && (num_nodes_target>maxnodes||num_nodes_target<3)) {
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, number entered out of range");
            }
        }
       
        correct = 0;
        while(correct == 0) {
           
            int upperrange = (int)(((num_nodes_target*num_nodes_target)-num_nodes_target)/3); //getting the number of edges to 2/3 of the maximum number
           
            if(upperrange<num_nodes_target) {
                upperrange = num_nodes_target;
            }
           
            correct = 1;
            String edges = JOptionPane.showInputDialog("How many connections would you like the network to be \n generated with (between "+ num_nodes_target + " and " + upperrange + ")");
           
            try {
                edge_target = Integer.parseInt(edges);
            }
           
            catch(NumberFormatException nf) { // if invalid input is input, the exception is caught here
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, please only enter whole numbers.");
            }
           
            if(correct==1 && (edge_target>upperrange||edge_target<num_nodes_target)) //making sure it is not out of range
            {
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, number entered out of range");
            }
        }
       
        for(int i=0;i<num_nodes_target;i++) {
            for(int j=0;j<num_nodes_target;j++) {
                graph[i][j][0] = infinity;
                graph[j][i][0] = infinity;
            }
        }
       
        int rand = -1;
        int rand2 = -1;
       
        for(int count = 0; count!=num_nodes_target; count++) // attaches at least 1 edge to all nodes
        {
            rand = count;
           
            while(rand == count||((graph[count][rand][1] != infinity)&&(graph[count][rand][1] != -1)))
                // makes sure that edges do not start and finish at the same node and that edge
                // being added does not already exist
            {
                rand = (int)(num_nodes_target*Math.random());
            }
           
            add_edge(count, rand, (int)((10 * Math.random()) + 1));
           
        }
       
        while(num_edges!=edge_target) // places all remaining requested edges onto graph
        {
            rand2 = rand;
            while(rand==rand2||((graph[rand][rand2][1] != -1)&&(graph[rand][rand2][1] != infinity))) // same as above checking conditions
            {
                rand = (int)(num_nodes_target*Math.random());
                rand2 = (int)(num_nodes_target*Math.random());
            }
           
            add_edge(rand, rand2, (int)((10 * Math.random()) + 1));
        }
       
       
       
    }

What it does is gets info about the graph to plot from the user and then adjusts the Database object's intance accordingly. Also placing the number of specified edges randomly between nodes. Then also generating the lengths of all these nodes randomly.
Java Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Database has nothing to do with any threads. It is just has to do with storing the different data in arrays. But, mayb u guys can see something i dont.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> Database has nothing to do with any threads.

Everything runs in a thread.

Author

Commented:
sorry, being dumb, been working all day, it's now 2140 here
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
thats ok :)  Get some rest.

Author

Commented:
no, i have to get this to work 2nite

Author

Commented:
Ok, added yield, now my comp doesnt freeze anymore. Thank you.

CEHJ, about ur previous comment, is there any way of making everything wait until those methods have returned?

Author

Commented:
the CPU usage still sharply increases when starting my prog, is that normal when using threads?
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
You should be doing that processing in your thread as I mentioned earlier.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> the CPU usage still sharply increases when starting my prog

Possibly if it does lots of work setting up.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>CEHJ, about ur previous comment, is there any way of making everything wait until those methods have returned?

If you mean what I was saying about the ActionListener you should be doing something like

if (n == JOptionPane.YES_OPTION) {
      Thread databaseProcessor = new Thread(new Runnable() {
            public void run() {
                     database.generate_random_graph();
                     graph.refresh();
            }    
      });
      t.start();
}

CERTIFIED EXPERT
Top Expert 2016

Commented:
Oops

>>t.start();

should be

databaseProcessor.start()





Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Creating a new thread to do your processing is an unnecessary overhead and will just slow down your gui.
You already have a background thread running to handle the processing.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>and will just slow down your gui

At the moment the processing is being done in the event dispatch thread and needs to be run on another thread to *free up* the gui thread
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
yes thats already been mentioned, and there is already a thread to handle it.
A new thread is not required, all it will do is slow things down.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>and there is already a thread to handle it.

Well if it can be controlled from that event handler then that's fine
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
In fact that is really what your background threads job is (performing the processing) as I mentioned in your previous question. The way you are currently using it serves no real purpose.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> Well if it can be controlled from that event handler then that's fine

As it already is I don't see why you'd think there is a problem.

acrxx,

See my example in your previous question, it showed where any processing should be done.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>As it already is I don't see why you'd think there is a problem.

At the moment, unless the code has been changed, all that's happening is processing is being done on the event queue thread

Author

Commented:
object, I know what yield does, and i saw that using it improved the situation, but why did it improve the situation. Just want to understand how it improved my code, rather than just place it in there without knowing what good it does.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
It tells the thread to give other threads a chance to run.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
In the words of the javadoc:

"Causes the currently executing thread object to temporarily pause and allow other threads to execute. "
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Because you loop is tight and doing intensive processing it doesn't give other threads a chance, and dominates the CPU.

Author

Commented:
thanks for that, you learn something every day

Author

Commented:
It appears to me that all te processing is still happening in the AWT EventQueue - 0 thread, while all others (except for main) are always waiting. The program runs correctly though. I was just wondering if this is still ok?

The problem I am also having is that when the dialog window asking the user for the details of the autogenerated network (or graph) it leaves a gap in the gui  when the dialog closes, exactly there where the dialog had previously been. I think this has to do with the fact that the main thread (which is responsible for the gui) has been terminated by this point. Is there any way of solving this problem without simply putting a while loop around all the gui components?
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> It appears to me that all te processing is still happening in the AWT EventQueue - 0 thread

it is, actionPerformed() is called from EDT.
See my earlier comments about moving the processing to your background thread.

> it leaves a gap in the gui  when the dialog closes, exactly there where the dialog had previously been

that cause its busy doing your processing so cannot update gui.

>  Is there any way of solving this problem without simply putting a while loop around all the gui components?

Moving your processing into your background thread (before the repaint call) will fix it.

Author

Commented:
I have moved everyhting to the background thread apart from the gui related processing. Are you saying I should move that to the background thread too?
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> Are you saying I should move that to the background thread too?

No just any lengthy processing, any code on running on the edt should not take long.
The gui will be blocked until it returns.

Author

Commented:
I have done all that, but to no use. gets stuck just as the first dialog asking for number of nodes opens. The dialog's frame opens, but the writing is not displayed. I am at the end of my wits. Gonna go an hit my head against a tree, then go and look for James Gosling so I can strangle him. ;)
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
post your current code

Author

Commented:
Here goes: The Project class (containing main) -------------------------------------------------------

import javax.swing.*;
import java.lang.*;
import javax.swing.JComponent.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;

public class Project extends JPanel {
   
    GridBagConstraints c = new GridBagConstraints();
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    int winheight = -90 + (int) dim.getHeight(); // gets window sizreminus the border
    int winwidth = -60 + (int) dim.getWidth();
    Database data;
    Graph graph;
    String[] columnNames =
    {"Network",
     "Mask",
     "Gateway",
     "Interface",
     "Cost"};
     
     Object[][] info = {
         {"Mary", "Campione",
          "Snowboarding", new Integer(5), new Boolean(false)},
          {"Alison", "Huml",
           "Rowing", new Integer(3), new Boolean(true)},
           {"Kathy", "Walrath",
            "Knitting", new Integer(2), new Boolean(false)},
            {"Sharon", "Zakhour",
             "Speed reading", new Integer(20), new Boolean(true)},
             {"Philip", "Milne",
              "Pool", new Integer(10), new Boolean(false)}
     };
     public Project() {
         data = new Database();
         graph = new Graph(data);
     }
     
     public JComponent createComponents() {
         FilterLight light = new FilterLight();
         RoutingTable table = new RoutingTable();
         Component jc;
         
         setBorder(BorderFactory.createEmptyBorder(
         30, //top
         30, //left
         30, //bottom
         30) //right
         );
         
         JButton button;
         GridBagLayout lay = new GridBagLayout();
         setLayout(lay);
         
         JLabel title = new JLabel("<html><font size = 16>Routing Protocol Simulator</font></html>");
         
         c.anchor = GridBagConstraints.CENTER;
         
         c.fill = GridBagConstraints.BOTH;
         
         c.weighty = 1;
         c.weightx = 1;
         
         setGBagParameters(0, 0, 12, 2);
         add(title, c);
         
         c.anchor = GridBagConstraints.CENTER;
         
         button = new JButton("Button 1");
         
         setGBagParameters(0, 2, 12, 9);
         add(graph, c);
         graph.start();
         
         ////////////
         
         JLabel chooseroutingtable = new JLabel("<html><font size = 3>Display Routing Table for Router:</font></html>");
         
         setGBagParameters(0, 11, 6, 1);
         
         add(chooseroutingtable, c);
         
         String[] items={"1","2","10"};//////////////////////////////////
         JComboBox chooserouting = new JComboBox(items);
         
         setGBagParameters(6, 11, 1, 1);
         add(chooserouting, c);
         
         for(int l=1;l!=4;l++) {
             JLabel blank = new JLabel("    ");
             setGBagParameters(6+l, 11, 1, 1);
             add(blank, c);
         }
         
         JButton display = new JButton("Display");
         setGBagParameters(10, 11, 2, 1);
         add(display,c);
         
         JScrollPane table1 = new JScrollPane(new JTable(info,columnNames));
         
         setGBagParameters(0, 12, 12, 5);
         
         add(table1, c);
         
         Component[][] x = new Component[15][8];
         
         for(int i = 0;i!=15;i++) {
             for(int j = 0; j!=8; j++) {
                 JLabel blank = new JLabel(" ");
                 x[i][j]=blank;
             }
         }
         
         for(int i=0;i!=8;i++) {
             x[0][i] = new JSeparator();
         }
         
         x[1][0] = new JLabel("Would you like to auto-generate");
         x[2][0] = new JLabel("a new Network?");
         JButton generate = new JButton("Auto Generate");
         generate.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                 int n = JOptionPane.showConfirmDialog(
                 null, "This will destroy the current network.\n Are you sure you want to auto-generate \n a new network?",
                 "Confirmation",
                 JOptionPane.YES_NO_OPTION);
                 if (n == JOptionPane.YES_OPTION) {
                     
                     data.setregenerate(true);
                     graph.refresh();
                     
                 }
             }
         });
         
         x[2][7] = generate;
         
         for(int i=0;i!=8;i++) {
             x[3][i] = new JSeparator();
         }
         
         x[4][0] = new JLabel("Routers can be added by left-");
         x[5][0] = new JLabel("clicking on the screen");
         
         for(int i=0;i!=8;i++) {
             x[6][i] = new JSeparator();
         }
         
         JRadioButton[] addDelete = new JRadioButton[2];
         ButtonGroup adddel = new ButtonGroup();
         addDelete[0] = new JRadioButton("Add a Connection from");
         addDelete[1] = new JRadioButton("Delete the Connection from");
         
         addDelete[0].setSelected(true);
         adddel.add(addDelete[0]);
         adddel.add(addDelete[1]);
         
         x[7][0] = addDelete[0];
         x[8][0] = addDelete[1];
         
         x[7][5] = new JLabel("Router");
         x[8][5] = new JLabel("to Router");
         x[9][4] = new JLabel("(add only)");
         x[9][5] = new JLabel("with Cost");
         
         x[9][0] = new JLabel("<html><font size = 2>PS: change cost of a connection by using add</font></html>");
         
         String[] items2={"1","2","3","4","5","6","7","8","9","10"};
         JComboBox node1 = new JComboBox(items);
         JComboBox node2 = new JComboBox(items);
         JComboBox weight = new JComboBox(items2);
         
         x[7][6] = node1;
         x[8][6] = node2;
         x[9][6] = weight;
         
         JButton executeadddel = new JButton("Add/Delete");
         x[9][7] = executeadddel;
         
         for(int i=0;i!=8;i++) {
             x[10][i] = new JSeparator();
         }
         
         x[11][0] = new JLabel("Delete Router:");
         
         JComboBox deletenode = new JComboBox(items);
         x[11][6] = deletenode;
         
         JButton exDelete = new JButton("Delete Router");
         x[11][7] = exDelete;
         
         JRadioButton[] chooseRouting = new JRadioButton[2];
         ButtonGroup prot = new ButtonGroup();
         chooseRouting[0] = new JRadioButton("RIP Routing Protocol");
         chooseRouting[1] = new JRadioButton("OSPF Routing Protocol");
         
         chooseRouting[0].setSelected(true);
         prot.add(chooseRouting[0]);
         prot.add(chooseRouting[1]);
         
         x[12][0] = chooseRouting[0];
         x[13][0] = chooseRouting[1];
         
         JButton setRouting = new JButton("Set");
         x[13][7] = setRouting;
         
         JButton exit = new JButton("Exit Program");
         x[14][7] = exit;
         
         for(int i = 0;i!=15;i++) {
             for(int j = 0; j!=8; j++) {
                 if(j==0) {
                     setGBagParameters(12+j, 2+i, 3, 1);
                     add(x[i][j], c);
                     j=3;
                 }
                 else {
                     setGBagParameters(12+j, 2+i, 1, 1);
                     add(x[i][j], c);
                 }
             }
         }
         
         
         return this;
     }
     
     public static void main(String[] args) {
         try {
             UIManager.setLookAndFeel(
             UIManager.getSystemLookAndFeelClassName());
         } catch (Exception e) { }
         
         
         //Create the top-level container and add contents to it.
         JFrame frame = new JFrame("Routing Protocol Simulation by Andreas Rohkraehmer");
         Project app = new Project();
         JComponent contents = app.createComponents();
         frame.getContentPane().add(contents, BorderLayout.CENTER);  //
         
         
         
         //Finish setting up the frame, and show it.
         frame.addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                 System.exit(0);
             }
         });
         //                frame.pack();
         
         Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
         double h = dim.getHeight();
         h = h - 30;                                   // accommodates for the taskbar
         double w = dim.getWidth();
         dim.setSize(w, h);
         frame.setSize(dim);
         
         frame.setResizable(false);
         
         frame.setVisible(true);
         
     }
     
     private void setGBagParameters(int gx, int gy, int gw, int gh) {
         
         c.gridx = gx;
         c.gridy = gy;
         c.gridwidth = gw;
         c.gridheight = gh;
         c.ipady = gh * (int)(winheight/17);
         c.ipadx = gw * (int)(winwidth/20); //sets the section to correct width
         
     }
     
}

The database class. --------------------------------------------------------------------------------------

import java.awt.*;
import java.lang.*;
import javax.swing.JOptionPane;
/**
 *
 * @author  Andy
 */
public class Database {
   
    private int graph[][][];
    private int num_nodes = -1;         // actual number of active nodes
    private int num_nodes_target = -1;  // how many active nodes were requwsted by the user
    private int num_edges = -1;
    private int num_edges_target = -1;
    private int maxnodes = 10;
    private int interfaces[]; // keeps track of how many interfaces each router has
    private int ip = 0;         // keeps track of which ip addresses have been assigned already
    private int edge_target = 0;
    private int infinity = 2000; // very large number which is out of range of possible values
    // and will be used through out the class and its methods
    private int active[]; // states whether a node is being used in the network 0 = inactive
    // 1 = active
    private int routingalg = 0; // value is either 1 or 2 for OSPF or RIP
   
    private boolean drawwait = true;
    private boolean regenerate = false;
   
   
    /** Creates a new instance of Database */
    public Database() {
       
        graph = new int[maxnodes][maxnodes][3];  // [10]-x [10]-y they are both used for the different node
        // [3] used to 1. store weight of edge, 2. ip address of connection
        // 3. used to store which interface this edge is attached to at router x.
        // each edge stored twice once storing info for node x and once for node y
       
       
       
        interfaces = new int[maxnodes];
        active = new int [maxnodes];
       
        // each entry in each array is initialised.
        // at the moment the array is the correct size to accommodate for
        // the maximum number of nodes
       
        for(int i=0;i<maxnodes;i++) {
            active[i] = 0; // all nodes start as inactive
           
            interfaces[i] = 0; // initialises all nodes' # of interfaces to 0.
           
            for(int j=0;j<maxnodes;j++) {
                Thread.yield();
                graph[i][j][0]=-1; // invalid weight (will b changed as new nodes are added)
                graph[i][j][1]=-1; // invalid address
                graph[i][j][2]=-1; // invalid interface IP address
            }
        }
       
    }
   
    public synchronized void reset() {
        for(int i=0;i<maxnodes;i++) {
            active[i] = 0; // all nodes start as inactive
           
            interfaces[i] = 0; // initialises all nodes' # of interfaces to 0.
           // Thread.yield();
           
            for(int j=0;j<maxnodes;j++) {
                graph[i][j][0]=-1; // invalid weight (will b changed as new nodes are added)
                graph[i][j][1]=-1; // invalid address
                graph[i][j][2]=-1; // invalid interface IP address
            }
        }
    }
   
    public synchronized void generate_random_graph() {
       
        int correct = 0;  // used for validation. Changed to show state of
        // correctness
       
       
        while(correct == 0) {
            correct = 1;
            String nodes = JOptionPane.showInputDialog("How many nodes would you like \n the network to have (3-" + maxnodes + ")");
           
            try {
                num_nodes_target = Integer.parseInt(nodes);
            }
           
            catch(NumberFormatException nf) {
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, please only enter whole numbers.");
            }
           
            if(correct==1 && (num_nodes_target>maxnodes||num_nodes_target<3)) {
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, number entered out of range");
            }
        }
       
        correct = 0;
        while(correct == 0) {
           
            int upperrange = (int)(((num_nodes_target*num_nodes_target)-num_nodes_target)/3); //getting the number of edges to 2/3 of the maximum number
           
            if(upperrange<num_nodes_target) {
                upperrange = num_nodes_target;
            }
           
            correct = 1;
            String edges = JOptionPane.showInputDialog("How many connections would you like the network to be \n generated with (between "+ num_nodes_target + " and " + upperrange + ")");
           
            try {
                edge_target = Integer.parseInt(edges);
            }
           
            catch(NumberFormatException nf) { // if invalid input is input, the exception is caught here
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, please only enter whole numbers.");
            }
           
            if(correct==1 && (edge_target>upperrange||edge_target<num_nodes_target)) //making sure it is not out of range
            {
                correct = 0;
                JOptionPane.showMessageDialog(null,"Invalid input, number entered out of range");
            }
        }
       
        for(int i=0;i<num_nodes_target;i++) {
            Thread.yield();
            for(int j=0;j<num_nodes_target;j++) {
                graph[i][j][0] = infinity;
                graph[j][i][0] = infinity;
            }
        }
       
        int rand = -1;
        int rand2 = -1;
       
        for(int count = 0; count!=num_nodes_target; count++) // attaches at least 1 edge to all nodes
        {
            rand = count;
           
            while(rand == count||((graph[count][rand][1] != infinity)&&(graph[count][rand][1] != -1)))
                // makes sure that edges do not start and finish at the same node and that edge
                // being added does not already exist
            {
                Thread.yield();
                rand = (int)(num_nodes_target*Math.random());
            }
           
            add_edge(count, rand, (int)((10 * Math.random()) + 1));
           
        }
       
        while(num_edges!=edge_target) // places all remaining requested edges onto graph
        {
            rand2 = rand;
            while(rand==rand2||((graph[rand][rand2][1] != -1)&&(graph[rand][rand2][1] != infinity))) // same as above checking conditions
            {
                rand = (int)(num_nodes_target*Math.random());
                Thread.yield();
                rand2 = (int)(num_nodes_target*Math.random());
            }
           
            add_edge(rand, rand2, (int)((10 * Math.random()) + 1));
        }
       
       
       
    }
   
    synchronized public int add_node()  // returns if adding node was successful
    {
        int i = 0;
        for(i=0; i<maxnodes; i++) {
           
            if(active[i]==0) {
               
                for(int j=0;j<maxnodes;j++) {
                    Thread.yield();
                    if(active[j]==1) {  // if node is active set distance to infinity
                        graph[i][j][0] = infinity;
                        graph[j][i][0] = infinity;
                    }
                }
               
                active[i]=1; // node activated
                num_nodes++;
               
                return i; // adding a node was successful and return which node was activated
            }
        }
        return -1; // adding was unsuccessful as grid is full
    }
   
    synchronized public void deletenode(int x) {
        for(int j=0;j<maxnodes;j++) {
            if(active[j]==1&&(graph[x][j][0] != -1) && (graph[x][j][0] !=infinity))
                // checks if edge present here
            {
                delete_edge(x, j, 1);
            }
           
            if(active[j]==1&&(graph[x][j][0] == infinity)) {
                graph[x][j][0] = -1;
                graph[j][x][0] = -1;
            }
        }
        active[x] = 0;
       
        num_nodes--;
       
    }
   
    synchronized public void add_edge(int x, int y, int value) {
       
        interfaces[x]++;
        interfaces[y]++;
        ip++;
        num_edges++;
       
        if(active[x]==0) // if inactive->activate
        {
            for(int i=0;i<maxnodes;i++) {
                graph[x][i][0] = infinity;
                graph[i][x][0] = infinity;
            }
           
            active[x]=1; // node activated
            num_nodes++;
        }
       
        if(active[y]==0) // if inactive->activate
        {
            for(int i=0;i<maxnodes;i++) {
                if(active[i]==1) {
                    graph[y][i][0] = infinity;
                    graph[i][y][0] = infinity;
                }
            }
           
            active[y] = 1; // node activated
            num_nodes++;
        }
       
       
       
        graph[x][y][0] = value;
        graph[y][x][0] = value;
        graph[x][y][1] = ip; // assigns the connection the appropriate ip address
        graph[y][x][1] = ip;
        graph[x][y][2] = interfaces[x]; // assigns the appropriate interface to the
        graph[y][x][2] = interfaces[y]; // connection
       
    }
   
    synchronized public void delete_edge(int x, int y, int del) { // del is to see whether or not node x
        // is bing deleted or not (values 1 or 0)
        num_edges--;
        int w = -1; // used to set values corresponding with whether or
        // not node x has been deleted
        if(del==1) {
            w = -1;
        }
       
        else {
            w = infinity;
        }
       
        graph[x][y][0] = w;
        graph[y][x][0] = w;
        graph[x][y][1] = -1;
        graph[y][x][1] = -1;
        graph[x][y][2] = -1;
        graph[y][x][2] = -1;
       
    }
   
    public synchronized int getnodeinfo(int x, int y, int i) {
        return graph[x][y][i];
    }
   
    public synchronized int getnodes() {
        return num_nodes;
    }
   
    public synchronized int getactive(int x) {
        return active[x];
    }
   
    public synchronized int returnalg() {
        return routingalg;
    }
   
    synchronized public void setroutingalg(int x) {
        routingalg = x;
    }
   
    synchronized public int maxnodes() {
        return maxnodes;
    }
   
    synchronized public void makewait(boolean r) {
        drawwait = r;
    }
   
    synchronized public boolean getdrawwait() {
        return drawwait;
    }
   
    synchronized public boolean getregenerate()
    {
        return regenerate;
    }
   
    synchronized public void setregenerate(boolean set)
    {
        regenerate = set;
    }
}

The graph class: ---------------------------------------------------------------------------------------------------------------------------

import java.awt.*;
import java.util.*;
import java.lang.*;
import java.lang.String.*;
import javax.swing.*;
/**
 *
 * @author  Andy
 */
public class Graph extends Canvas implements Runnable {
   
    private int coord[][];
    private Database data;
    private int maxx = -1;
    private int maxy = -1;
    private int originx = -1;
    private int originy = -1;
    private int radius = -1;
    private int numnodes = -1;
    private double angle = -1;
    private int maxnodes = -1;
    private int x = 0;
   
    //    public Thread drawing = new Thread(this);
   
   
    /** Creates a new instance of Graph */
    public Graph(Database d) {
        data = d;
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        maxx = (int) ((471/1024)* (-60 + (int) dim.getWidth()));
        maxy = (int) ((304/738)* (-90 + (int) dim.getHeight()));
        originx = (int) maxx/2;
        originy = (int) maxy/2;
        radius = maxy - 30;
        maxnodes = data.maxnodes();
       
       
        coord = new int[maxnodes][2]; // used to store the co-ordinates of the nodes
       
        for(int i=0;i<maxnodes;i++) {
            Thread.yield();
            coord[i][0]=-1; // invalid co-ordinate
            coord[i][1]=-1; // invalid co-ordinate
           
        }
       
       
       
    }
   
    public void start() {
        Thread drawing = new Thread(this);
        System.out.println(drawing.getName());
        drawing.setName("PaintingThread");
        drawing.start();
    }
   
    public synchronized void refresh() {

        notify();
    }
   
   
    public void run() {
        while(true) {
            if(data.getdrawwait()==true) {  // flag set in anither thread
               
               
                synchronized (this) {
                    System.out.println("We are in synchronized");
                    try {
                        wait();
                    }
                    catch (Exception ex) {
                        System.out.println("Interrupted");
                    }
                }
                if(data.getregenerate()==true) {
                   
                    data.reset();
                    Thread.yield();
                    data.generate_random_graph();
                    data.setregenerate(false);
                }
                repaint();
                System.out.println("We are just after repaint");
                data.makewait(true);
            }
        }
    }
   
    public void paint(Graphics g) {
        double totangle = 0;
        numnodes = data.getnodes();
        maxnodes = data.maxnodes();
        angle = 360/numnodes;
       
        setForeground(Color.black);
        setBackground(Color.white);
       
        if(numnodes > 1) {
           
            System.out.println(numnodes);
            for(int i = 0; i!=numnodes; i++) {
                Thread.yield();
                String j = String.valueOf(i);
                coord[i][0]=(int)((radius* Math.sin(totangle)) + originx);
                coord[i][1]=(int)((radius* Math.cos(totangle)) + originy);
                setForeground(Color.black);
                g.fillOval(coord[i][0]+100,coord[i][1]+100,20,20);
                // setForeground(Color.white);
                g.drawString(j, coord[i][0] + 100, coord[i][1] + 100);
                totangle = totangle+angle;
            }
        }
        else {
            setForeground(Color.white);
            g.fillOval(15,15,20,20);
        }
       
    }
   
}

I would suggest that you compile and run the code urself so u can see the prob (as I have submitted all the code this time). Any help would be greatly appreciated.

Andy
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>
Project.java:41: cannot resolve symbol
symbol  : class FilterLight
location: class Project
         FilterLight light = new FilterLight();
>>
CERTIFIED EXPERT
Top Expert 2016

Commented:
Preferably post a link to a jar containing both source and *compiled* binary

Author

Commented:
dont worry, i dont use that anymore, just comment it out.
CERTIFIED EXPERT
Top Expert 2016

Commented:
There are unfortunately quite a few other errors too. At the moment i can't compile to 1.4 but *can* run it (don't ask...)

Author

Commented:
what compiler do u use? Cos that might b one of my probs.
CERTIFIED EXPERT
Top Expert 2016

Commented:
Sun JDK 1.3

Author

Commented:
what java package does that come with?

Author

Commented:
never mind, found it
CERTIFIED EXPERT
Top Expert 2016

Commented:
You don't need to worry about *how* you compile it - just as long as it is compiled
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
What you need to do is seperate your data collection (and perform that from edt) from your data processing (and do that in background thread).

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.