Box2D Java

ewjordan wrote:
- Is your app multi-threaded by any chance? I'm wondering if maybe the UI thread is altering some of the data concurrent with the simulation or something like that. None of this is thread safe, so that could definitely cause some problems.

That statement gives me some headaches because my application is multi-threaded. As a result it freezes from time to time since I have assertions enabled. I think there are three alternatives:

    1) Change my way of calling JBox2D methods (not that easy because of multi-threaded 3rd party code)
    2) Turn off assertions and pray
    3) Tune the JBox2D code in that way, that whenever the "m_lock" field is accessed instead of an assertion some synchronization code is executed

From looking into the code it looks like option number 2 will hardly work because vital methods will exit before doing stuff.
Do you think alternative number 3 is worth a shot? Probably with some classes of the concurrency package (http://java.sun.com/docs/books/tutorial ... level.html) it's possible to let multiple threads call methods of the world object without exceptions and methods guaranteed to be executed. Hm ❓

Stefan

btw: This thread is becoming a little too long to find information. Would an own JBox2D forum be a good idea?
Hm...I actually just got an e-mail from someone else today about threading problems, so maybe it's time to think about this a bit. I don't want to diverge very far from the C++, but I might consider it here since I think people are for various reasons more likely to do multi-threaded stuff in Java, and it might be easier to make things safe in a cross-platform manner than it would be in C++...

At the moment, though, I just don't know enough about how to avoid hurting performance when writing thread safe code in Java to go through the engine and try to do this now. Since the main "supported" use of the engine is within a single threaded environment (or at least an environment where the physics is only modified from one thread), I don't want to cause speed penalties in that case.

Perhaps someone that knows more can give advice on this. What we would need to do is make sure that the step method completes without any physical quantities being modified. If there's a way to do this without sacrificing speed in the single threaded case, I'm happy to put it in. It might be true that the main things to worry about are the m_lock bits of code, though there might be a few other scattered areas that would be important.

The only workarounds I can suggest at the moment are to either handle the locking yourself (which might be a pain if you're calling physics methods from all over the place) or at least make sure any physics alterations are all happening on the physics thread.

I've never tried the concurrency package, I'll take a look and see if it looks like it would help.

Erin, are you planning anything along the lines of thread safety for the C++ code at any point in the future?
Could you post use cases how multi threads are used with JBox2d? I have experience with the concurrency package and most of my work are involved in high performance messaging systems which uses that package a lot to handle simultaneous messages.

Besides that I have people at work who have implemented part of the JVM (IBM JVM) as well as other brilliant Java guys that I can talk to.
@makas: I myself have never done anything multi-threaded with JBox2d (more precisely, I've never done anything where the physics engine is touched from more than one thread), so maybe someone else can comment on that? I'm assuming it mostly comes down to either a) running physics on a separate thread from control and drawing so that its timing is independent of frame rate, or b) getting input events that trigger physical actions off of another thread. But I'm not sure, so maybe someone that's doing stuff like that can give some more detail, or at least an example or two.
I agree that for the Java port only a very slim solution which does not require any relevant changes from the C++ version is reasonable.

My first naive idea would be to identify those methods of the world class which may not be executed concurrently (step, createBody, destroyBody etc.) and find a mechanism to synchronize the access to these methods. Probably a simple ReentrantLock object would do?
@ewjordan: would this strategy be sufficient to avoid multi-threaded problems?
@makas: could this serve as a use case for you?

fyi: My application runs independant of any frame rate but additionally to the "world.step"-calling-thread other threads try to create and destroy bodies.
Boing wrote:
I agree that for the Java port only a very slim solution which does not require any relevant changes from the C++ version is reasonable.

My first naive idea would be to identify those methods of the world class which may not be executed concurrently (step, createBody, destroyBody etc.) and find a mechanism to synchronize the access to these methods. Probably a simple ReentrantLock object would do?
@ewjordan: would this strategy be sufficient to avoid multi-threaded problems?
@makas: could this serve as a use case for you?

fyi: My application runs independant of any frame rate but additionally to the "world.step"-calling-thread other threads try to create and destroy bodies.


Hmm, I still can't really see why the application needs to create and destroy bodies on a separate threads (new threads each time?) to the one calling world.step().

Isn't the recommended practice (for games) to have a single thread looping to capture inputs, update the game state and render it on screen? That seems like a reasonable practice to me instead of using the AWT Event thread to do stuff when an input event arrives.

Or perhaps the use case isn't very clear to me.

But if you *really* have to be multi threaded, then perhaps the easiest way is to synchronize on the world object itself? E.g
Code:
public void step()
{
    synchronized( world )
    {
        world.step();
    }
}

public void modifyWorldObjects()
{
    synchronized( world )
    {
        world.addBody();
        world.removeBody();
    }
}
Well, I wouldn't want to dive too deep into my special case which is a little complex because of the mentioned 3rd-party-component.
My basic idea was simply to change the JBox2D code in a way that at those places where currently an assertions fails instead of that the thread just waits until the ressources are free. If this could be done easily (what I cannot say) it would be a nice enhancement since it would hardly affect the single-threaded usage.

But thinking about it, it's probably less error-prone to put some effort into channeling the access of JBox2D through a single thread, which is probably the "cleanest" approach.
Boing wrote:
Well, I wouldn't want to dive too deep into my special case which is a little complex because of the mentioned 3rd-party-component.
My basic idea was simply to change the JBox2D code in a way that at those places where currently an assertions fails instead of that the thread just waits until the ressources are free. If this could be done easily (what I cannot say) it would be a nice enhancement since it would hardly affect the single-threaded usage.

But thinking about it, it's probably less error-prone to put some effort into channeling the access of JBox2D through a single thread, which is probably the "cleanest" approach.



Hmmm, for JBox2D to synchronize the calls to it will impose unnecessary overheads for those single threaded applications.

I would suggest that one extends World as SynchronizedWorld then override the method to add synchronized for the ones that has assert (lock). At least the single threaded application does not need to suffer any penalties by using the "unsync" World. E.g

Code:
public SynchronizedWorld extends World
{
     public synchronized void step()
     {
          super.step();
     }

     public synchronized void createBody()
     {
          super.createBody();
     }
}
The idea of the SynchronizedWorld class sounds good, but simply synchronizing the methods won't make it thread-safe since problems occur when different threads call different methods. You would need to synchronize an instance variable, probably at the places where currently the m_lock flag occurs.
Boing wrote:
The idea of the SynchronizedWorld class sounds good, but simply synchronizing the methods won't make it thread-safe since problems occur when different threads call different methods. You would need to synchronize an instance variable, probably at the places where currently the m_lock flag occurs.


Um, it doesn't matter if different threads are calling different methods as long as those methods have the "synchronized" keyword declared in their method. What that effectively means is

Code:
public synchronized void doSomething()
{
    // Do something....
}
// Is equivalent to
public void doSomething()
{
    synchronized( this )
    {
         // Do something....
    }
}


Which means, different threads calling different method to the same World instance is queued. Perhaps this will help you understand Java threading better http://java.sun.com/docs/books/jls/thir ... ml#8.4.3.6

Original thread: https://box2d.org/forum/viewtopic.php?t=36