Are there any synchronizing/reference issues with this code?
(Assume that myStrings
is already instantiated.)
MySynch.java
:
public class MySynch
{
public static String[] myStrings = new String[10];
public static void updateStrings()
{
synchronized (myStrings)
{
myStrings = new String[10]; // Safe?
myStrings[0] = something[0];
myStrings[1] = somethingElse[4];
}
}
}
The object array myStrings
may be read from by more than one thread, and has one thread that updates (writes) it by running updateStrings()
. The threads that read from it will also use a synchronized (myStrings)
block to read from it, of course, for safety.
Are there issues with locking the array and instantiating it again inside the synchronized
block which is locking it (as above)?
There is an synchronization issue: when myStrings is set to a new instance, and a second thread is executing the method just after, that second thread will synchronize the second instance of myStrings.
You should synchronized on the class or any other static final object with
synchronized(MySynch.class) {
...
}