Java Code Examples for java.util.ConcurrentModificationException

The following examples show how to use java.util.ConcurrentModificationException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
public static
void main(String[] args) {
    List list = new LinkedList();
    Object o1 = new Integer(1);
    list.add(o1);
    ListIterator e = list.listIterator();
    e.next();
    Object o2 = new Integer (2);
    list.add(o2);

    try{
        e.remove();
    } catch (ConcurrentModificationException cme) {
        return;
    }

    throw new RuntimeException(
        "LinkedList ListIterator.remove() comodification check failed.");
}
 
Example 2
Source Project: coming   Source File: Arja_00143_t.java    License: MIT License 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw MathRuntimeException.createConcurrentModificationException(LocalizedFormats.MAP_MODIFIED_WHILE_ITERATING);
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) {
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw MathRuntimeException.createNoSuchElementException(LocalizedFormats.ITERATOR_EXHAUSTED);
        }
    }

}
 
Example 3
Source Project: coding-snippets   Source File: KolobokeLongObjectHashMap.java    License: MIT License 6 votes vote down vote up
@Override
@Nonnull
public final Object[] toArray() {
    int size = size();
    Object[] result = new Object[size];
    if (size == 0)
        return result;
    
    int resultIndex = 0;
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    V[] vals = values;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        long key;
        if ((key = keys[i]) != free) {
            result[(resultIndex++)] = new MutableEntry(mc, i, key, vals[i]);
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
    return result;
}
 
Example 4
Source Project: libreveris   Source File: OmrFont.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This is the general paint method for drawing a symbol layout, at
 * a specified location, using a specified alignment.
 *
 * @param g         the graphics environment
 * @param layout    what: the symbol, perhaps transformed
 * @param location  where: the precise location in the display
 * @param alignment how: the way the symbol is aligned wrt the location
 */
public static void paint (Graphics2D g,
                          TextLayout layout,
                          Point location,
                          Alignment alignment)
{
    try {
        // Compute symbol origin
        Rectangle2D bounds = layout.getBounds();
        Point2D toTextOrigin = alignment.toTextOrigin(bounds);
        Point2D origin = new Point2D.Double(
                location.x + toTextOrigin.getX(),
                location.y + toTextOrigin.getY());

        // Draw the symbol
        layout.draw(g, (float) origin.getX(), (float) origin.getY());
    } catch (ConcurrentModificationException ignored) {
    } catch (Exception ex) {
        logger.warn("Cannot paint at " + location, ex);
    }
}
 
Example 5
Source Project: coding-snippets   Source File: KolobokeLongIntHashMap.java    License: MIT License 6 votes vote down vote up
@Override
public boolean reverseRemoveAllFrom(IntSet s) {
    if ((KolobokeLongIntHashMap.ValueView.this.isEmpty()) || (s.isEmpty()))
        return false;
    
    boolean changed = false;
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    int[] vals = values;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        if ((keys[i]) != free) {
            changed |= s.removeInt(vals[i]);
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
    return changed;
}
 
Example 6
Source Project: gemfirexd-oss   Source File: HARegionQueue.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * this method is for transmission of DACE information with initial image state
 * in HARegions.  It should not be used for other purposes.  The map contains
 * only those entries that have no items queued.  This is used to prevent
 * replay of events in the new queue that have already been removed from this queue.
 */
public Map getEventMapForGII() {
  // fix for bug #41621 - concurrent modification exception while serializing event map
  Map<ThreadIdentifier, DispatchedAndCurrentEvents> events = this.eventsMap;
  do {
    HashMap result = new HashMap();
    try {
      for (Map.Entry<ThreadIdentifier, DispatchedAndCurrentEvents> entry: events.entrySet()) {
        if (entry.getValue().isCountersEmpty()) {
          result.put(entry.getKey(), entry.getValue());
        }
      }
      return result;
    } catch (ConcurrentModificationException e) {
      if (this.logger.fineEnabled()) {
        this.logger.fine("HARegion encountered concurrent modification exception while analysing event state - will try again");
      }
    }
  } while (true);
}
 
Example 7
public static
void main(String[] args) {
    List list = new LinkedList();
    Object o1 = new Integer(1);
    list.add(o1);
    ListIterator e = list.listIterator();
    e.next();
    Object o2 = new Integer (2);
    list.add(o2);

    try{
        e.remove();
    } catch (ConcurrentModificationException cme) {
        return;
    }

    throw new RuntimeException(
        "LinkedList ListIterator.remove() comodification check failed.");
}
 
Example 8
public void sort(Comparator<? super E> c) {
    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);
        @SuppressWarnings("unchecked") E[] es = (E[])newElements;
        Arrays.sort(es, lo, hi, c);
        l.setArray(expectedArray = newElements);
    } finally {
        lock.unlock();
    }
}
 
