JOML-CI / JOML

A Java math library for OpenGL rendering calculations
MIT License
729 stars 104 forks source link

Advice on thread safety #296

Closed tlf30 closed 3 years ago

tlf30 commented 3 years ago

Hello, I looking for advice on using JOML in a multi-threaded environment where multiple threads may read/modify joml objects (Matrix/Vector/Quaternion/etc...). Synchronous access would be fine for my use case, but currently not implemented in JOML (and for good reason as it will impact performance).

Is there any recommended method for handling this? Or is there any interest in adding a set of thread-safe variants for the existing objects in joml, perhaps as a separate package?

Thanks, Trevor

pollend commented 3 years ago

why would JOML need to manage write access? you can just guard it in a synchronization block or mutex. I don't know what your use case would be though?

tlf30 commented 3 years ago

Hello @pollend, I am working on a library for multi-threaded rendering/simulation. For this years major release, we are removing an in-house math library and moving to joml. I am trying to restrict the number of possible issues from the user code side where the user could potentially corrupt the joml object's contents by writing to it when the library is reading/writing it from another thread.

When possible I want to avoid synchronization, that is why I figured I would ask to see how others handle this.

After playing with it yesterday, I have a rough draft for a pattern that may help prevent situations like that. It is not perfect, but much better than what I started with.

public class Location {
    private volatile Vector3dc position = new Vector3d();
    private volatile Quaternionfc rotation = new Quaternionf();
    private volatile Vector3fc scale = new Vector3f(1f, 1f, 1f);

    public Vector3dc getPosition() {
        return position;
    }

    public void setPosition(Vector3dc position) {
        this.position = position;
    }

    public Quaternionfc getRotation() {
        return rotation;
    }

    public void setRotation(Quaternionfc rotation) {
        this.rotation = rotation;
    }

    public Vector3fc getScale() {
        return scale;
    }

    public void setScale(Vector3fc scale) {
        this.scale = scale;
    }

By using the read only views I can restrict (or at least impress on end users) to not modify the contents after setting the object.

Just looking for suggestions.

Thank you, Trevor

httpdigest commented 3 years ago

I'm converting this to a "Discussion". It fits discussions better than issues since it requests for advice and opinion and seems to be more of the "long running" kind of thing as there is no apparent definition for when the things being asked for have been sufficiently provided.