Solved

NullPointerException in update(Graphics g)

Posted on 1997-06-09
5
267 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
solarwind tftp server 2 45
Java Options in Zimbra Server 2 46
replace a word with other 1 40
Way to decrease size of apk file 9 45
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 will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

895 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

15 Experts available now in Live!

Get 1:1 Help Now