OutOfMemoryError

Hi everyone!

im getting into learning Java, and its slow going, but im gradually getting there with it etc, but im stumped at the mo!

ive got a project that has 2 files, 1 is the main file, and the other is a seperate class (for a starfield)

the problem is the 2nd file (a class) as whenever I run the main program, i get a java.lang.OutOfMemoryError
error :’(

my main class is this:

public class fscreen extends JFrame implements KeyListener

my stars class is this:

public class stars extends fscreen

and for my star file I do this which worked on other projects (where the extends was Canvas etc unlike this project) I set it up like this:



// This is in the 'global' area
stars mystarfield;

//In the fscreen bit
mystarfield = new stars();


Now as SOON as I try to do the mystarfield = new stars(); thats when i get the memory error! I cant see whats wrong with it, apart from the only thing im trying different is the extends JFrame bit as with looking at other code etc, found more ppl use that than things like extends Canvas etc (tried that in a previous project, and i had probs trying to get the keylistener working!)

sorry to sound like a complete Newbie, but thats me! ::slight_smile: :smiley:

PS. If i copy the whole stars class into the main .java file and remove the class info and make them functions the program works fine!

Usually means you have an infinite recursive loop, like this:


void a()
{
  List l = new LinkedList();
  while( true )
  {
    l.add( "hello" );
   }
}

…which, sooner or later, obviously HAS to run out of memory.

PS: always post your affected source code or else no-one can actually help you.

Thanks.

i checked the code, but even if I remove the calls to the class ive built it still does it.
It seems to be the mystars = new stars(); that is the prob for some strange reason! ???

here’s all the code so far (basically not a lot as just using it to get to grips with working in Java etc!)

The main file (fscreen.java):


import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;

public class fscreen extends JFrame implements KeyListener
{

public static final int WIDTH = 800, HEIGHT = 600;
protected static final GraphicsDevice DEVICE = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
protected static final GraphicsConfiguration CONFIG = DEVICE.getDefaultConfiguration();
protected static final DisplayMode DISPLAY = DEVICE.getDisplayMode();

private int       keys[];

BufferStrategy      bstrat;
Canvas                  cs;
stars                   mystars;

    public fscreen()
    {
            super("Stars test",CONFIG);
            setSize(new Dimension(WIDTH,HEIGHT));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        setUndecorated(true);
            setIgnoreRepaint(true);

            cs = new Canvas(CONFIG);
            cs.addKeyListener(this);
            cs.setSize(WIDTH,HEIGHT);
            getContentPane().add(cs,BorderLayout.CENTER);
            pack();
            show();

            keys = new int[256];

        cs.createBufferStrategy(2);
        bstrat = cs.getBufferStrategy();

// This seems to be the problem line! as both other refernces to init and draw the stars are commented out yet this causes the error !

//-----------------------------------------

            mystars = new stars();

//-----------------------------------------

           //Commented out to show that the error occurs in the above line
            //mystars.init();

        loop();
    }

protected void loop()
{

      while(true)
      {
            if(keyDown(KeyEvent.VK_ESCAPE))
            {
                  System.exit(0);
            }

          Graphics2D g = (Graphics2D) bstrat.getDrawGraphics();

          g.setColor(Color.black);
          g.fillRect(0,0,WIDTH,HEIGHT);
            // Star update
            //mystars.update_stars(g);
            g.setColor(Color.red);
            g.drawString("hello",10,10);
            g.dispose();
            bstrat.show();
          
      }
}



// Main

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


// Key routines

protected boolean keyDown(int key)
{
      return (keys[key&0xff] != 0);
}

public void keyPressed(KeyEvent e)
{
      keys[e.getKeyCode()&0xff] = 1;
}

public void keyReleased(KeyEvent e)
{
      keys[e.getKeyCode()&0xff] = 0;
}

public void keyTyped(KeyEvent e)
{
}


}

and the stars.java file:


import java.util.Random;

import java.awt.*;

public class stars extends fscreen
{

// Create random numbers
      private Random lpd_rnd=new Random();

// Number of stars
      protected static final int num_stars = 200;

// Arrays for the star positions

      private int[] sx;
      private int[] sy;
      private int[] sz;

// Speed of the starsystem
      private double   SPEED = 2;

// Initialise the stars.
public  void init()
{

// Create the star coord arrays
      sx = new int[num_stars];
      sy = new int[num_stars];
      sz = new int[num_stars];

// Fill the arrays with random positions
      for(int i=0; i<num_stars-1; i++)
       {
          sx[i] = (lpd_rnd.nextInt(WIDTH)+1) - WIDTH/2;
          sy[i] = (lpd_rnd.nextInt(HEIGHT)+1) - HEIGHT/2;
          sz[i] = lpd_rnd.nextInt(256)+1;
       }

}

// Move and draw the stars
public void update_stars(Graphics mg)
{

//Temp store for current star
      int tmpx,tmpy;

      for(int i=0; i<num_stars-1; i++)
      {
               tmpx = ((sx[i]*256)/sz[i]) + WIDTH/2;
               tmpy = ((sy[i]*256)/sz[i]) + HEIGHT/2;
               if(tmpx >=0 || tmpx <=WIDTH || tmpy >=0 || tmpy <=HEIGHT)
               {
                int tsize = (256/sz[i]);
                   mg.setColor(Color.white);
                   mg.fillOval(tmpx,tmpy,tsize,tsize);
                   sz[i]-=SPEED;
               }
   // If the star is past our 'camera' then reset the star
               if(sz[i] <= 0)
               {
                 sx[i] = (lpd_rnd.nextInt(WIDTH)+1) - WIDTH/2;
                 sy[i] = (lpd_rnd.nextInt(HEIGHT)+1) - HEIGHT/2;
                 sz[i] = 256;
               }

       }
}
}

hope someone can help as its really puzzling me! (probably something REALLY simple but I jsut cant see it! hehe)

In fact … it’s PRECISELY what I said it would be.

I’m not going to tell you what’s happened (but I’ll give you a hint…see below), simply because it’s not worth you doing any more programming until you change the way you look at your code.

You are not reading your own code. You need to:

  1. get a pen + paper
  2. step through your code line by line from the line that is broken
  3. write down what’s happening
  4. keep going until you get to the point where you go “ohmygod”

Of course, 99% of people do the pen-paper part in their head :).

