Multithread considerations

Hi all,

This is related to jMEPhysics2 development, so I'm putting it here, not in the development group.

I'm trying to develop a project similar to Robocode, but with the complexity of a 3D scene and realistic physics simulation. I found an issue (not manifested in tests yet) with the multithreaded nature of the code. Each Tank (robot) will be "controlled" by it's own thread, as in robocode. For doing this, I'm implementing safe methods for operating on the tank behavior, like accellerate, or turnWheels, etc. The thing is: the tank thread will change the values of the availableAcceleration and desiredVelocity of the RotationalJointAxis, indirectly.

The issue is:

These attributes are going to be read by the update/render thread, without any safety. Is there a change this thread can get STALE values of them? Would it be really harmfull for the performance using VOLATILE attributes instead?

I think this is the same as putting physics and render in different threads. Is jMEPhysics2 safe in that matter? Does the possible altering of instructions order, by the JVM and CPU, affect the rendering in this case, showing unstabble, invalid state node objects?

I'd really like to discuss this matter with you guys, since we're going to need this more and more every day.

jME is not thread safe. What I think you should do is have a lock Object, and synchronize it during rendering. Then use the same lock to protect your methods changing your robots. In this way, you will never be able to render while updates are being performed.

And yes… the objects should be made volatile if you want to guarantee accuracy.

As duenez I'd also suggest to synchronize access yourself (externally). Double-buffering all the values in jME Physics 2 does not sound like a good idea.

Take a look at ReentrantLock rather than synchronizing on an object…it's a much nicer way of locking.

Nice, I didn't know Java had this type of locking for synchronization  XD . They apparently were introduced in 1.5. Thanks Darkfrog!!

Sure, and the ConcurrentLinkedQueue and ConcurrentHashMap also come in quite handy when dealing with multithreaded application design. :wink:

Thank you for the guidelines guys. I'm right now digesting the book Java Concurrency in Practice and I'll put my hands on the code later on. One thing that is not clear for me is this:

Should I put this synchronization code inside jMEPhysics? Like hacking the code, sppliting it from the cvs's HEAD

Sorry for the last post.

I figured out how I could make a lock object externally. I'll wait until I finish the book and see the other options around, since they seem to be more performant. I'll keep you up to date with this, if it's of any interest.