Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this thread safe?

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?

like image 381
Leo Avatar asked Sep 10 '10 16:09

Leo


People also ask

How can you tell if a thread is safe?

To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.

Is using thread-safe?

A MessageService object is effectively immutable since its state can't change after its construction. So, it's thread-safe. Moreover, if MessageService were actually mutable, but multiple threads only have read-only access to it, it's thread-safe as well.

What is meant by thread-safe in C?

A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. In C language, local variables are dynamically allocated on the stack.

Which of the following is thread-safe?

Answer: Since String is immutable in Java, it's inherently thread-safe.


2 Answers

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.

like image 98
Jon Skeet Avatar answered Oct 15 '22 03:10

Jon Skeet


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.

like image 37
Nemi Avatar answered Oct 15 '22 03:10

Nemi