default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
@Test
public void test() {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
SynchronizedCollection<String> sc = SynchronizedCollection.synchronizedCollection(list);
ExecutorService executorService = Executors.newFixedThreadPool(4);
// "1" 를 remove 하는 쓰레드가 여러개 달라붙었을 때
for(int i = 0; i < 10; i++) {
executorService.submit(()->{
System.out.println(
"threadId = " + Thread.currentThread().getId() + " removeIf=" + sc.removeIf(
p -> p.equals("1")));
});
}
executorService.shutdown();
}
threadId = 21 removeIf=false
threadId = 22 removeIf=true
threadId = 21 removeIf=false
threadId = 19 removeIf=false
threadId = 20 removeIf=true
threadId = 21 removeIf=false
threadId = 19 removeIf=false
threadId = 22 removeIf=false
threadId = 20 removeIf=false
threadId = 21 removeIf=false
잘 동작했다면 removeIf=true인 로그줄이 한개만 나와야 한다.