I have a setup in my game where physics are updated in a separate thread with an implementation as follows
Physics Processor (Physics Thread)
public class PhysicsProcessor extends Runnable {
private DynamicsWorld world;
public PhysicsProcessor() {
/* basic dynamics world setup with dvbt broadphase :P */
}
public synchronized getDynamicsWorld() { return world; }
@Override
public void run() {
/* update time */
//update phyics
getDynamicsWorld().stepSimulation(/* delta time */);
}
}
Example Object Creation In Main Thread
myPhysicsProcessor.getDynamicsWorld.addRigidBody(/* some rigid body created here */);
The problem is that when the game runs I occasionally get a null pointer exception in the separate thread on "stepSimulation", which was caused by setAabb in my dbvt broadphase.
Does anyone have any suggestions on what I can do to prevent this exception, or how to work around it?
You could make the world
final
from the looks of it. Then that would show you the futility of synchronizing the access:You see, when you do:
myPhysicsProcessor.getDynamicsWorld().addRigidBody(...)
the synchronization stops after thegetDynamicsWorld()
returns. SoaddRigidBody(...)
is called outside of the safe synchronized context.No, what you want to do is ensure that it is always used within a sync block:
Now that's OK for one method, but if you find yourself wanting to do lots of methods of
DynamicsWorld
outside the runner in this way, or just want another choice, then this one requires no syncing:Then you would do this, to add a body:
It will get executed before the next
stepSimulation
on the same thread as that, so no thread worries.