Example 9
@Override
public boolean visit (SystemPart part)
{
    try {
        // Render the part starting barline, if any
        if (part.getStartingBarline() != null) {
            part.getStartingBarline()
                .renderLine(g);
        }
    } catch (ConcurrentModificationException ignored) {
    } catch (Exception ex) {
        logger.warn(
            getClass().getSimpleName() + " Error visiting " + part,
            ex);
    }

    return true;
}
 
Example 10
Source Project: phoebus   Source File: ScanCommandTree.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private TreeItem<ScanCommand> findTreeItem(final long address)
{
    if (address < 0)
        return null;
    while (true)
    {
        try
        {
            return findTreeItem(root.getChildren(), address);
        }
        catch (ConcurrentModificationException ex)
        {
            // XXX Avoid ConcurrentModificationException instead of catching and trying again?
            logger.log(Level.WARNING, "Scan tree needs to re-try lookup of command", ex);
        }
    }
}
 
Example 11
Source Project: android_9.0.0_r45   Source File: ArrayMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Make the array map empty.  All storage is released.
 */
@Override
public void clear() {
    if (mSize > 0) {
        final int[] ohashes = mHashes;
        final Object[] oarray = mArray;
        final int osize = mSize;
        mHashes = EmptyArray.INT;
        mArray = EmptyArray.OBJECT;
        mSize = 0;
        freeArrays(ohashes, oarray, osize);
    }
    if (CONCURRENT_MODIFICATION_EXCEPTIONS && mSize > 0) {
        throw new ConcurrentModificationException();
    }
}
 
Example 12
Source Project: data-structures   Source File: BinarySearchTreeTest.java    License: MIT License 6 votes vote down vote up
@Test(expected = ConcurrentModificationException.class)
public void concurrentModificationErrorRemovingPostOrder() {

  BinarySearchTree<Integer> bst = new BinarySearchTree<>();

  bst.add(1);
  bst.add(2);
  bst.add(3);

  Iterator<Integer> iter = bst.traverse(TreeTraversalOrder.POST_ORDER);

  while (iter.hasNext()) {
    bst.remove(2);
    iter.next();
  }
}
 
Example 13
Source Project: coding-snippets   Source File: KolobokeLongIntHashMap.java    License: MIT License 6 votes vote down vote up
public boolean forEachWhile(LongPredicate predicate) {
    if (predicate == null)
        throw new NullPointerException();
    
    if (KolobokeLongIntHashMap.this.isEmpty())
        return true;
    
    boolean terminated = false;
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        long key;
        if ((key = keys[i]) != free) {
            if (!(predicate.test(key))) {
                terminated = true;
                break;
            } 
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
    return !terminated;
}
 
Example 14
public static
void main(String[] args) {
    List list = new LinkedList();
    Object o1 = new Integer(1);
    list.add(o1);
    ListIterator e = list.listIterator();
    e.next();
    Object o2 = new Integer (2);
    list.add(o2);

    try{
        e.remove();
    } catch (ConcurrentModificationException cme) {
        return;
    }

    throw new RuntimeException(
        "LinkedList ListIterator.remove() comodification check failed.");
}
 
Example 15
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();
    }
}
 
