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,11 +2,12 @@ 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;
AtomicInteger current = new AtomicInteger();
public RelatedAuthorSpliterator(List<Author> list) {
this.list = list;
@ -14,21 +15,21 @@ public class RelatedAuthorSpliterator implements Spliterator<Author> {
@Override
public boolean tryAdvance(Consumer<? super Author> action) {
action.accept(list.get(current++));
return current < list.size();
action.accept(list.get(current.getAndIncrement()));
return current.get() < list.size();
}
@Override
public Spliterator<Author> trySplit() {
int currentSize = list.size() - current;
int currentSize = list.size() - current.get();
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;
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;
}
}
@ -37,11 +38,12 @@ public class RelatedAuthorSpliterator implements Spliterator<Author> {
@Override
public long estimateSize() {
return list.size() - current;
return list.size() - current.get();
}
@Override
public int characteristics() {
return SIZED + CONCURRENT;
return CONCURRENT;
}
}