Actually, I am a bit confused in regards of several explanation from website or blog about synchronization and thread-safe. I've done some research on different class of Core Java Api or Java Framework (Collections). And i've often noticed that some class are synchronize and thread-safe which means, at a time, only one thread can access the code.
But i need some precision :
A class is synchronize so its thread-safe ?
Or synchronize and thread-safe have two different meaning ?
Best regards
A class is synchronize so its thread-safe ?
A class is not synchronized. Rather a method, or a block of code is synchronized.
Synchronization (using synchronized) is one way to make code thread-safe. There are other ways.
Or synchronize and thread-safe have two different meaning ?
Yes. They have different meanings.
And i've often noticed that some class are synchronize and thread-safe which means, at a time, only one thread can access the code.
Actually, if you "noticed" that, you were not paying attention!
With a synchronized method, only one thread can access the code while holding a given lock; i.e. you get mutual exclusion. If two threads use different locks, then you won't get mutual exclusion.
The other thing to note is that merely using synchronized does not guarantee thread-safety. You need to use it in the right way:
threads need to synchronize on the appropriate objects / locks
threads need to synchronize in all appropriate code
if the code entails acquiring multiple locks, the locks need to be acquired in an order that avoids deadlocks.
Related
Recently I have been studying the sleep barber, and I have comprehended that it seems like a binary semaphore when the permits value equals to 1. How about when it exceeds 1? Will one thread be exchanged by a new one without releasing when multiple threads acquired?
I think it is unsafe but I am not sure .
It would be nice if you could tell me the difference between syncing and simultaneous access.
Semaphore works as a gate. It can't be qualified as thread-safe or thread-unsafe. Resources (in general objects) can be thread-safe or unsafe.
If it is binary semaphore, only one thread can access your resources at any given moment. So there is no need to think about thread-safety.
But if semaphore count is 2, two threads can simultaneously access the same resource. If your resource (some object) is thread-safe, you are good. Otherwise you would need to implement some kind of synchronization mechanism so that unsafe part can only be accessed by one thread at a time.
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?
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.
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.
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
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.
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!
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
In practice, performance wise, Thread safe, Synchronised, non-thread safe and non-synchronised classes are ordered as:
Hashtable(slower) < Collections.SynchronizedMap < HashMap(fastest)
Is using Locks (java.util.concurrent.locks.Lock) instead of keyword synchronized + method wait() and method notify() totally the same?
Can I thread-safely program using locks (explicit locks) rather than implicit locks (synchronized)?
As of know I have always been using implicit locks. I am aware of the advantages given by the Lock interface implementation like methods: isLocked(), getLockQueueLength(), getHoldCount(), etc... however still the old school way (wait() and notify()) would have other limits other than not having those methods?
I am also aware of the possibility of constructing a lock with a (boolean fairness) parameter which allows lack of starvation.
Yes, absolutely you can write thread-safe program using java.util.concurrent.locks.Lock. If you see any implementation of java.util.concurrent.locks.Lock like ReentrantLock internal implementation uses old synchronized blocks.
Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.
Adding to my difference the synchronized keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks in ways it cannot with Locks. e.g. it can combine synchronized blocks.synchronized is best for a small number of threads accessing a lock and Lock may be best for a high number of threads accessing the same locks . Also synchronized block makes no guarantees about the sequence in which threads waiting to entering it are granted access.
Locks and synchronized blocks have the same semantics and provide the same guarantees from a Java Memory Model perspective. The main difference is that Locks provide more control (such as with tryLock or when asking a lock to be fair etc.) which allow for a more flexible and fine-grained lock management.
However, when you don't need those additional features, it is better to use a plain old synchronized block as it reduces the room for error (e.g. you can't "forget" to unlock it).
So, while working on something that was having locking issues, a question came to me. Do objects that only can be accessed from a single thread require locks or synchronization at all?
For example, given Thread1, Thread2, and Thread3, along with Buffer1, Buffer2, Buffer3, where each buffer is instanced as a thread is created, meaning that Thread1 will only ever access Buffer1, and the same for Thread2 and Buffer2, along with Thread3 and Buffer3. Thread1 will never touch Buffer2 or Buffer3. While adding/removing/modifying bytes in the stream, are locks needed?
No, You wont need any locks in this case. Locking and synchronization is only required when any resource is being shared between multiple threads.
If you go ahead and add synchronization on the private instance of that buffer then still it wont make any difference as there will be no thread waiting to acquire locks, The only one locking and releasing the buffer will be the owner thread.
1. When more than one thread try to access an object, then locking becomes necessary.
2. Moreover classes when developed needs to be thread safe, if concurrent access by threads is possible.
3. A class is said to be thread safe, it if behaves correctly in the presence of interleaving and scheduling of the underlying OS , without any synchronization mechanism from the client.
4. Locking the resources can cause overhead, prevents concurrent access, and bottle neck situations.
Only when two or more threads need to access a shared object you need to worry about locking.
No. This strategy for ensuring thread-safety is generally referred to as confinement.
Confinement relies on encapsulation techniques to ensure that multiple threads cannot access an object. "Concurrent Programming in Java" by Doug Lea has good chapter on the details of confinement and its strengths and weaknesses compared to other exclusion techniques.
Paraphrasing from Lea, in general there are 4 conditions needed for confinement of a reference r, to an object x, within a method m:
m cannot pass r as an argument to another method.
m cannot pass r as a return value.
m cannot record r in a field (instance or static) that is accessible from another thread.
m cannot may not let any other references escape (via 1-3) that may be traversed to r.
From what I remember from my studies, if you are using a private buffer for every thread you should not worry about locking it to avoid concurrent access, since you don't have any.
If no-one is reading the buffer apart from the creator, it could do whatever he wants on it without worrying that someone else is reading or writing it. so you should be fine
But you have to remember that a thread can be interrupted at any time, so your internal buffer can be in a inconsistent state. (this shouldn't be a problem since you are accessing only sequentially from the same thread)
Locks are not needed unless threads are concurrently using the same data structure.
Hence if different data structures are used by each thread, your code is guaranteed to be thread safe.
Incidentally, this is one of the main reasons why the key Java collection classes like java.util.ArrayList are not thread safe: making them thread safe would add a performance overhead which you shouldn't have to pay for if you don't need, and in a lot of cases you don't need it because you can ensure in some other way that only one thread accesses the ArrayList at once.
Can any one please share their experience on
"When do we make a call to use between Synchronised method and Synchronised Block"
Any Performance Issues?
When do we make a call to use between Synchronised method and Synchronised Block.
If you want to lock for the duration of a method call AND you want to lock on this (or the current class, for a static method), then synchronized methods are the right solution.
If you are locking on something else (e.g. a private lock object or some internal data structure), then the synchronized block approach is better.
Similarly, if only some of the code in a procedure call needs to be done holding a lock, it is better to use a synchronized block and put just that code in the block.
Any Performance Issues?
None, apart from the general principal that it is a bad idea to hold a lock longer than you need to. (The longer a lock is held, the more likely it is that other threads will need to wait.)
I'm not sure what you mean by "synchronized statement". You use the synchronized keyword to either denote that a method is synchronized or (as you mention) a block of code within it.
I typically favour keeping methods small and manageable and therefore labelling the entire method as synchronized (when required). This has the advantage that it is immediately evident to a user of the class as to which methods represent critical sections. It also allows you as a programmer to more easily determine whether a class is thread-safe, namely: Are all public methods that access mutable data labelled as synchronized?
There is no performance difference between the approaches as both require obtaining a lock.
Always try to use Synchronized block if possible, for any case its not possible then go for Synchronized method. Will be a lot of performance improvements depend on the no. of lines in the Synchronized method. As no. of lines increases,performance will degrade.
I tend to use synchronized methods when it is the public interface that requires synchronization (c.f. synchronized collections) and synchronized blocks for class internal synchronization, such as access to a shared resource which needs to be thread safe.
There is also a readability issue. I find method level synchronization to be neater and more obvious as the code is not cluttered with lock management.
As for performance, I'm not aware of any particular difference in the behaviour of either approach. I think it is more important to avoid excessive synchronization, so a method which only needs access to the shared resource 1 in 10 calls should use block level rather than method level synchronization.
My approach to any given scenario is usually based on a mix of these factors, modified by previous experience.
In terms of overall performance, there is no difference between having a synchronized block or method. The issue is really in terms of coding practices. Synchronizing a method seems like an easy thing to do however, when working with multiple people on a project, it becomes possible for someone to alter a simple light method that someone else synchronized into a heavy operation one. In fact, one really good example (from personal experience) of where you can get into trouble is when you are using a dependency injection framework and you have methods in a service object that interact with data access objects (daos) that are synchronized. The expectation is that the daos perform quickly so the locks are only held briefly. Someone else comes along and either alters the daos or creates and injects new ones that are much slower and suddenly things start to really slow down because the service object has synchronized interaction with it.
I don't think synchronized blocks can get around that issue that I described above however, at least with synchronized blocks, they are harder to miss than a declaration in the method.