Example 16
Source Project: j2objc   Source File: ArrayListTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * java.util.ArrayList#trimToSize()
 */
public void test_trimToSize() {
    // Test for method void java.util.ArrayList.trimToSize()
    for (int i = 99; i > 24; i--)
        alist.remove(i);
    ((ArrayList) alist).trimToSize();
    assertEquals("Returned incorrect size after trim", 25, alist.size());
    for (int i = 0; i < alist.size(); i++)
        assertTrue("Trimmed list contained incorrect elements", alist
                .get(i) == objArray[i]);
    Vector v = new Vector();
    v.add("a");
    ArrayList al = new ArrayList(v);
    al.add("b");
    Iterator it = al.iterator();
    al.trimToSize();
    try {
        it.next();
        fail("should throw a ConcurrentModificationException");
    } catch (ConcurrentModificationException ioobe) {
        // expected
    }
}
 
Example 17
Source Project: incubator-retired-wave   Source File: ConcurrentSetTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testRemoveWhileLockedDoesNotCauseCme() {
  set.add(a);
  set.add(b);
  set.add(c);
  set.add(d);

  set.lock();
  try {
    // Removals to attempt on every iteration.
    String [] removals = new String [] {b, d, c, a};
    int toRemove = 0;
    for (String x : set) {
      set.remove(removals[toRemove++]);
    }
  } catch (ConcurrentModificationException e) {
    fail("removal during iteration caused CME");
  }
  set.unlock();
}
 
Example 18
Source Project: swellrt   Source File: CopyOnWriteSetTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testRemoveWhileIteratingDoesNotCauseCme() {
  set.add(a);
  set.add(b);
  set.add(c);
  set.add(d);

  try {
    // Removals to attempt on every iteration.
    String [] removals = new String [] {b, d, c, a};
    int toRemove = 0;
    for (String x : set) {
      set.remove(removals[toRemove++]);
    }
  } catch (ConcurrentModificationException e) {
    fail("removal during iteration caused CME");
  }
}
 
Example 19
Source Project: coding-snippets   Source File: KolobokeLongIntHashMap.java    License: MIT License 6 votes vote down vote up
@Override
public final void forEach(@Nonnull
Consumer<? super Map.Entry<Long, Integer>> action) {
    if (action == null)
        throw new NullPointerException();
    
    if (KolobokeLongIntHashMap.EntryView.this.isEmpty())
        return ;
    
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    int[] vals = values;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        long key;
        if ((key = keys[i]) != free) {
            action.accept(new KolobokeLongIntHashMap.MutableEntry(mc, i, key, vals[i]));
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
}
 
Example 20
public void add(ET object) {
    if (expectedModCount == list.modCount) {
        Link<ET> next = link.next;
        Link<ET> newLink = new Link<ET>(object, link, next);
        link.next = newLink;
        next.previous = newLink;
        link = newLink;
        lastLink = null;
        pos++;
        expectedModCount++;
        list.size++;
        list.modCount++;
    } else {
        throw new ConcurrentModificationException();
    }
}
 
Example 21
Source Project: hypergraphdb   Source File: MyIdentityHashMap.java    License: Apache License 2.0 6 votes vote down vote up
Entry<K,V> nextEntry() { 
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    Entry<K,V> e = next;
    if (e == null) 
        throw new NoSuchElementException();
        
    Entry<K,V> n = e.next;
    Entry[] t = table;
    int i = index;
    while (n == null && i > 0)
        n = t[--i];
    index = i;
    next = n;
    return current = e;
}
 
Example 22
Source Project: coming   Source File: Arja_00107_s.java    License: MIT License 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw MathRuntimeException.createConcurrentModificationException(LocalizedFormats.MAP_MODIFIED_WHILE_ITERATING);
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) {
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw MathRuntimeException.createNoSuchElementException(LocalizedFormats.ITERATOR_EXHAUSTED);
        }
    }

}
 
