What are fail-safe & fail-fast Iterators in Java -


there 2 types of iterators in java: fail-safe , fail-fast.

what mean, , difference between them?

what difference between them ...

"fail safe" means: won't fail. strictly speaking, there no such thing in java fail-safe iterator. correct term "weakly consistent". javadoc says:

"most concurrent collection implementations (including queues) differ usual java.util conventions in iterators , spliterators provide weakly consistent rather fast-fail traversal."

typically, weak consistency means if collection modified concurrently iteration, guarantees of iteration sees weaker. (the details specified in each conncurrent collection classes javadocs.)

"fail fast" means: may fail ... , failure condition checked aggressively failure condition (where possible1) detected before damage can done. in java, fail-fast iterator fails throwing concurrentmodificationexception.

the alternative "fail-fast" , "weakly consistent" semantic iteration fails unpredictably; e.g. give wrong answer or throw totally unexpected exception. (this behavior of standard implementations of enumeration api in versions of java.)

... , different iterator use collection.

no. these properties of iterators implemented standard collection types; i.e. either "fail fast" or "weakly consistent" ... when used correctly respect synchronization , java memory model1.


the fail-fast iterators typically implemented using volatile counter on collection object.

  • when collection updated, counter incremented.
  • when iterator created, current value of counter embedded in iterator object.
  • when iterator operation performed, method compares 2 counter values , throws cme if different.

the implementation of fail-safe iterators typically light-weight. typically rely on properties of specific list implementation's data structures. there no general pattern. (read source code specific collection classes interested in.)


1 - rider fail-fast behavior assumes application id correctly respect synchronization , memory model. means (for example) if iterate arraylist without proper synchronization, end result corrupted list result. "fast fail" mechanism detect concurrent modification (though isn't guaranteed), won't detect underlying corruption. example, javadoc vector.iterator() says this:

"the fail-fast behavior of iterator cannot guaranteed is, speaking, impossible make hard guarantees in presence of unsynchronized concurrent modification. fail-fast iterators throw concurrentmodificationexception on best-effort basis. therefore, wrong write program depended on exception correctness: fail-fast behavior of iterators should used detect bugs."


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -