Java threading is a world of trouble. Typically, in java programs you will have at least three threads
active at all times - the “mouse” thread, the “repaint” thread, and the main application run loop.
You basically have two choices:
Be very, very careful every time to manipulate a data structure to consider what might happen if one
of the other threads ran “right now”, and combat concurrency issues with careful use of synchronized
primitives. Getting this right, and keeping it right, is a never ending struggle. You’re very likely to either
miss an important synchronization issue, or to overuse synchronization and end up with deadlocks.
The nastiest aspect of this design is that programs seem to work, because the bugs are only exposed
by infrequent timing windows. These problems are practically impossible to debug because they are
very hard to reproduce.
The other choice is to coerce your program back into a single threaded model, so that every piece of
code is executed in exactly one thread, and a few critical data changes are protected with synchronization.
Personally, I do EVERYTHING to one thread. In my applets, the mouse and canvas repaint threads
just quickly note the activity and exit without doing any real work. All the substantial code runs
in the main event loop, which can safely assume that everything is happening serially in exactly
the sequence it naturally provides.