BAEL-1473 replaced int with AtomicInteger for safe usage in multi-threaded env (#3497)

* BAEL-1473 Intoduction to Spliterator in Java

* BAEL-1473 - Replace .out with logger.info

* removed log

* BAEL-1473 - added test-cases

* modify test-cases

* AtomicInteger instead of int

* SIZED removed
This commit is contained in:
Ahmad Alsanie 2018-01-24 19:29:14 +02:00 committed by maibin
parent 689083a090
commit 0585764866
1 changed files with 36 additions and 34 deletions

View File

@ -2,46 +2,48 @@ package com.baeldung.spliteratorAPI;
import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
public class RelatedAuthorSpliterator implements Spliterator<Author> {
private final List<Author> list;
private int current = 0;
private final List<Author> list;
AtomicInteger current = new AtomicInteger();
public RelatedAuthorSpliterator(List<Author> list) {
this.list = list;
}
public RelatedAuthorSpliterator(List<Author> list) {
this.list = list;
}
@Override
public boolean tryAdvance(Consumer<? super Author> action) {
action.accept(list.get(current++));
return current < list.size();
}
@Override
public boolean tryAdvance(Consumer<? super Author> action) {
@Override
public Spliterator<Author> trySplit() {
int currentSize = list.size() - current;
if (currentSize < 10) {
return null;
}
for (int splitPos = currentSize / 2 + current; splitPos < list.size(); splitPos++) {
if (list.get(splitPos)
.getRelatedArticleId() == 0) {
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(list.subList(current, splitPos));
current = splitPos;
return spliterator;
}
}
return null;
}
action.accept(list.get(current.getAndIncrement()));
return current.get() < list.size();
}
@Override
public long estimateSize() {
return list.size() - current;
}
@Override
public Spliterator<Author> trySplit() {
int currentSize = list.size() - current.get();
if (currentSize < 10) {
return null;
}
for (int splitPos = currentSize / 2 + current.intValue(); splitPos < list.size(); splitPos++) {
if (list.get(splitPos).getRelatedArticleId() == 0) {
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(list.subList(current.get(), splitPos));
current.set(splitPos);
return spliterator;
}
}
return null;
}
@Override
public long estimateSize() {
return list.size() - current.get();
}
@Override
public int characteristics() {
return CONCURRENT;
}
@Override
public int characteristics() {
return SIZED + CONCURRENT;
}
}