I code in Java8, and I want to use a thread and then catch the result which the thread creates via a mutable object. The code is something like the following:
public class MyTest {
public static void main(String[] args) throws InterruptedException {
MutableString mutableString = new MutableString();
Thread thread = new Thread(
() -> mutableString.value = "value_from_another_thread");
thread.start();
thread.join();
assert "value_from_another_thread".equals(mutableString.value);
}
private static class MutableString {
String value; // Does this have to be volatile or should I use AtomicReference instead of MutableString?
}
}
It seems that it works fine on my dev laptop, but is there any possibility where this code doesn't work properly in some environment? Should I use volatile
for the value
field or replace the MutableString
class by AtomicReference
for safety?
EDIT:
What if a CountDownLatch
was used instead of thread.join()
? Does it change something?
public class MyTest {
public static void main(String[] args) throws InterruptedException {
MutableString mutableString = new MutableString();
CountDownLatch latch = new CountDownLatch(1);
MyThread myThread = new MyThread(latch, mutableString);
myThread.start();
latch.await();
assert "value_from_another_thread".equals(mutableString.value);
}
private static class MyThread extends Thread {
private final CountDownLatch latch;
private final MutableString mutableString;
MyThread(CountDownLatch latch, MutableString mutableString) {
this.latch = latch;
this.mutableString = mutableString;
}
@Override
public void run() {
mutableString.value = "value_from_another_thread";
latch.countDown();
}
}
private static class MutableString {
String value; // Does this have to be volatile or should I use AtomicReference instead of MutableString?
}
}