🚀 𝐅𝐚𝐢𝐥-𝐅𝐚𝐬𝐭 𝐯𝐬 𝐅𝐚𝐢𝐥-𝐒𝐚𝐟𝐞 𝐈𝐭𝐞𝐫𝐚𝐭𝐨𝐫𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚 If you're preparing for Java interviews, this is an important concept to understand. When iterating over collections in Java, two types of iterator behaviors exist. 🔴 Fail-Fast Iterator If the collection is modified while iterating, it immediately throws a Concurrent Modification Exception. Example collections: • ArrayList • HashMap • HashSet Example: List<String> list = new ArrayList<>(); list.add("Java"); list.add("Spring"); for (String s : list) { list.add("Docker"); // throws ConcurrentModificationException } These iterators detect structural modifications during iteration and fail immediately. 🟢 Fail-Safe Iterator Fail-Safe iterators work on a copy of the collection, so modifications during iteration do not throw exceptions. Example collections: • ConcurrentHashMap • CopyOnWriteArrayList Example: CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); list.add("Java"); for (String s : list) { list.add("Spring"); // no exception } 📌 Key Difference Fail-Fast → Throws exception if collection is modified during iteration Fail-Safe → Works on a copy, so no exception occurs Understanding this concept is important when working with multithreading and concurrent collections. Follow for more Java internals explained simply. #Java #JavaDeveloper #Programming #CodingInterview #BackendDevelopment
#CFBR
Check this out