I am pretty new to multithreading and want to unterstand it better. I want to now how to make an array threadsafe in Java? Meaning I have several threads accessing and changing the data in the array and I want to prevent one thread from changing the data, while the other thread is reading it.
My approach was the following:
I have a Data class containing an array and two methods updateData(Integer[] data) and getUpdate() for accessing and manipulating the array.
public class Data <T extends Comparable> {
private T[] data;
public T[] getUpdate() {
synchronized (this) {
return data.clone();
}
}
public void updateData(T[] data) {
synchronized (this) {
this.data = data.clone();
}
}
}
This data object is now used in two different threads, the main thread wich updates the data and the swing EDT thread wich reads the data and uses it.
public static void main(String[] args) {
Data<Integer> data = new Data<>();
data.updateData(new Integer[]{1,2,3,4,5,6,7,8,10});
SwingUtilities.invokeLater(() -> {
ColumnVisualizer visualizer = new ColumnVisualizer();
new Timer(100, e -> {
visualizer.setData(data.getUpdate());
}).start();
});
while(condition) {
data.updateData(createNewData());
}
}
As I understand it if I access the array only through the updateData() and getUpdate() methods, which I made threadsafe with the synchronized keyword, the data itself is threadsafe. Since if a thread calls the getUpdate() method it sets a lock on the Data instance and when another thread wants to call updateData() it can not access the part where the old array is replaced with the new one, until the Data instance is not longer looked on.
Have I understand it correctly and is this a convenient approach to make the array threadsafe in Java?