I have 2 separate threads in an application that does some graph theory simulations (using Java2D), one executes ~60 times per second and its task is rendering. The other one executes ~30 times per second and does some calculations.
Both of these threads share resources. To be specific, they share collections which they iterate through. A problem occurs when both of these threads access a collection at the same time. (One is trying to render objects in it, while the other is modifying the collection). That results in a ConcurrentModificationException. I've tried some solutions and one that I figured out is working properly (and is easy to implement) is using an empty object that the threads switch holding a lock on.
Like so (example code):
public class Question {
static Object syncObject;
public static void main(String []Args) {
syncObject = new Object();
Runnable rendering = new Runnable() { //called 60 times a second
public void run() {
synchronized(syncObject) {
//doRendering
}
}
};
Runnable calculations = new Runnable() { //called 30 times a second
public void run() {
synchronized(syncObject) {
//doModifications
}
}
};
Thread t1 = new Thread(rendering);
Thread t2 = new Thread(calculations);
t1.start();
t2.start();
}
}
Now, this seems to work properly. This way I dont have to synchronize every single resource I'm working with that might be modified at the moment of rendering as well as the "logic" calculations update.
But I feel like this is not a very good solution tho. So I want to ask if this is somewhat acceptable and/or if there is a more proper solution. (Unless what I'm doing is completely wrong)
Also I don't want to rewrite half of the existing code that I've been working on for a while.