Threadsafe vs Synchronized
Asked Answered
I

7

26

I'm new to java. I'm little bit confused between Threadsafe and synchronized. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occurring. Where as Synchronized means only one thread can operate at single time.

So how they are related to each other?

Intendment answered 15/2, 2014 at 0:53 Comment(7)
@jtahlborn: "All" is way overstating it. :P It takes more than just synchronization; it takes coordinated synchronization. If two threads that mess with the same stuff aren't synchronizing on the same lock/monitor/mutex/whatever, then you have many of the same issues as if they're not synchronized at all.Couture
@Couture - i was generalizing. yes, just throwing synchronized around does not make your code thread-safe. how about "synchronization is a mechanism for making code thread-safe, but not all thread-safe code uses synchronization".Flooded
if a code is synchronized then how it'll be used by multiple threads(as per threadsafety)?Intendment
@user3312230 - it won't be used by multiple threads, that's what helps make it thread-safe.Flooded
@user3312230: The point of synchronization is to protect the stuff that will break if two threads muck around with it at the same time, and keep them from mucking around with it simultaneously. Most of the time the threads will be doing two different things, and won't collide; if one's messing with your object while the other is doing something totally different, then everything just hums along and appears to be working simultaneously. But at the critical points where they can collide, and collision would be fatal, synchronization makes them wait in line.Couture
thats true about synchronisation.But we know all synchronised code are treadsafe, then how Threadsafe defines a method or class instance can be used by multiple threads at the same time without any problems occuring.Intendment
@Nayak: Again, not all synchronized code is thread-safe. Anyone who understands thread safety knows better than to even utter those words. Thread safety is far more complicated than just "make everything synchronized", because doing so unnecessarily or incorrectly can actually cause deadlocks. It refers to the bigger picture, how related-but-distinct parts interact.Couture
C
18

The definition of thread safety given in Java Concurrency in Practice is:

A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.

For example, a java.text.SimpleDateFormat object has internal mutable state that is modified when a method that parses or formats is called. If multiple threads call the methods of the same dateformat object, there is a chance a thread can modify the state needed by the other threads, with the result that the results obtained by some of the threads may be in error. The possibility of having internal state get corrupted causing bad output makes this class not threadsafe.

There are multiple ways of handling this problem. You can have every place in your application that needs a SimpleDateFormat object instantiate a new one every time it needs one, you can make a ThreadLocal holding a SimpleDateFormat object so that each thread of your program can access its own copy (so each thread only has to create one), you can use an alternative to SimpleDateFormat that doesn't keep state, or you can do locking using synchronized so that only one thread at a time can access the dateFormat object.

Locking is not necessarily the best approach, avoiding shared mutable state is best whenever possible. That's why in Java 8 they introduced a date formatter that doesn't keep mutable state.

The synchronized keyword is one way of restricting access to a method or block of code so that otherwise thread-unsafe data doesn't get corrupted. This keyword protects the method or block by requiring that a thread has to acquire exclusive access to a certain lock (the object instance, if synchronized is on an instance method, or the class instance, if synchronized is on a static method, or the specified lock if using a synchronized block) before it can enter the method or block, while providing memory visibility so that threads don't see stale data.

Caladium answered 25/3, 2015 at 13:41 Comment(1)
Excellent explanation. Any other resources to learn about concurrency other than JCIP?Mortonmortuary
A
13

Thread safety is a desired behavior of the program, where the synchronized block helps you achieve that behavior. ​There are other methods of obtaining Thread safety e.g immutable class/objects. Hope this helps.

Adjudicate answered 15/2, 2014 at 0:57 Comment(2)
As we know all synchronised code are treadsafe, then how Threadsafe defines a method or class instance can be used by multiple threads at the same time without any problems occuring.Intendment
I know is a bit old but i would like to add a comment, thread safe behavior is not intercepting one's normal operation, which involved variables' value. synchronize blocks multiple access to the same sharing object in order to achieve this, e.g. some static classes, or other method such as injecting templates and creating new instances for each thread etc.Fontainebleau
G
5

Thread safety: A thread safe program protects it's data from memory consistency errors. In a highly multi-threaded program, a thread safe program does not cause any side effects with multiple read/write operations from multiple threads on shared data (objects). Different threads can share and modify object data without consistency errors.

synchronized is one basic method of achieving ThreadSafe code.

Refer to below SE questions for more details:

What does 'synchronized' mean?

You can achieve thread safety by using advanced concurrency API. This documentation page provides good programming constructs to achieve thread safety.

Lock Objects support locking idioms that simplify many concurrent applications.

Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.

ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.

Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.

Related SE question:

Synchronization vs Lock

Gatefold answered 5/7, 2016 at 13:13 Comment(0)
E
2

After patiently reading through a lot of answers and not being too technical at the same time, I could say something definite but close to what Nayak had already replied to fastcodejava above, which comes later on in my answer but look

synchronization is not even close to brute-forcing thread-safety; it's just making a piece of code (or method) safe and incorruptible for a single authorized thread by preventing it from being used by any other threads.

Thread safety is about how all threads accessing a certain element behave and get their desired results in the same way if they would have been sequential (or even not so), without any form of undesired corruption (sorry for the pleonasm) as in an ideal world.

One of the ways of achieving proximity to thread-safety would be using classes in java.util.concurrent.atomic.

Sad, that they don't have final methods though!

Enterprise answered 5/7, 2016 at 10:17 Comment(0)
S
2

Synchronized: only one thread can operate at same time. Threadsafe: a method or class instance can be used by multiple threads at the same time without any problems occurring. If you relate this question as, Why synchronized methods are thread safe? than you can get better idea.

As per the definition this appears to be confusive. But not,if you understand it analytically.

Synchronized means: sequentially one by one in an order,Not concurrently [Not at the same time]. synchronized method not allows to act another thread on it, While a thread is already working on it.This avoids concurrency. example of synchronization: If you want to buy a movie ticket,and stand in a queue. you will get the ticket only after the person in front of you get the ticket.

Thread safe means: method becomes safe to be accessed by multiple threads without any problem at the same time.synchronized keyword is one of the way to achieve 'thread safe'. But Remember:Actually while multiple threads tries to access synchronized method they follow the order so becomes safe to access. Actually, Even they act at the same time, but cannot access the same resource(method/block) at the same time, because of synchronized behavior of the resource.

Because If a method becomes synchronized, so this is becomes safe to allow multiple threads to act on it, without any problem. Remember:: multiple threads "not act on it at the same time" hence we call synchronized methods thread safe.

Hope this helps to understand.

Scruff answered 17/11, 2017 at 11:22 Comment(0)
T
0

Nayak, when we declare a method as synchronized, all other calls to it from other threads are locked and can wait indefinitely. Java also provides other means of locking with Lock objects now.

You can also declare an object to be final or volatile to guarantee its availability to other concurrent threads.

ref: http://www.javamex.com/tutorials/threads/thread_safety.shtml

Telex answered 25/3, 2015 at 13:7 Comment(0)
R
-2

In practice, performance wise, Thread safe, Synchronised, non-thread safe and non-synchronised classes are ordered as:

Hashtable(slower)  <  Collections.SynchronizedMap  <  HashMap(fastest)
Raines answered 17/9, 2017 at 18:39 Comment(1)
This doesn't really help in explaining the concepts of thread-safety and synchronized methods, as requested by the OP.Ratepayer

© 2022 - 2024 — McMap. All rights reserved.