HINT: What happens, precisely, when you instantiate (“new [something or other]”) a class? You know that as well as calling the class’s constructor, it FIRST calls the superclass’s constructor (if it has one)…

(if you don’t know what a constructor is, or what a superclass is, or that “A extends B” marks B as a superclass of A, then you need to go read the free Sun tutorials on programming java. then come back here if you still dont undrestand)

your stars class extends the fscreen class (why ??) and doesn’t define a constructor of its own. So when you instantiate an fscreen object, in the constructor it tries to create a new stars object, which calls the fscreen constructor, which tries to create a new stars object, which calls the fscreen constructor which …

well you get the picture …
eventually you run out of mem.

D.

-edit- sorry about that blahblahblah, was obviously writing this as you were replying … -edit-

doh! scuse me while I wipe the egg from my face! :-[ ;D

as I said, im a total newbie to Java, and still trying to get my head round all this stuff! so total cockups are pretty common here at the mo! hehe…

the reason i had the extends fscreen in the stars.java file was I was trying to be lazy and not having to pass over some of the ‘global’ variables (ie the WIDTH & HEIGHT)

I see what you was getting at with the constant calling one, then the other calling the first again etc in a never ending loop!

Will go and have a read up a bit more on the constructors etc as with having so many things to look at, its hard to work out what you NEED to look at FIRST!

thanks for the help guys! much appreciated!

I would just like to say that it’s a good idea you made an error like this in Java and not C/C++. :slight_smile:

[quote]doh! scuse me while I wipe the egg from my face! :-[ ;D

as I said, im a total newbie to Java, and still trying to get my head round all this stuff! so total cockups are pretty common here at the mo! hehe…

the reason i had the extends fscreen in the stars.java file was I was trying to be lazy and not having to pass over some of the ‘global’ variables (ie the WIDTH & HEIGHT)

I see what you was getting at with the constant calling one, then the other calling the first again etc in a never ending loop!

Will go and have a read up a bit more on the constructors etc as with having so many things to look at, its hard to work out what you NEED to look at FIRST!

thanks for the help guys! much appreciated!
[/quote]

hehe I WAS wondering why whenever I ran the code my machine sounded like it was crying! ;D

as you can probably tell from my code, im more used to been sat in front of photoshop and 3ds max rather than writing code! but I thought id expand and learn Java to get a break from the gfx stuff for a bit.

been scanning through this forum and reading up a fair bit and it is gradualyl sinking in (honest! ;))

[quote]doh! scuse me while I wipe the egg from my face! :-[ ;D

as I said, im a total newbie to Java, and still trying to get my head round all this stuff! so total cockups are pretty common here at the mo! hehe…

the reason i had the extends fscreen in the stars.java file was I was trying to be lazy and not having to pass over some of the ‘global’ variables (ie the WIDTH & HEIGHT)

I see what you was getting at with the constant calling one, then the other calling the first again etc in a never ending loop!

Will go and have a read up a bit more on the constructors etc as with having so many things to look at, its hard to work out what you NEED to look at FIRST!

thanks for the help guys! much appreciated!
[/quote]
if u havent already done so, make those global variables static so that u can just use them anywhere like fscreen.WIDTH, or fscreen.HEIGHT.

K.I.L.E.R, just out of curiosity, what would’ve happened if he was using C/Cpp?

My guesses:

  1. freeze
  2. page file explosion, then 3 or 4
  3. BSOD
  4. “This program has performed an illegal operation and will be closed… operation: Stack Overflow”