3

I just trying to explore What is ThreadSafe mean?

Below are my understanding:

It looks like for me; allowing multiple threads to access a collection at the same time; this is irrespective of its synchronization. For example any method without synchronized keyword on it; is thread safe, means mutiple threads can access it.

It is up to a developer choice to maintain some more logic (synchronization) on this method to maintain data integrity while multi-threads are accessing it. That is separate from thread safe.

If my above statement is false; just read the below JAVA DOC for `ConcurrentHashMap:

keySet: The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

The above statement says keySet iterator will not guarantee the data integrity; while multi-threads are modifying the collection.

Could you please answer me, *Is KeySet iterator of ConcurrentHashMap is threadsafe?

And my understanding on thread safe is correct ??

Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
  • 5
    your question itself has answer. – codingenious Oct 25 '13 at 08:09
  • 1
    As javadoc goes this is incredibly clear and no answer could paraphrase it better or with more clarity. What exactly do you not understand? – Bohemian Oct 25 '13 at 08:11
  • ConcurrentHashMap keySet() is thread safe so there might be no need to synchronize or take a copy. – Prashant Shilimkar Oct 25 '13 at 08:12
  • 1
    "iterator will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator" – this is enough for something to be 'thread safe'. The question is, what exactly do you define as 'thread safe'... – Tadas S Oct 25 '13 at 08:24
  • @afk5min is the quoted is your definition of thread safe ?? So it means thread-safe wont ensure what modification on the collection.. simply allows multiple threads are able to traverse elements ..? – Kanagavelu Sugumar Oct 25 '13 at 09:15
  • 'Thread safety' means that there will be **no undefined behavior** when accessing the same object concurrently (or unchecked exceptions when it can be determined that undefined behavior _will definitely happen by continuing execution_). – Tadas S Oct 25 '13 at 10:06

3 Answers3

3

keySet: The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction

This itself explains, that KeySet iterator of ConcurrentHashMap is threadsafe.

codingenious
  • 8,385
  • 12
  • 60
  • 90
3

General idea behind the java.util.concurrent package is providing a set of data structures that provide thread-safe access without strong consistency. This way these objects achieve higher concurrency then properly locked objects.

Being thread safe means that, even without any explicit synchronization you never corrupt the objects. In HashTable and HashMap some methods are potential problems for multi-thread access, such as remove method, that first checks that the element exists, then removes it. These kind of methods are implemented as atomic operations in ConcurrentHashMap, thus you do not need to afraid that you will lose some data.

However it does not mean that this class is automatically locked for each operation. High level operations such as putAll and iterators are not synchronized. The class does not provide strong consistency. The order and timing of your operations are guaranteed to not to corrupt the object, but are not guaranteed to generate accurate results.

For example if your print the object concurrently with a call to putAll, you might see a partially populated output. Using an iterator concurrently with new insertions also might not reflect all insertions as you quoted.

This is different from being thread safe. Even though the results might surprise you, you are assured that nothing is lost or accidentally overwritten, elements are added to and removed from your object without any problem. If this behaviour is sufficient for your requirements you are advised to use java.util.concurrent classes. If you need more consistency, then you need to use synchronized classes from java.util or use synchronization yourself.

infiniteRefactor
  • 1,940
  • 15
  • 22
  • Great answer. Most of the time, there is absolutely no need for 'sequentialization' (concurrent calls transformed into arbitrarily-ordered sequential calls, by `synchronized` & co.) nor for 'deterministic sequentialization`, where concurrent calls are transformed into sequential calls in a specific, reproducible order. That's pretty much why 'thread safety' has an entirely different meaning. – Tadas S Oct 25 '13 at 10:12
1

By your definition the Set returned by ConcurrentHashMap.keySet() is thread safe.

However, it may act in very strange ways, as pointed out in the quote you included.

  1. As a Set, entries may appear and/or disappear at random. I.e. if you call contains twice on the same object, the two results may differ.
  2. As an Iterable you could begin two iterations of its underlying objects in two different threads and discover that the two iterations enumerate different entries.
  3. Furthermre, contains and iteration may not match either.

This activity will not occur, however, if you somehow lock the underlying Map from modification while you have hold of your Set but the need to do that does not imply that the structure is not thread safe.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • So i could see lot of inconsistency using iterator; Then why it is called as Threadsafe...? OR Is threadsafe is out of data consistency ..? – Kanagavelu Sugumar Oct 25 '13 at 09:01
  • @KanagaveluSugumar - Thread safe means that accessing it through multiple threads will not break or crash. It may give inconsistent result - that you have to defend against yourself - if you care. *It is up to a developer choice to maintain some more logic (synchronization) on this method to maintain data integrity while multi-threads are accessing it.* – OldCurmudgeon Oct 25 '13 at 09:26
  • Ohhhhhhhhh ..? is it ..? So my understanding is correct..? And the best answer to this http://stackoverflow.com/questions/6324085/what-is-thread-safe-in-java question is wrong, is it ..? – Kanagavelu Sugumar Oct 25 '13 at 09:37
  • @KanagaveluSugumar - To my mind *thread safe* means that if you do not use `synchronized` when writing to it the structure may become damaged. That does not demand consistency between threads, if you need that then you must implement that yourself. – OldCurmudgeon Oct 25 '13 at 10:15