Java 类java.util.ConcurrentModificationException 实例源码

项目:NotifyTools    文件:WeakFastHashMap.java   
public void remove() {
    if (lastReturned == null) {
        throw new IllegalStateException();
    }
    if (fast) {
        synchronized (WeakFastHashMap.this) {
            if (expected != map) {
                throw new ConcurrentModificationException();
            }
            WeakFastHashMap.this.remove(lastReturned.getKey());
            lastReturned = null;
            expected = map;
        }
    } else {
        iterator.remove();
        lastReturned = null;
    }
}
项目:android-retrostreams    文件:LinkedListSpliterator.java   
@Override
public void forEachRemaining(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    Object eol = endOfList;
    Object p;
    int n;
    if ((n = getEst()) > 0 && (p = current) != eol) {
        current = eol;
        est = 0;
        do {
            T item = getNodeItem(p);
            p = getNextNode(p);
            action.accept(item);
        } while (p != eol && --n > 0);
    }
    if (expectedModCount != getModCount(list)) {
        throw new ConcurrentModificationException();
    }
}
项目:java-course    文件:SimpleHashtable.java   
/**
 * Returns the next element in the iteration.
 * @return The next element in the iteration.
 * @throws ConcurrentModificationException If collection is updated while iterating through.
 * @throws NoSuchElementException If the iteration has no more elements.
 */
@Override
public TableEntry next() {
    if(expModificationCount != modificationCount) {
        throw new ConcurrentModificationException("Collection is updated while iterating through!");
    }
    for(; currentIndex < table.length; currentIndex++) {
        if(table[currentIndex] != null) {
            if(current == null) {
                current = lastReturned = table[currentIndex];
                current = current.next;
            } else {
                lastReturned = current;
                current = current.next;
            }
            if(current == null) {
                currentIndex++;
            }
            count++;
            return lastReturned;
        }
    }
    throw new NoSuchElementException("There is no more elements in collection!");
}
项目:unitimes    文件:AbstractSolver.java   
@Override
public Map<String,String> statusSolutionInfo() {
    if (isPassivated())
        return (iBestSolutionInfoBeforePassivation == null ? iCurrentSolutionInfoBeforePassivation : iBestSolutionInfoBeforePassivation);
    Lock lock = currentSolution().getLock().readLock();
    lock.lock();
    try {
        Map<String,String> info = super.currentSolution().getBestInfo();
        try {
            Solution<V, T> solution = getWorkingSolution();
            if (info == null || getSolutionComparator().isBetterThanBestSolution(solution))
                info = solution.getModel().getInfo(solution.getAssignment());
        } catch (ConcurrentModificationException e) {}
        return info;
    } finally {
        lock.unlock();
    }
}
项目:Uranium    文件:UnsafeList.java   
public void remove() {
    if (lastRet < 0) {
        throw new IllegalStateException();
    }

    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }

    try {
        UnsafeList.this.remove(lastRet);
        index = lastRet;
        lastRet = -1;
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}
项目:jdk8u-jdk    文件:CopyOnWriteArrayList.java   
public void replaceAll(UnaryOperator<E> operator) {
    if (operator == null) throw new NullPointerException();
    final ReentrantLock lock = l.lock;
    lock.lock();
    try {
        int lo = offset;
        int hi = offset + size;
        Object[] elements = expectedArray;
        if (l.getArray() != elements)
            throw new ConcurrentModificationException();
        int len = elements.length;
        if (lo < 0 || hi > len)
            throw new IndexOutOfBoundsException();
        Object[] newElements = Arrays.copyOf(elements, len);
        for (int i = lo; i < hi; ++i) {
            @SuppressWarnings("unchecked") E e = (E) elements[i];
            newElements[i] = operator.apply(e);
        }
        l.setArray(expectedArray = newElements);
    } finally {
        lock.unlock();
    }
}
项目:Uranium    文件:LongHashSet.java   
@Override
public Long next() {
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }

    int length = values.length;
    if (index >= length) {
        lastReturned = -2;
        throw new NoSuchElementException();
    }

    lastReturned = index;
    for (index += 1; index < length && (values[index] == FREE || values[index] == REMOVED); index++) {
        // This is just to drive the index forward to the next valid entry
    }

    if (values[lastReturned] == FREE) {
        return FREE;
    } else {
        return values[lastReturned];
    }
}
项目:sstore-soft    文件:LocalInitQueueCallback.java   
@Override
public String toString() {
    String ret = super.toString();
    if (this.responses.isEmpty() == false) {
        ret += "\n-------------\n";
        String debug = "";
        while (true) {
            try {
                debug = StringUtil.join("\n", this.responses); 
            } catch (ConcurrentModificationException ex) {
                continue;
            }
            break;
        }
        ret += debug;
    }
    return (ret);
}
项目:alfresco-repository    文件:AuthorityBridgeTableAsynchronouslyRefreshedCache.java   
private BridgeTable<String> doBuildCache(String tenantId)
{
    List<AuthorityBridgeLink> links = authorityBridgeDAO.getAuthorityBridgeLinks();
    BridgeTable<String> bridgeTable = new BridgeTable<String>();
    try
    {
        for (AuthorityBridgeLink link : links)
        {
            bridgeTable.addLink(link.getParentName(), link.getChildName());
        }
    }
    catch (ConcurrentModificationException e)
    {
        // Explain exception
        checkCyclic(links);
        // If cyclic groups is not the cause then rethrow
        throw e;
    }
    return bridgeTable;
}
项目:hadoop-oss    文件:LightWeightGSet.java   
private void ensureNext() {
  if (trackModification && modification != iterModification) {
    throw new ConcurrentModificationException("modification=" + modification
        + " != iterModification = " + iterModification);
  }
  if (next != null) {
    return;
  }
  if (cur == null) {
    return;
  }
  next = cur.getNext();
  if (next == null) {
    next = nextNonemptyEntry();
  }
}
项目:xcc    文件:THashPrimitiveIterator.java   
/**
 * Removes the last entry returned by the iterator.
 * Invoking this method more than once for a single entry
 * will leave the underlying data structure in a confused
 * state.
 */
public void remove() {
    if (_expectedSize != _hash.size()) {
        throw new ConcurrentModificationException();
    }

    // Disable auto compaction during the remove. This is a workaround for bug 1642768.
    try {
        _hash.tempDisableAutoCompaction();
        _hash.removeAt(_index);
    }
    finally {
        _hash.reenableAutoCompaction( false );
    }

    _expectedSize--;
}
项目:hadoop    文件:LightWeightHashSet.java   
@Override
public T next() {
  if (modification != startModification) {
    throw new ConcurrentModificationException("modification="
        + modification + " != startModification = " + startModification);
  }
  if (next == null) {
    throw new NoSuchElementException();
  }
  final T e = next.element;
  // find the next element
  final LinkedElement<T> n = next.next;
  next = n != null ? n : nextNonemptyEntry();
  return e;
}
项目:guava-mock    文件:MapPutTester.java   
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithValueIteration() {
  try {
    Iterator<V> iterator = getMap().values().iterator();
    put(e3());
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}
项目:OpenJSharp    文件:CopyOnWriteArrayList.java   
public boolean retainAll(Collection<?> c) {
    if (c == null) throw new NullPointerException();
    boolean removed = false;
    final ReentrantLock lock = l.lock;
    lock.lock();
    try {
        int n = size;
        if (n > 0) {
            int lo = offset;
            int hi = offset + n;
            Object[] elements = expectedArray;
            if (l.getArray() != elements)
                throw new ConcurrentModificationException();
            int len = elements.length;
            if (lo < 0 || hi > len)
                throw new IndexOutOfBoundsException();
            int newSize = 0;
            Object[] temp = new Object[n];
            for (int i = lo; i < hi; ++i) {
                Object element = elements[i];
                if (c.contains(element))
                    temp[newSize++] = element;
            }
            if (newSize != n) {
                Object[] newElements = new Object[len - n + newSize];
                System.arraycopy(elements, 0, newElements, 0, lo);
                System.arraycopy(temp, 0, newElements, lo, newSize);
                System.arraycopy(elements, hi, newElements,
                                 lo + newSize, len - hi);
                size = newSize;
                removed = true;
                l.setArray(expectedArray = newElements);
            }
        }
    } finally {
        lock.unlock();
    }
    return removed;
}
项目:cuttlefish    文件:ContestSimulation.java   
public void reset() {
    setIncremental(true);
    for (Edge edge : super.getEdges())
        super.removeEdge(edge);

    Collection<Vertex> vertices = super.getVertices();
    while (!vertices.isEmpty()) {
        try {
            for (Vertex vertex : vertices)
                super.removeVertex(vertex);
        } catch (ConcurrentModificationException e) {
        }
    }
    update(0);
}
项目:guava-mock    文件:MapPutTester.java   
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithEntrySetIteration() {
  try {
    Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
    put(e3());
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}
项目:APCSAB    文件:MyStack.java   
public E next() {
    // Load head lazily
    if (-1 == size) {
        size = MyStack.this.size;
        next = head;
    }
    // Size has changed
    if (size != MyStack.this.size)
        throw new ConcurrentModificationException();
    E value = next.value;
    next = next.getNext();
    return value;
}
项目:guava-mock    文件:MapClearTester.java   
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_REMOVE})
@CollectionSize.Require(SEVERAL)
public void testClearConcurrentWithEntrySetIteration() {
  try {
    Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
    getMap().clear();
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}
项目:s-store    文件:AbstractMapBasedMultimap.java   
/**
 * If the delegate collection is empty, but the multimap has values for the
 * key, replace the delegate with the new collection for the key.
 *
 * <p>For a subcollection, refresh its ancestor and validate that the
 * ancestor delegate hasn't changed.
 */
void refreshIfEmpty() {
  if (ancestor != null) {
    ancestor.refreshIfEmpty();
    if (ancestor.getDelegate() != ancestorDelegate) {
      throw new ConcurrentModificationException();
    }
  } else if (delegate.isEmpty()) {
    Collection<V> newDelegate = map.get(key);
    if (newDelegate != null) {
      delegate = newDelegate;
    }
  }
}
项目:openjdk-jdk10    文件:SubList.java   
@Test(dataProvider = "modifiable",
      expectedExceptions = ConcurrentModificationException.class)
public void testModIteratorRemove(List<Integer> list, int from, int to) {
    List<Integer> subList = list.subList(from, to);
    Iterator<Integer> it = subList.iterator();
    it.next();
    list.add(42);
    it.remove();
}
项目:java-course    文件:SimpleHashtableTest.java   
@Test(expected=ConcurrentModificationException.class)
public void iteratorThrowExceptionIfPuttingAndRemovingElement() {
    fillHashtable();

    Iterator<SimpleHashtable.TableEntry> iterator = hashtable.iterator();
    while(iterator.hasNext()) {
        SimpleHashtable.TableEntry pair = iterator.next();
        if(pair.getValue().equals("Njemacka")) {
            hashtable.put("Toyota","Japan");
            iterator.remove();
        }
    }
}
项目:GitHub    文件:StatefulRunnableTest.java   
@Test
public void testClosesResultWhenOnSuccessThrows() throws Exception {
  doThrow(mException).when(mStatefulRunnable).onSuccess(mResult);
  try {
    runSuccess();
    fail();
  } catch (ConcurrentModificationException cme) {
    // expected
  }
  verify(mStatefulRunnable).disposeResult(mResult);
}
项目:GitHub    文件:ArtDecoderTest.java   
@Test(expected = ConcurrentModificationException.class)
public void testBitmapFactoryThrowsAnException() {
  whenBitmapFactoryDecodeStream()
      .thenAnswer(mBitmapFactoryDefaultAnswer)
      .thenThrow(new ConcurrentModificationException());
  try {
    mArtDecoder.decodeFromEncodedImage(mEncodedImage, DEFAULT_BITMAP_CONFIG, null);
  } finally {
    verify(mBitmapPool).release(mBitmap);
  }
}
项目:dremio-oss    文件:DatastoreRpcClient.java   
public void delete(String storeId, ByteString key, long previousVersion) throws RpcException {
  final DeleteRequest.Builder builder = DeleteRequest.newBuilder();
  builder.setStoreId(storeId);
  builder.setKey(key);
  builder.setPreviousVersion(previousVersion);
  ReceivedResponseMessage<DeleteResponse> response = rpcService.getDeleteEndpoint().send(builder.build());
  if (response.getBody().hasConcurrentModificationError()) {
    throw new ConcurrentModificationException(response.getBody().getConcurrentModificationError());
  }
}
项目:googles-monorepo-demo    文件:AbstractMultisetSetCountTester.java   
@CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithEntrySetIteration() {
  try {
    Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
    assertSetCount(e0(), 0);
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}
项目:monarch    文件:ObjectIntHashMap.java   
final Entry nextEntry() {
  if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
  Entry e = next;
  if (e == null)
    throw new NoSuchElementException();

  if ((next = e.next) == null) {
    Entry[] t = table;
    while (index < t.length && (next = t[index++]) == null);
  }
  current = e;
  return e;
}
项目:guava-mock    文件:CollectionRemoveIfTester.java   
@CollectionFeature.Require({SUPPORTS_ITERATOR_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(SEVERAL)
public void testRemoveIfSomeMatchesConcurrentWithIteration() {
  try {
    Iterator<E> iterator = collection.iterator();
    assertTrue(collection.removeIf(Predicate.isEqual(samples.e0())));
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}
项目:guava-mock    文件:CollectionRemoveAllTester.java   
@CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(SEVERAL)
public void testRemoveAllSomePresentConcurrentWithIteration() {
  try {
    Iterator<E> iterator = collection.iterator();
    assertTrue(collection.removeAll(MinimalCollection.of(e0(), e3())));
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}
项目:HCFCore    文件:AbstractLinkedMap.java   
protected LinkEntry<K, V> nextEntry() {
    if (parent.modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    if (next == parent.header)  {
        throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY);
    }
    last = next;
    next = next.after;
    return last;
}
项目:HCFCore    文件:AbstractLinkedMap.java   
protected LinkEntry<K, V> nextEntry() {
    if (parent.modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    if (next == parent.header)  {
        throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY);
    }
    last = next;
    next = next.after;
    return last;
}
项目:java-kdtree    文件:TreeMapTest.java   
@Test(expected = ConcurrentModificationException.class)
public void testConcurrentRemoveAll() throws Exception {
    ArrayList<CartesianPoint> list = new ArrayList<>();
    TreeMap<CartesianPoint, String> map = new TreeMap<>(TreeMap.Space2D);
    for (int i = 0; i < 10; i++) {
        CartesianPoint point = new CartesianPoint(i, i);
        map.put(point, Integer.toString(i * i));
        if (i % 2 == 0) list.add(point.clone());
    }
    Iterator<Entry<CartesianPoint, String>> iterator = map.entrySet().iterator();
    map.keySet().removeAll(list);
    iterator.next();
}
项目:HCFCore    文件:AbstractPatriciaTrie.java   
/**
 * Returns the next {@link TrieEntry}.
 */
protected TrieEntry<K,V> nextEntry() {
    if (expectedModCount != AbstractPatriciaTrie.this.modCount) {
        throw new ConcurrentModificationException();
    }

    final TrieEntry<K,V> e = next;
    if (e == null) {
        throw new NoSuchElementException();
    }

    next = findNext(e);
    current = e;
    return e;
}
项目:Logisim    文件:ArraySet.java   
@Override
public E next() {
    if (itVersion != version) {
        throw new ConcurrentModificationException();
    } else if (!hasNext) {
        throw new NoSuchElementException();
    } else {
        E ret = (E) values[pos];
        ++pos;
        hasNext = pos < values.length;
        removeOk = true;
        return ret;
    }
}
项目:java-kdtree    文件:TreeMapTest.java   
@Test(expected = ConcurrentModificationException.class)
public void testConcurrentRemoveKeyValue() throws Exception {
    TreeMap<CartesianPoint, String> map = new TreeMap<>(TreeMap.Space2D);
    for (int i = 0; i < 10; i++) {
        CartesianPoint point = new CartesianPoint(i, i);
        map.put(point, Integer.toString(i * i));
    }
    Iterator<Entry<CartesianPoint, String>> iterator = map.entrySet().iterator();
    map.remove(new CartesianPoint(0, 0), Integer.toString(0));
    iterator.next();
}
项目:dremio-oss    文件:DatastoreRpcClient.java   
public Long put(String storeId, ByteString key, ByteString value) throws RpcException {
  final PutRequest.Builder builder = PutRequest.newBuilder();
  builder.setStoreId(storeId);
  builder.setKey(key);
  builder.setValue(value);
  ReceivedResponseMessage<PutResponse> response = rpcService.getPutEndpoint().send(builder.build());
  if (response.getBody().hasConcurrentModificationError()) {
    throw new ConcurrentModificationException(response.getBody().getConcurrentModificationError());
  }
  if (response.getBody().hasVersion()) {
    return response.getBody().getVersion();
  }
  return null;
}
项目:googles-monorepo-demo    文件:CollectionAddTester.java   
@CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddConcurrentWithIteration() {
  try {
    Iterator<E> iterator = collection.iterator();
    assertTrue(collection.add(e3()));
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}
项目:incubator-netbeans    文件:JavaElementFoldVisitor.java   
private void handleJavadoc(Tree t) throws BadLocationException, ConcurrentModificationException {
    int start = (int) sp.getStartPosition(cu, t);

    if (start == (-1))
        return ;

    if (start < initialCommentStopPos)
        initialCommentStopPos = start;

    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId>  ts = th.tokenSequence(JavaTokenId.language());

    if (ts.move(start) == Integer.MAX_VALUE) {
        return;//nothing
    }

    while (ts.movePrevious()) {
        Token<JavaTokenId> token = ts.token();

        if (token.id() == JavaTokenId.JAVADOC_COMMENT) {
            int startOffset = ts.offset();
            addFold(creator.createJavadocFold(startOffset, startOffset + token.length()), startOffset);
            if (startOffset < initialCommentStopPos)
                initialCommentStopPos = startOffset;
        }
        if (   token.id() != JavaTokenId.WHITESPACE
            && token.id() != JavaTokenId.BLOCK_COMMENT
            && token.id() != JavaTokenId.LINE_COMMENT)
            break;
    }
}
项目:incubator-netbeans    文件:TimeComponentPanel.java   
private void fillTimeTable() {
    Reference ref = (Reference)jList1.getSelectedValue();
    Object fo = ref == null ? null : ref.get();

    // clear the table
    DefaultTableModel model = (DefaultTableModel) times.getModel();
    while (model.getRowCount() > 0) {
        model.removeRow(0);
    }
    key2RowNumber.clear();

    if (fo == null) return;

    Collection<String> keys = TimesCollectorPeer.getDefault().getKeysForFile(fo);
    for (int i = 0; i < 10; i++) {
        try {
            synchronized(keys) {
                for (String key : keys) {
                    changeRow(fo, key);
                }
                return;
            }
        } catch (ConcurrentModificationException ex) {
            LOG.log(Level.INFO, "Retry " + i, ex);
        }
    }
}
项目:incubator-netbeans    文件:IdentityHashSet.java   
protected int nextIndex() {
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    if (!hasNext()) {
        throw new NoSuchElementException();
    }

    indexValid = false;
    lastReturnedIndex = index;
    index++;
    return lastReturnedIndex;
}
项目:guava-mock    文件:AbstractMultisetSetCountTester.java   
@CollectionFeature.Require({SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithEntrySetIteration() {
  try {
    Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
    assertSetCount(e0(), 0);
    iterator.next();
    fail("Expected ConcurrentModificationException");
  } catch (ConcurrentModificationException expected) {
    // success
  }
}