7

I am writing an application for Android and am using worker threads to process certain information. Having read through my code I am now unsure if it is thread safe.

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

public class myClass implements Runnable
{
    private String myString;

    @Override
    public void run()
    {
        myString = "Some Value";
    }
}

This is called by running something similar to this.

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

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

Leo
  • 537
  • 1
  • 7
  • 16
  • Your question reminds me a lot of this article http://blogs.msdn.com/b/ericlippert/archive/2009/10/19/what-is-this-thing-you-call-thread-safe.aspx – Conrad Frix Sep 10 '10 at 17:03

2 Answers2

4

In itself, that's thread-safe. But which threads are going to be reading the myString value? If you read it from the main thread after writing it in the new thread, that isn't thread-safe.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

No, as you have presented it, it is thread safe. If you make a getter for the myString variable, you have a potential threading issue. In that case you would want to make the getter/setter method synchronized, or better yet make the variable volatile, which will ensure that the variable's value is the same for every thread.

Nemi
  • 3,011
  • 1
  • 26
  • 24