Example 23
Source Project: coding-snippets   Source File: KolobokeLongObjectHashMap.java    License: MIT License 6 votes vote down vote up
public void forEach(Consumer<? super Long> action) {
    if (action == null)
        throw new NullPointerException();
    
    if (KolobokeLongObjectHashMap.this.isEmpty())
        return ;
    
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        long key;
        if ((key = keys[i]) != free) {
            action.accept(key);
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
}
 
Example 24
Source Project: data-structures   Source File: BinarySearchTreeTest.java    License: MIT License 6 votes vote down vote up
@Test(expected = ConcurrentModificationException.class)
public void concurrentModificationErrorRemovingInOrderOrder() {

  BinarySearchTree<Integer> bst = new BinarySearchTree<>();

  bst.add(1);
  bst.add(2);
  bst.add(3);

  Iterator<Integer> iter = bst.traverse(TreeTraversalOrder.IN_ORDER);

  while (iter.hasNext()) {
    bst.remove(2);
    iter.next();
  }
}
 
Example 25
Source Project: coming   Source File: Arja_0032_t.java    License: MIT License 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw MathRuntimeException.createConcurrentModificationException(LocalizedFormats.MAP_MODIFIED_WHILE_ITERATING);
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) {
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw MathRuntimeException.createNoSuchElementException(LocalizedFormats.ITERATOR_EXHAUSTED);
        }
    }

}
 
Example 26
Source Project: astor   Source File: OpenIntToDoubleHashMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw new ConcurrentModificationException();
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) { // NOPMD
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw new NoSuchElementException();
        }
    }

}
 
Example 27
Source Project: coding-snippets   Source File: KolobokeLongIntHashMap.java    License: MIT License 6 votes vote down vote up
@Override
public void replaceAll(LongIntToIntFunction function) {
    if (function == null)
        throw new NullPointerException();
    
    if (KolobokeLongIntHashMap.this.isEmpty())
        return ;
    
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    int[] vals = values;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        long key;
        if ((key = keys[i]) != free) {
            vals[i] = function.applyAsInt(key, vals[i]);
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
}
 
Example 28
Source Project: astor   Source File: OpenIntToFieldHashMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Advance iterator one step further.
 * @exception ConcurrentModificationException if the map is modified during iteration
 * @exception NoSuchElementException if there is no element left in the map
 */
public void advance()
    throws ConcurrentModificationException, NoSuchElementException {

    if (referenceCount != count) {
        throw new ConcurrentModificationException();
    }

    // advance on step
    current = next;

    // prepare next step
    try {
        while (states[++next] != FULL) {
            // nothing to do
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        next = -2;
        if (current < 0) {
            throw new NoSuchElementException();
        }
    }

}
 
Example 29
Source Project: ghidra   Source File: AddressRangeMapDB.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see ghidra.util.datastruct.IndexRangeIterator#hasNext()
 */
@Override
public boolean hasNext() {
	lock.acquire();
	try {
		if (expectedModCount != modCount)
			throw new ConcurrentModificationException();
		if (nextRec != null) {
			return true;
		}
		if (recIter != null) {
			try {
				return recIter.hasNext();
			}
			catch (IOException e) {
				errHandler.dbError(e);
			}
		}
		return false;
	}
	finally {
		lock.release();
	}
}
 
Example 30
Source Project: gatk   Source File: SVIntervalTree.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Node<V> next() {
    if ( next == null ) {
        throw new NoSuchElementException("No next element.");
    }

    if ( next.wasRemoved() ) {
        next = (Node<V>)min(next.getInterval());
        if ( next == null ) {
            throw new ConcurrentModificationException("Current element was removed, and there are no more elements.");
        }
    }
    last = next;
    next = next.getNext();
    return last;
}