Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Thread Safety mean?

I've been reading some blogs on multi-threaded programming in ruby. What I noticed is that the author tends to use the word thread-safety. What does it mean? Why is it important to write thread-safety code?

like image 667
Chamnap Avatar asked Mar 11 '11 08:03

Chamnap


People also ask

What means thread-safety?

In multithreaded environments, we need to write implementations in a thread-safe way. This means that different threads can access the same resources without exposing erroneous behavior or producing unpredictable results. This programming methodology is known as “thread-safety.”

What is thread-safe and not thread-safe?

Thread-safety is recommended when the web server run multiple threads of execution simultaneously for different requests. In Thread Safety binary can work in a multi-threaded web server context. Thread Safety works by creating a local storage copy in each thread so that the data will not collide with another thread.

What does it mean to be thread-safe in Java?

thread-safety or thread-safe code in Java refers to code that can safely be utilized or shared in concurrent or multi-threading environment and they will behave as expected.

What is thread-safety how do you achieve it?

1) Immutable objects are by default thread-safe because their state can not be modified once created. Since String is immutable in Java, it's inherently thread-safe. 2) Read-only or final variables in Java are also thread-safe in Java. 3) Locking is one way of achieving thread-safety in Java.


1 Answers

If you have a resource (let's say a global List of Books for example) and you have two threads running which can modify this list. There are a lot of situations where the data of the list will get inconsistent.

  • (Thread A reads a Book ands displays its Data)
  • (Thread B deletes the same Book while the Data is used by Thread A)
  • (Thread A now wants to add some information to the Book)

So you have to make your code thread-safe so that at anytime only one single thread can have write access to the list of books.

Deadlocking mentioned by SpyrosP happens when Thread A blocks the List for writing and waits for Thread B to add data on the list. Because both threads will wait for each other to do something they can't do. That only happens if the thread-safety mechanism is not properly implemented.

like image 163
Chris Avatar answered Oct 30 '22 13:10

Chris