Solved

NullPointerException in update(Graphics g)

Posted on 1997-06-09
5
264 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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:

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now