Solved

NullPointerException in update(Graphics g)

Posted on 1997-06-09
5
274 Views
Last Modified: 2010-08-05
Why am I always getting NullPointerExceptions in this update method:


public synchronized void update(Graphics g) {

    Color plotColor;

    left = 10;
    right = monitor.location().x-5;
    floor = bottomPanel.location().y-50;
    length = right - left;
    inc = length/11.00;

    if(offscreenG == null) {
        offscreenImg = createImage(size().width, size().height);
        offscreenG = offscreenImg.getGraphics();
    }

    if(trajG == null) {
        trajImg = createImage(size().width, size().height);
        trajG = trajImg.getGraphics();
        drawOldTrajectories(trajG);
    }

    offscreenG.drawImage(trajImg,0,0,this);

    if(running) drawCurrentTrajectory(offscreenG);
   
    drawFloor(offscreenG);
    drawCannon(offscreenG);
    g.drawImage(offscreenImg,0,0,this);
}

  All of the drawXxx methods are declared synchronized.  I get the exception within these draw methods, usually the last time my run() method calls it (the update).  
Here is my run() method:

public void run() {

    Double tempDouble;
    tempDouble = new Double(angleField.getText().trim());
    theta = (tempDouble.doubleValue())*Math.PI/180;
    double c1 = Math.tan(theta);
    int vel = this.vel.getValue();
    double c2 = g/(2*vel*vel*Math.cos(theta)*Math.cos(theta));
    plotX = plotY = 0;
    points.removeAllElements();

    double R = c1/c2;


    long t = System.currentTimeMillis();
    for(double i = 0; i<=R/2; i+=(5/inc) ){
        plotX = (int)(inc*i) + left;
        plotY = floor - (int)(inc*(c1*i - c2*i*i));
        points.addElement(new Point(plotX, plotY));
        repaint();
        try {
            t+=sleepTime;
            Thread.sleep(Math.max(0, t - System.currentTimeMillis()));
            }
        catch (InterruptedException e) {}
    }

    peak = (vel*vel*Math.sin(theta)*Math.sin(theta))/(2*g);
    heightField.setText(""+peak);
    repaint();

    for(double i = R/2; i<=R; i+=(5/inc) ){
        plotX = (int)(inc*i) + left;
        plotY = floor - (int)(inc*(c1*i - c2*i*i));
        points.addElement(new Point(plotX, plotY));
        repaint();
        try {
            t+=sleepTime;
            Thread.sleep(Math.max(0, t - System.currentTimeMillis()));
            }
        catch (InterruptedException e) {}
    }



    plotX = left + (int)(inc*R);
    plotY = floor - (int)(inc*(c1*R - c2*R*R));
    monitor.property[trial][2].setText(""+R);
    repaint();
   
    allPoints.setElementAt((Vector)points.clone(),trial);
    running = false;
    offscreenG = null;
    trajG = null;
    repaint();

}
0
Comment
Question by:brecht
  • 3
  • 2
5 Comments
 
LVL 3

Accepted Solution

by:
garik earned 100 total points
ID: 1221448
Drawing methods are long methods; therefore, it's possible (assuming that you're right and the problem is in synchronization) that some thread comes to the end of your run() method while the other thread is in the middle of update(). I'd try to synchronize nulling of GCs on something like you "running" variable:

public void run()
{
  ...
  synchronized(running) {
    running = false;
    offscreenG = null;
    trajG = null;
  }
  repaint();
}

public void update()
{
  ...
  synchronized(running) {
    if(offscreenG == null) {
      offscreenImg = createImage(size().width, size().height);
      offscreenG = offscreenImg.getGraphics();
    }
    if(trajG == null) {
      trajImg = createImage(size().width, size().height);
      trajG = trajImg.getGraphics();
      drawOldTrajectories(trajG);
    }
    offscreenG.drawImage(trajImg,0,0,this);
    if(running) drawCurrentTrajectory(offscreenG);
                     
    drawFloor(offscreenG);
    drawCannon(offscreenG);
    g.drawImage(offscreenImg,0,0,this);
  }
}

With this synchronization no threads can set to null your GC's while some thread is doing update().
Somehow I've a feeling that synchronization is not the problem in your case. If it's so, more code would help to localize the problem.
0
 

Author Comment

by:brecht
ID: 1221449
This basically worked.  I can't sycnhronize on "running", because its not an Object, so I just synchronized on "this".  That seems to work, but do you foresee any problem in doing that?
0
 
LVL 3

Expert Comment

by:garik
ID: 1221450
The only problem might be reduced multi-threading efficiency, since you lock the whole applet during update, but if the number of simultaneously running threads is not too big, that shouldn't bother. If some applets "freeze" on update, then you migth consider reducing the scope of the object for synchronization.
0
 

Author Comment

by:brecht
ID: 1221451
The thing is, I just don't know much about using synchronization.  I've just seen examples in books where they declare a method synchronized, or synchronize on some variable, but I don't really have a good feel for it.  What else could I use synchronize on besides "running" or "this" ?
0
 
LVL 3

Expert Comment

by:garik
ID: 1221452
You can synchronize on any variable of the reference type. F.ex., you could use offscreenImg or trajG for synchronization - any object that identifies overlapping area of interest for the concurrent threads. But before you dive into multithreading and synchronization, I'd suggest to work more on your existing code, clean it up. Don't be afraid to use more methods - it'd not only improve the readability of your code, but could also better define sections dealing with particular objects and ease significantly synchronization in the future. Try to really think through the concept of object oriented programming - it helped me, anyway :)
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How do I remove an object from a 3 40
Problem to Alipay 10 48
Notify sent to other threads in Java 9 34
Coding for the first time 9 37
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question