How to make the following Java class thread safe?
class Test { int size; int index; String[] a; Test() { a = new String[10]; size = 10; } Test(int b) { a = new String[b]; size = b; } public int getSize() { return size; } public void addElement(String s) { if (a.length < size) { a[index] = s; index++; } else { // ... } } public String getElement(int i) { if (i < index) { return a[i - 1]; } else { return 0; } } } - Is it enough to make the
String[] a;variablevolatile? - Or do i need to use the
synchronizedkeyword?
My assumption is that synchronized is not needed for the methods getSize() and getElement(). Is that correct?
private.Testan immutable class. I'm sure someone will post an answer soon with more details.