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.
For each particle, you call
calculateNetForce(allTheParticles)
, which I suppose makes your computations proportional to O(N^2) (the square of the number of all particles). This is the main performance killer, and you better find an algorithm with complexity of O(N), and only then try to parallelize. Off the top of my head, I can propose to first calculate the sum mass and the center of gravity for all particles. Then, for each particle, calculate mass and the center of the rest of particles. This can be done with taking the total mass and center, and adding a "hole" with negative mass instead of the current particle. Then calculate the force between the particle and the rest of them. The calculations for each particle are independent and can be parallelized with any of ways proposed by other commenters.