- What is “non-blocking” concurrency and how is it different than normal concurrency using threads? Why don’t we use non-blocking concurrency in all the scenarios where concurrency is required? Is there overhead for using non-blocking concurrency?
- I have heard that non-blocking concurrency is available in Java. Are there any particular scenarios where we should use this feature?
- Is there a difference or advantage to using one of these methods with a collection? What are the trade-offs?
Example for Q3:
class List
{
private final ArrayList<String> list = new ArrayList<String>();
void add(String newValue)
{
synchronized (list)
{
list.add(newValue);
}
}
}
vs.
private final ArrayList<String> list = Collections.synchronizedList();
The questions are more from a learning/understanding point of view. Thanks for attention.
Formal:
Informal: One of the most advantageous feature of non-blocking vs. blocking is that, threads does not have to be suspended/waken up by the OS. Such overhead can amount to 1ms to a few 10ms, so removing this can be a big performance gain. In java, it also means that you can choose to use non-fair locking, which can have much more system throughput than fair-locking.
Yes, from Java5. In fact, in Java you should basically try to meet your needs with java.util.concurrent as much as possible (which happen to use non-blocking concurrency a lot, but you don’t have to explicitly worry in most cases). Only if you have no other option, you should use synchronized wrappers (.synchronizedList() etc.) or manual
synchronizekeyword. That way, you end up most of the time with more maintainable, better performing apps.Non-blocking concurrency is particularly advantageous when there is a lot of contention. You can’t use it when you need blocking (fair-locking, event-driven stuff, queue with maximum length etc.), but if you don’t need that, non-blocking concurrency tends to perform better in most conditions.
Both have the same behavior (the byte code should be equal). But I suggest to use
Collections.synchronizedbecause it’s shorter = smaller room to screw up!