I'm working on a class that holds an Image and paints it centered on 0, 0; for this, it retrieves the height and width of the image and bases its display offset on those values. But, in making it an ImageObserver in case the image is not yet fully loaded, I'm leaking this
in the constructor:
public class Sprite extends SimplePaintable implements ImageObserver {
private final Image sprite;
private int xOffset;
private boolean xOffsetSet;
private int yOffset;
private boolean yOffsetSet;
public Sprite(Image sprite) {
this.sprite = sprite;
//warning: leaking this in constructor
int width = sprite.getWidth(this);
xOffset = width/2;
xOffsetSet = width != -1;
int height = sprite.getHeight(this);
yOffset = height/2;
yOffsetSet = height != -1;
}
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
assert img == sprite;
if ((infoflags & WIDTH) != 0) {
xOffset = width / 2;
xOffsetSet = true;
}
if ((infoflags & HEIGHT) != 0) {
yOffset = height / 2;
yOffsetSet = true;
}
return !(xOffsetSet && yOffsetSet);
}
...
At first I thought this was fine, as only the offset variables were uninitialized and their default values were fine for (not) displaying an unloaded image, but then I realized that if the image loaded immediately as getWidth(this)
was called, it could theoretically call imageUpdate
before the constructor finished, causing the offsets to be set properly in imageUpdate
, and then be unset by the constructor. Is this a concern, or are images only loaded synchronously on the EDT? If this is a concern, would making imageUpdate a synchronized
method prevent it from running until the constructor finished?
this
from within a constructor. The issue (as you surmised) is that your instance hasn't been initialized yet.Image
is already loaded,observer
can benull
.Image.getWidth
is guaranteed not to callimageUpdate
until after the constructor is finished, then it is safe in this specific case.