Is this thread safe?

I am writing an Android application and use workflows to process certain information. After reading my code, I am now not sure how safe the stream is.

I wrote a simplified version of my code, I omitted the Handler object used to communicate with the main thread and, obviously, with the process itself.

 public class myClass implements Runnable { private String myString; @Override public void run() { myString = "Some Value"; } } 

This is caused by the launch of something similar to this.

 myClass class = new myClass(); Thread thread = new Thread(class); thread.start() 

So, this code is not thread safe because I am changing myString (declared in the main thread) in the run() function?

+7
android multithreading runnable thread-safety
source share
2 answers

This in itself is thread safe. But which streams will read the value of myString ? If you read it from the main stream after writing it in a new stream, this is not thread safe.

+4
source share

No, since you introduced it, it is thread safe. If you use getter for the myString variable, you have a potential thread problem. In this case, you want the getter / setter method to synchronize or, moreover, make the variable volatile, which ensures that the value of the variable is the same for each stream.

+2
source share

All Articles