I'm building a (concurrent) simulator for a set of N particles that are moving in a space according to the Newton's laws. My idea is model each particle as a task, which interacts with other particles (tasks) in order to get their positions and masses in order to calculate the net force it is subject to. Each particle-task is something as
while(true){
force = thisParticle.calculateNetForce(allTheParticles);
thisParticle.waitForAllTheParticlesToCalculateNetForce(); // synchronization
thisParticle.updatePosition(force);
thisParticle.waitForAllTheParticlesToUpdateTheirState(); // synchronization
}
I can have a lot of particles (100 or more), so I can't create such a number of Java threads (which are mapped to physical threads).
My idea is to use Runtime.getRuntime().availableProcessors()+1
threads onto which the many tasks can be executed.
However, I can't use a FixedThreadExecutor because the particle-tasks does not end. I would like to use a FixedThreadExecutor which must be also able to perform a sort of scheduling internally. Do you know something for this purpose?
Or, could you suggest me better approaches for modelling such a system by a point of view of concurrency (e.g. a different task decomposition) ?
P.s.: I am limited to "classical" concurrency mechanisms, not including actors or similar architectures.
thisParticle.waitForAllTheParticlesToCalculateNetForce();
effectively waits for something (via an actual wait or a CountdownLatch/CyclicBarrier/Phaser etc.), the thread in which that method is run will be returned to the pool and be available to other tasks. Not sure I understand why your FixedThreadPool approach would not work. – ZobiasPROCESSORS+1
tasks get executed. – Dabbsawait
is a non blocking call: the thread becomes idle until all parties have calledawait()
. So unless you hold a lock when calling await, the other tasks should be able to use that idle thread. It might be worth posting some of your code. – Zobiasawait
will wait/block until all parties are awaiting. In your case, only two threads will trip the barrier and wait indefinitely. Once all ten threads invoke await then you the rest of the method will continue. – Asbestos