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?
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.”
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With