Toxiclibs: many instances of VerletPhysics2D


II would love to use this cool library for a project.
In this project I have many closed physic systems, which need to be computed parallel, like parallel physics worlds.
The question is if it is possible to use many instances of VerletPhysics2D simultaneuslly?
Something like:
VerletPhysics2D physics1, physics2, … , physicsN ;

Thankyou in advance

Yup! We can have as many instances of that class as we want! :ok_hand:

However, multiple instances of some class got nothing to do w/ multithreading! :thread:

If a particular instance of a class is accessed by more than 1 thread, and at least it is mutated by 1 of those threads, all of those accesses may need to be synchronized () { }! :face_with_monocle:

AFAIK, all Processing’s 3rd-party libraries don’t use any synchronization internally. :sweat:

Therefore, it’s up to us to use that ourselves if we have multithreading access in our sketches. :woozy_face:

Thank you for the fast response!
I will try to synchronize.
Could you give me an advice how to implement it in Processing?

  • Let’s say you’ve got an array of 10 VerletPhysics2D objects.
  • Among them, the VerletPhysics2D object w/ index 4 is the only 1 being accessed by more than 1 Thread.
  • So any method which mutates that particular object, like update(), addParticle(), etc., needs to be inside a synchronized () block.
 * Synchronized VerletPhysics2D Example (v1.1)
 * GoToLoop (2019/Jan/12)

import toxi.physics2d.VerletPhysics2D;
import toxi.physics2d.VerletParticle2D;

static final int PHYSICS = 10;
final VerletPhysics2D[] physics = new VerletPhysics2D[PHYSICS];

void setup() {
  size(300, 200);
  for (int i = 0; i < PHYSICS; physics[i++] = new VerletPhysics2D());
  thread("intervalAddParticleIndex4"); // Make a thread to deal w/ physics[4]

void draw() {

  for (final VerletPhysics2D phy : physics) {
    if (phy == physics[4])  synchronized (phy) {
      phy.update(); // synchronized update() for physics[4]
    } else phy.update(); // non-synchronized update() for the rest

  surface.setTitle("phy4: " + physics[4].particles.size());

void intervalAddParticleIndex4() {
  final VerletPhysics2D phy4 = physics[4];

  for (;; delay(1000))  synchronized (phy4) { // adds 1 particle per second
    phy4.addParticle(new VerletParticle2D(random(width), random(height)));