Question

I'm going to share a Matrix class between multiple threads in Java. The Matrix class is: https://github.com/vkostyukov/la4j/blob/master/src/main/java/org/la4j/matrix/sparse/CRSMatrix.java

and the only method i'm going to call is getting a row which is defined by the following code:

@Override
public Vector getRow(int i) {

    int rowCardinality = rowPointers[i + 1] - rowPointers[i]; 

    double rowValues[] = new double[rowCardinality];
    int rowIndices[] = new int[rowCardinality];

    System.arraycopy(values, rowPointers[i], rowValues, 0,     rowCardinality);
    System.arraycopy(columnIndices, rowPointers[i], rowIndices, 
                     0, rowCardinality);

    return new CompressedVector(columns, rowCardinality, rowValues, 
                                rowIndices);
}

So it is read-only. Would you please help me to understand if this will cause problems for my multithreaded program or i need to use synchronization or locks?

Was it helpful?

Solution

I have not looked deep, but looking at your code I can see that these 3 instance fields:

private double values[];
private int columnIndices[];
private int rowPointers[];

are shared (since they are instance fields). This means that if you provide a way to alter them, you could have issues. I mean, you call getRow in one thread, while another thread changes their contents. Of course you might have problems.

If you do not alter them (you only need to know them at creation time), make them final and set them in your constructor. And do not provide any means (methods) of changing their contents, thus making the class Immutable; thus Thread Safe.

Otherwise simple make your method synchronized.

Also, you will share an instance, and not the class. One more point, is it's always about the writers to your shared data and not the readers. Writers alter your instances, not readers.

OTHER TIPS

The fact that you’re asking the question in the first place means that you don’t have a strong enough understanding of JVM to write low-lock code, so it should be avoided. You should also avoid sharing data across threads unless it's immutable,

The class has all kinds of mutators such as update, insert, and remove and no synchronization. The class is not thread safe.

I assume you are asking because you want to reuse someone else's non-thread-safe class in your own multithreaded program.

There needs to be some synchronization between the thread that creates the object and the threads that use it. For example if

  1. Thread A creates the object
  2. Thread A releases a lock
  3. Thread B acquires the same lock
  4. Thread B reads from the object

then you should be ok.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top