package me.nallar.tickthreading.collections;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;

public class HashSetReplaceIterateTempListClear<T> extends HashSet<T> {
	private volatile boolean defer = false;
	private final LinkedList<T> deferred = new LinkedList<T>();

	@Override
	public synchronized boolean add(T t) {
		if (defer) {
			return !contains(t) && deferred.add(t);
		} else {
			return super.add(t);
		}
	}

	@Override
	public synchronized Iterator<T> iterator() {
		if (defer) {
			throw new IllegalStateException();
		}
		defer = true;
		return super.iterator();
	}

	@Override
	public synchronized void clear() {
		super.clear();
		defer = false;
		addAll(deferred);
		deferred.clear();
	}
}

@@ -41,16 +41,47 @@
 ons;%0D%0A%0D%0A
+import java.util.Collections;%0D%0A
 import j
@@ -99,16 +99,16 @@
 shSet;%0D%0A
-
 import j
@@ -335,16 +335,246 @@
 t%3CT%3E();%0D
+%0A%09private static final Iterator emptyIterator = Collections.emptyList().iterator();%0D%0A%09private ThreadLocal%3CBoolean%3E noDefer = new ThreadLocal%3CBoolean%3E() %7B%0D%0A%09%09@Override%0D%0A%09%09public Boolean initialValue() %7B%0D%0A%09%09%09return false;%0D%0A%09%09%7D%0D%0A%09%7D;%0D
 %0A%0D%0A%09@Ove
@@ -811,41 +811,51 @@
 %0A%09%09%09
-throw new IllegalStateException()
+noDefer.set(true);%0D%0A%09%09%09return emptyIterator
 ;%0D%0A%09
@@ -913,32 +913,32 @@
 %0D%0A%0D%0A%09@Override%0D%0A
-
 %09public synchron
@@ -958,16 +958,81 @@
 ar() %7B%0D%0A
+%09%09if (noDefer.get()) %7B%0D%0A%09%09%09noDefer.set(false);%0D%0A%09%09%09return;%0D%0A%09%09%7D%0D%0A
 %09%09super.

Fix HashSetReplaceIterateTempListClear behaviour under concurrent access.