java - Synchronized method seems interrupted -
i'm writing applet multiple threads. i've had strange problems i've tracked them down class below. it's entire code, no snips.
public class boundingbox { private volatile int top; private volatile int left; private volatile int bottom; private volatile int right; public static final int ignore = 0; public static final int top = -2; public static final int left = -1; public static final int bottom = 2; public static final int right = 1; boundingbox(int left, int top, int width, int height) { this.top = top; this.left = left; this.right = left + width; this.bottom = top + height; } public synchronized int top() { return top; } public synchronized int left() { return left; } public synchronized int bottom() { return bottom; } public synchronized int right() { return right; } public synchronized int width() { return right - left; } public synchronized int height() { return bottom - top; } public synchronized void translate(vector2d vector) { left += vector.getx(); right += vector.getx(); top += vector.gety(); bottom += vector.gety(); } public synchronized void alignto(point2d point, int halign, int valign) { if ((halign != ignore && halign != left && halign != right) || (valign != ignore && valign != top && valign != bottom)) throw new illegalargumentexception(); /// start debug code /// if (right - left != width()) system.out.println("x"); if (bottom - top != height()) system.out.println("y"); /// end debug code /// int width = width(); int height = height(); if (halign != ignore) { left = point.getx(); if (halign == right) left -= width; right = left + width; } if (valign != ignore) { top = point.gety(); if (valign == bottom) top -= height; bottom = top + height; } } }
x
, y
print sometimes. can see, width()
defined right - left
, still happens these 2 aren't equal (same height()
). 4 fields private , methods synchronized, nothing should interrupt alignto
, right? still, seems me.
what's wrong code?
declaring top, left, bottom, right volatile not enough keep them synchronized in way need. problem is, variables being modified on different threads using translate method, changing during execution of alignto. need put lock on variables duration of alignto, or cache them local variables.
Comments
Post a Comment