Fail-fast iterators

Hi,
I am writing a Thread that necessarily has to iterate through the values stored in Hashtable. This Hashtable can also have elements added and removed from it concurrently while the Thread is running.
The Thread itself will only run about once every 5 minutes and it is used to remove stale entries from the table.
What I am currently doing is getting a Collection view of the Hashtable and then using an iterator to iterate through it.
Collection col = table.values();
for(Iterator itor = col.iterator(); itor.hasNext(); )
    try
        TableEntry te = (TableEntry) itor.next();
        if(System.getTimeMillis() - te.timestamp > this.ttl)
            itor.remove();
    catch(ConcurrentModificationException e)
        //the iterator has failed fast
    catch(NullPointerException e)
        //will I even get an NPE if the Iterator doesn't fail fast?
}The API says that the fail-fast property of a Collections iterator should not be relied upon to guarantee program correctness.
I do not particularly care if items are added to the Hashtable while the cleaning Thread is running, they won't be stale entries anyway. I assume that an Iterator created before anything is added will 'skip' over the added values if it doesn't fail-fast, is this the case? (I am well aware of the dangers of assuming, that's why I'm also asking:) )
What I do care about is entries that are removed concurrently with the cleaning Thread. If the Iterator does not fail-fast will it return null when I call itor.next() if the value that should be returned has been removed?
Also I would like to be able to continue processing the 'collection' of entries as it was before the Iterator failed-fast (obviously skipping any new entries or removed entries). If I catch the ConcurrentModificationException but don't break out of the loop will a ConcurrentModificationException be thrown for every subsequent interation of the loop?
The tutorials that I have read all seem to assume that nothing will go wrong when working with Iterators...

Thanks for the replies.
I am implementing a part of a distributed system here.
The Hashtable is used to store results that have been computed (by another Thread) until the process that requested the processing be done fetches them (they are removed from the table when they are fetched).
Ideally I could just assume that everything that requests processing will be good enough to fetch the results but I know that I can't, so I figured having a Thread that slept for about 5 minutes at a time and when it woke up cleaned any stale entries would be a good thing.
Because of this I imagine very few elements would expire, it is only going to happen when other programmers forget to fetch the results, or if the network was to go down badly, this is why I only envisage running the cleaner Thread very rarely (once every 5 minutes would be a lower bound)
I chose Hashtable because of the way that it is synchronized. Since a new Thread is created for every processing request it is possible for a number of Threads to all be trying to access the table at the same time. I have looked at LinkedHashMap, and while it will be able to iterate through it faster, concurrent accesses would be slower (since I'd have to wrap it in a SynchronizedMap). Given that iterating through it is rare, I am not too concerned if a Hashtable is marginally slower.
Seeing as my iterator would be toast once a ConcurrentModificationException is thrown is there any way I can completely lock the table while the cleanup Thread is running?
AFAIK synchronizing on the table before the loop won't make the loop a critical section, it will just mutex the table object. Is there any way to define a critical section based on a mutex (very C/C++ style thinking, I know) such that I could prevent concurrent accesses to the table until the cleanup Thread has finished it's loop?
I appreciate your help
-Gordon

Similar Messages

  • How do you measure if a battery is failing faster than normal?

    How can you tell if your battery is failing faster than normal or acceptable?
    I bought 2 batteries with my G4 Powerbook 2 years ago. One now gives me an hour of battery life, and one 1.5 hours. This seems very low considering it's only 1 year of use per battery. Apple Care only asks about how long the battery has been owned... never how much it has been used, number of cycles, amps, etc.
    Battery Information:
    BATTERY #1
    Full Charge Capacity (mAh): 2703
    Remaining Capacity (mAh): 2170
    Amperage (mA): 637
    Voltage (mV): 12522
    Cycle Count: 190
    BATTERY #2:
    Full Charge Capacity (mAh): 3032
    Remaining Capacity (mAh): 3027
    Amperage (mA): 0
    Voltage (mV): 12417
    Cycle Count: 105
    Compare these numbers with my brother's PowerBook G4, bought just a few months after mine:
    My main battery has 209 cycles and a capacity of 3686 mAh. My secondary has only 29 cycles and a capacity of 4400 mAh.
    why does he have 3686 mAh after 209 cycles, and my bettery has 2703 after 190 cycles? Is there some way to tell if this is "inappropriate" loss of power?
    Thanks
    -Erika
    PowerBook G4   Mac OS X (10.4.4)  

    I did do several things wrong (that I only found out about now):
    1. I left the computer plugged into AC
    2. I stored whichever battery was not in use full, rather than half full
    But I did callibrate regularly (if only by necessity).
    I still think 1.5 hours at 2 years is not very good if you are using two batteries (that's really only one year each).
    However, I called AppleCare, and I was told they will only consider a battery if it has been owned for under a year, and has less than one hour of life at best. That still seems extremely low to me (I'd be upset if I had 1 hour at 1 year on my only battery), but such is life. I think the moral of the story is that it would help to give instructions about battery care with the computer, and don't buy an extra battery unless you really need it.

  • Old imac G5 screen failing fast

    I have an old imac G5 and the screen seems to be failing fast. There are multiple green, red, yellow, blue and pink neon lines running vertically through the screen. It's getting to the point where I can't even use it because i can't see what I'm doing. Is this because the graphics card is failing? How can i fix this? I dont have the money to just go buy a new mac plus I love this one.

    The fastest way to differentiate between the gfx chipset on the logic bard and the display itself is to attach an external monitor. If the problems persist on the external monitor, that pretty much fingers the gfx chipset. Not 100% sure about your model but I'm pretty sure you don't have  a video or graphcis "card." Until fairly recently, the gpx chipset was integral with and soldered to the logic board, meaning the only fix is a complete logic board change-out.
    If the external monitor shows no problems, that fingers the display itself or the cabling as the problem. Not a cheap fix but certainly better than a new logic board. If you have a spare external monitor and the right cabling, and the image looks fine on it, you could simply leave the external attached and forget about the built-in display.
    A lot of G5 owners reported similar issues with their displays. One common factor was a serial number starting with "W8." See what your serial number starts with (just don't post your entire serial number here for security reasons.)

  • HELP me with the source code

    In this assignment you are asked to create a Java class that simulates the Java Vector class. You are also asked to create two Exception classes to allow the program to continue if errors occur. These are �MyVectNoDataException� and �MyVectIndexOutOfBoundsException�.
    1.     Write a Java class called �myVect� which will operate in the same way as the Java Vector class. In particular it should have
    a.     The following data members
    i.     An Object array
    ii.     An integer �size� that determines the size of the array
    iii.     An integer �increment� that defines the number of additional elements that will be added when the Array is to be resized.
    b.     The following methods
    i.     Constructor 1      myVect()that creates a new myVect object with an internal array size of 10 and an increment of 3.
    ii.     Constructor 2           myVect(int s)
    that creates a new myVect object with an internal array size of s and an increment of 3.
    iii.     Constructor 3           myVect(int s, int i)
    that creates a new myVect object with an internal array size of s and an increment of i.
    iv.     A method          void resize()
    that increases the size of the internal array by the number of elements in the �increment� variable.
    v.     A method      void addElement(Object o)
    that inserts an Object at the next available position in the internal array. If there are less than 3 vacant elements left in the array then the resize() method should be run automatically.
    vi.     A method      void deleteElement()
    that deletes the Object at the last occupied position in the internal array. If no element contains an Object then a MyVectNoDataException should be thrown and the program should continue.
    vii.     A method void insertElement(Object o,int p)
    that inserts an Object at position p in the internal array. The Objects at position p and below should each be moved down by one position before the insertion.
    If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue.
    viii.     A method void deleteElementAt(int p)
    that deletes the Object at position p in the internal array. The Objects below position p should each be moved up by one position after the deletion. If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue.
    If the position p is valid but does not contain an Object then a MyVectNoDataException should be thrown and the program should continue.
    ix.     A method      Object getElement()
    that returns the Object at the last occupied position in the internal array.
    x.     A method      Object getElementAt(int p)
    that returns the Object at position p in the internal array. If the index p is outside the bounds of the internal array then a MyVectIndexOutOfBoundsException should be thrown and the program should continue. If the position p is valid but does not contain an Object then a MyVectNoDataException should be thrown and the program should continue.
    xi.     A toString() method that produces a formatted String representing the myVect object and its data. It should also include the size and increment values.
    c.     Write a Java program called Assign3.java that creates a myVect object then
    i.     Store 6 objects of the following types
    1.     String
    2.     Date
    3.     Integer
    4.     String
    5.     StringTokenizer
    6.     Date
    ii.     Print the myVect object.
    iii.     Add 2 more objects
    1.     StringBuffer
    2.     Double
    iv.     Print the myVect object
    v.     Delete the Object at position 2
    vi.     Delete the Object at position 15
    vii.     Display the Object at position 10
    viii.     Display the length of the second String.
    ix.     Print the myVect object
    d.     Include Javadoc comments in the myVect class code then produce Java documentation using Javadoc.

    * @(#)MyOwnVectorReallyItIs.java     1.89 03/01/23
    * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    package java.util;
    * The <code>MyOwnVectorReallyItIs</code> class implements a growable array of
    * objects. Like an array, it contains components that can be
    * accessed using an integer index. However, the size of a
    * <code>MyOwnVectorReallyItIs</code> can grow or shrink as needed to accommodate
    * adding and removing items after the <code>MyOwnVectorReallyItIs</code> has been created.<p>
    * Each MyOwnVectorReallyItIs tries to optimize storage management by maintaining a
    * <code>capacity</code> and a <code>capacityIncrement</code>. The
    * <code>capacity</code> is always at least as large as the MyOwnVectorReallyItIs
    * size; it is usually larger because as components are added to the
    * MyOwnVectorReallyItIs, the MyOwnVectorReallyItIs's storage increases in chunks the size of
    * <code>capacityIncrement</code>. An application can increase the
    * capacity of a MyOwnVectorReallyItIs before inserting a large number of
    * components; this reduces the amount of incremental reallocation. <p>
    * As of the Java 2 platform v1.2, this class has been retrofitted to
    * implement List, so that it becomes a part of Java's collection framework.
    * Unlike the new collection implementations, MyOwnVectorReallyItIs is synchronized.<p>
    * The Iterators returned by MyOwnVectorReallyItIs's iterator and listIterator
    * methods are <em>fail-fast</em>: if the MyOwnVectorReallyItIs is structurally modified
    * at any time after the Iterator is created, in any way except through the
    * Iterator's own remove or add methods, the Iterator will throw a
    * ConcurrentModificationException.  Thus, in the face of concurrent
    * modification, the Iterator fails quickly and cleanly, rather than risking
    * arbitrary, non-deterministic behavior at an undetermined time in the future.
    * The Enumerations returned by MyOwnVectorReallyItIs's elements method are <em>not</em>
    * fail-fast.
    * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
    * as it is, generally speaking, impossible to make any hard guarantees in the
    * presence of unsynchronized concurrent modification.  Fail-fast iterators
    * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
    * Therefore, it would be wrong to write a program that depended on this
    * exception for its correctness:  <i>the fail-fast behavior of iterators
    * should be used only to detect bugs.</i><p>
    * This class is a member of the
    * <a href="{@docRoot}/../guide/collections/index.html">
    * Java Collections Framework</a>.
    * @author  Lee Boynton
    * @author  Jonathan Payne
    * @version 1.89, 01/23/03
    * @see Collection
    * @see List
    * @see ArrayList
    * @see LinkedList
    * @since   JDK1.0
    public class MyOwnVectorReallyItIs extends AbstractList
            implements List, RandomAccess, Cloneable, java.io.Serializable
         * The array buffer into which the components of the MyOwnVectorReallyItIs are
         * stored. The capacity of the MyOwnVectorReallyItIs is the length of this array buffer,
         * and is at least large enough to contain all the MyOwnVectorReallyItIs's elements.<p>
         * Any array elements following the last element in the MyOwnVectorReallyItIs are null.
         * @serial
        protected Object elementData[];
         * The number of valid components in this <tt>MyOwnVectorReallyItIs</tt> object.
         * Components <tt>elementData[0]</tt> through
         * <tt>elementData[elementCount-1]</tt> are the actual items.
         * @serial
        protected int elementCount;
         * The amount by which the capacity of the MyOwnVectorReallyItIs is automatically
         * incremented when its size becomes greater than its capacity.  If
         * the capacity increment is less than or equal to zero, the capacity
         * of the MyOwnVectorReallyItIs is doubled each time it needs to grow.
         * @serial
        protected int capacityIncrement;
        /** use serialVersionUID from JDK 1.0.2 for interoperability */
        private static final long serialVersionUID = -2767605614048989439L;
         * Constructs an empty MyOwnVectorReallyItIs with the specified initial capacity and
         * capacity increment.
         * @param   initialCapacity     the initial capacity of the MyOwnVectorReallyItIs.
         * @param   capacityIncrement   the amount by which the capacity is
         *                              increased when the MyOwnVectorReallyItIs overflows.
         * @exception IllegalArgumentException if the specified initial capacity
         *               is negative
        public MyOwnVectorReallyItIs(int initialCapacity, int capacityIncrement) {
         super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
         this.elementData = new Object[initialCapacity];
         this.capacityIncrement = capacityIncrement;
         * Constructs an empty MyOwnVectorReallyItIs with the specified initial capacity and
         * with its capacity increment equal to zero.
         * @param   initialCapacity   the initial capacity of the MyOwnVectorReallyItIs.
         * @exception IllegalArgumentException if the specified initial capacity
         *               is negative
        public MyOwnVectorReallyItIs(int initialCapacity) {
         this(initialCapacity, 0);
         * Constructs an empty MyOwnVectorReallyItIs so that its internal data array
         * has size <tt>10</tt> and its standard capacity increment is
         * zero.
        public MyOwnVectorReallyItIs() {
         this(10);
         * Constructs a MyOwnVectorReallyItIs containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         * @param c the collection whose elements are to be placed into this
         *       MyOwnVectorReallyItIs.
         * @throws NullPointerException if the specified collection is null.
         * @since   1.2
        public MyOwnVectorReallyItIs(Collection c) {
            elementCount = c.size();
            // 10% for growth
            elementData = new Object[
                          (int)Math.min((elementCount*110L)/100,Integer.MAX_VALUE)];
            c.toArray(elementData);
         * Copies the components of this MyOwnVectorReallyItIs into the specified array. The
         * item at index <tt>k</tt> in this MyOwnVectorReallyItIs is copied into component
         * <tt>k</tt> of <tt>anArray</tt>. The array must be big enough to hold
         * all the objects in this MyOwnVectorReallyItIs, else an
         * <tt>IndexOutOfBoundsException</tt> is thrown.
         * @param   anArray   the array into which the components get copied.
         * @throws  NullPointerException if the given array is null.
        public synchronized void copyInto(Object anArray[]) {
         System.arraycopy(elementData, 0, anArray, 0, elementCount);
         * Trims the capacity of this MyOwnVectorReallyItIs to be the MyOwnVectorReallyItIs's current
         * size. If the capacity of this MyOwnVectorReallyItIs is larger than its current
         * size, then the capacity is changed to equal the size by replacing
         * its internal data array, kept in the field <tt>elementData</tt>,
         * with a smaller one. An application can use this operation to
         * minimize the storage of a MyOwnVectorReallyItIs.
        public synchronized void trimToSize() {
         modCount++;
         int oldCapacity = elementData.length;
         if (elementCount < oldCapacity) {
             Object oldData[] = elementData;
             elementData = new Object[elementCount];
             System.arraycopy(oldData, 0, elementData, 0, elementCount);
         * Increases the capacity of this MyOwnVectorReallyItIs, if necessary, to ensure
         * that it can hold at least the number of components specified by
         * the minimum capacity argument.
         * <p>If the current capacity of this MyOwnVectorReallyItIs is less than
         * <tt>minCapacity</tt>, then its capacity is increased by replacing its
         * internal data array, kept in the field <tt>elementData</tt>, with a
         * larger one.  The size of the new data array will be the old size plus
         * <tt>capacityIncrement</tt>, unless the value of
         * <tt>capacityIncrement</tt> is less than or equal to zero, in which case
         * the new capacity will be twice the old capacity; but if this new size
         * is still smaller than <tt>minCapacity</tt>, then the new capacity will
         * be <tt>minCapacity</tt>.
         * @param minCapacity the desired minimum capacity.
        public synchronized void ensureCapacity(int minCapacity) {
         modCount++;
         ensureCapacityHelper(minCapacity);
         * This implements the unsynchronized semantics of ensureCapacity.
         * Synchronized methods in this class can internally call this
         * method for ensuring capacity without incurring the cost of an
         * extra synchronization.
         * @see java.util.MyOwnVectorReallyItIs#ensureCapacity(int)
        private void ensureCapacityHelper(int minCapacity) {
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
             Object oldData[] = elementData;
             int newCapacity = (capacityIncrement > 0) ?
              (oldCapacity + capacityIncrement) : (oldCapacity * 2);
                 if (newCapacity < minCapacity) {
              newCapacity = minCapacity;
             elementData = new Object[newCapacity];
             System.arraycopy(oldData, 0, elementData, 0, elementCount);
         * Sets the size of this MyOwnVectorReallyItIs. If the new size is greater than the
         * current size, new <code>null</code> items are added to the end of
         * the MyOwnVectorReallyItIs. If the new size is less than the current size, all
         * components at index <code>newSize</code> and greater are discarded.
         * @param   newSize   the new size of this MyOwnVectorReallyItIs.
         * @throws  ArrayIndexOutOfBoundsException if new size is negative.
        public synchronized void setSize(int newSize) {
         modCount++;
         if (newSize > elementCount) {
             ensureCapacityHelper(newSize);
         } else {
             for (int i = newSize ; i < elementCount ; i++) {
              elementData[i] = null;
         elementCount = newSize;
         * Returns the current capacity of this MyOwnVectorReallyItIs.
         * @return  the current capacity (the length of its internal
         *          data array, kept in the field <tt>elementData</tt>
         *          of this MyOwnVectorReallyItIs).
        public synchronized int capacity() {
         return elementData.length;
         * Returns the number of components in this MyOwnVectorReallyItIs.
         * @return  the number of components in this MyOwnVectorReallyItIs.
        public synchronized int size() {
         return elementCount;
         * Tests if this MyOwnVectorReallyItIs has no components.
         * @return  <code>true</code> if and only if this MyOwnVectorReallyItIs has
         *          no components, that is, its size is zero;
         *          <code>false</code> otherwise.
        public synchronized boolean isEmpty() {
         return elementCount == 0;
         * Returns an enumeration of the components of this MyOwnVectorReallyItIs. The
         * returned <tt>Enumeration</tt> object will generate all items in
         * this MyOwnVectorReallyItIs. The first item generated is the item at index <tt>0</tt>,
         * then the item at index <tt>1</tt>, and so on.
         * @return  an enumeration of the components of this MyOwnVectorReallyItIs.
         * @see     Enumeration
         * @see     Iterator
        public Enumeration elements() {
         return new Enumeration() {
             int count = 0;
             public boolean hasMoreElements() {
              return count < elementCount;
             public Object nextElement() {
              synchronized (MyOwnVectorReallyItIs.this) {
                  if (count < elementCount) {
                   return elementData[count++];
              throw new NoSuchElementException("MyOwnVectorReallyItIs Enumeration");
         * Tests if the specified object is a component in this MyOwnVectorReallyItIs.
         * @param   elem   an object.
         * @return  <code>true</code> if and only if the specified object
         * is the same as a component in this MyOwnVectorReallyItIs, as determined by the
         * <tt>equals</tt> method; <code>false</code> otherwise.
        public boolean contains(Object elem) {
         return indexOf(elem, 0) >= 0;
         * Searches for the first occurence of the given argument, testing
         * for equality using the <code>equals</code> method.
         * @param   elem   an object.
         * @return  the index of the first occurrence of the argument in this
         *          MyOwnVectorReallyItIs, that is, the smallest value <tt>k</tt> such that
         *          <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
         *          returns <code>-1</code> if the object is not found.
         * @see     Object#equals(Object)
        public int indexOf(Object elem) {
         return indexOf(elem, 0);
         * Searches for the first occurence of the given argument, beginning
         * the search at <code>index</code>, and testing for equality using
         * the <code>equals</code> method.
         * @param   elem    an object.
         * @param   index   the non-negative index to start searching from.
         * @return  the index of the first occurrence of the object argument in
         *          this MyOwnVectorReallyItIs at position <code>index</code> or later in the
         *          MyOwnVectorReallyItIs, that is, the smallest value <tt>k</tt> such that
         *          <tt>elem.equals(elementData[k]) && (k >= index)</tt> is
         *          <tt>true</tt>; returns <code>-1</code> if the object is not
         *          found. (Returns <code>-1</code> if <tt>index</tt> >= the
         *          current size of this <tt>MyOwnVectorReallyItIs</tt>.)
         * @exception  IndexOutOfBoundsException  if <tt>index</tt> is negative.
         * @see     Object#equals(Object)
        public synchronized int indexOf(Object elem, int index) {
         if (elem == null) {
             for (int i = index ; i < elementCount ; i++)
              if (elementData==null)
              return i;
         } else {
         for (int i = index ; i < elementCount ; i++)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the index of the last occurrence of the specified object in
    * this MyOwnVectorReallyItIs.
    * @param elem the desired component.
    * @return the index of the last occurrence of the specified object in
    * this MyOwnVectorReallyItIs, that is, the largest value <tt>k</tt> such that
    * <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
    * returns <code>-1</code> if the object is not found.
    public synchronized int lastIndexOf(Object elem) {
         return lastIndexOf(elem, elementCount-1);
    * Searches backwards for the specified object, starting from the
    * specified index, and returns an index to it.
    * @param elem the desired component.
    * @param index the index to start searching from.
    * @return the index of the last occurrence of the specified object in this
    * MyOwnVectorReallyItIs at position less than or equal to <code>index</code> in
    * the MyOwnVectorReallyItIs, that is, the largest value <tt>k</tt> such that
    * <tt>elem.equals(elementData[k]) && (k <= index)</tt> is
    * <tt>true</tt>; <code>-1</code> if the object is not found.
    * (Returns <code>-1</code> if <tt>index</tt> is negative.)
    * @exception IndexOutOfBoundsException if <tt>index</tt> is greater
    * than or equal to the current size of this MyOwnVectorReallyItIs.
    public synchronized int lastIndexOf(Object elem, int index) {
    if (index >= elementCount)
    throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
         if (elem == null) {
         for (int i = index; i >= 0; i--)
              if (elementData[i]==null)
              return i;
         } else {
         for (int i = index; i >= 0; i--)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the component at the specified index.<p>
    * This method is identical in functionality to the get method
    * (which is part of the List interface).
    * @param index an index into this MyOwnVectorReallyItIs.
    * @return the component at the specified index.
    * @exception ArrayIndexOutOfBoundsException if the <tt>index</tt>
    * is negative or not less than the current size of this
    * <tt>MyOwnVectorReallyItIs</tt> object.
    * given.
    * @see     #get(int)
    * @see     List
    public synchronized Object elementAt(int index) {
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
    return elementData[index];
    * Returns the first component (the item at index <tt>0</tt>) of
    * this MyOwnVectorReallyItIs.
    * @return the first component of this MyOwnVectorReallyItIs.
    * @exception NoSuchElementException if this MyOwnVectorReallyItIs has no components.
    public synchronized Object firstElement() {
         if (elementCount == 0) {
         throw new NoSuchElementException();
         return elementData[0];
    * Returns the last component of the MyOwnVectorReallyItIs.
    * @return the last component of the MyOwnVectorReallyItIs, i.e., the component at index
    * <code>size() - 1</code>.
    * @exception NoSuchElementException if this MyOwnVectorReallyItIs is empty.
    public synchronized Object lastElement() {
         if (elementCount == 0) {
         throw new NoSuchElementException();
         return elementData[elementCount - 1];
    * Sets the component at the specified <code>index</code> of this
    * MyOwnVectorReallyItIs to be the specified object. The previous component at that
    * position is discarded.<p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than the current size of the MyOwnVectorReallyItIs. <p>
    * This method is identical in functionality to the set method
    * (which is part of the List interface). Note that the set method reverses
    * the order of the parameters, to more closely match array usage. Note
    * also that the set method returns the old value that was stored at the
    * specified position.
    * @param obj what the component is to be set to.
    * @param index the specified index.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see List
    * @see     #set(int, java.lang.Object)
    public synchronized void setElementAt(Object obj, int index) {
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                  elementCount);
         elementData[index] = obj;
    * Deletes the component at the specified index. Each component in
    * this MyOwnVectorReallyItIs with an index greater or equal to the specified
    * <code>index</code> is shifted downward to have an index one
    * smaller than the value it had previously. The size of this MyOwnVectorReallyItIs
    * is decreased by <tt>1</tt>.<p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than the current size of the MyOwnVectorReallyItIs. <p>
    * This method is identical in functionality to the remove method
    * (which is part of the List interface). Note that the remove method
    * returns the old value that was stored at the specified position.
    * @param index the index of the object to remove.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see     #remove(int)
    * @see     List
    public synchronized void removeElementAt(int index) {
         modCount++;
         if (index >= elementCount) {
         throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                  elementCount);
         else if (index < 0) {
         throw new ArrayIndexOutOfBoundsException(index);
         int j = elementCount - index - 1;
         if (j > 0) {
         System.arraycopy(elementData, index + 1, elementData, index, j);
         elementCount--;
         elementData[elementCount] = null; /* to let gc do its work */
    * Inserts the specified object as a component in this MyOwnVectorReallyItIs at the
    * specified <code>index</code>. Each component in this MyOwnVectorReallyItIs with
    * an index greater or equal to the specified <code>index</code> is
    * shifted upward to have an index one greater than the value it had
    * previously. <p>
    * The index must be a value greater than or equal to <code>0</code>
    * and less than or equal to the current size of the MyOwnVectorReallyItIs. (If the
    * index is equal to the current size of the MyOwnVectorReallyItIs, the new element
    * is appended to the MyOwnVectorReallyItIs.)<p>
    * This method is identical in functionality to the add(Object, int) method
    * (which is part of the List interface). Note that the add method reverses
    * the order of the parameters, to more closely match array usage.
    * @param obj the component to insert.
    * @param index where to insert the new component.
    * @exception ArrayIndexOutOfBoundsException if the index was invalid.
    * @see #size()
    * @see     #add(int, Object)
    * @see     List
    public synchronized void insertElementAt(Object obj, int index) {
         modCount++;
         if (index > elementCount) {
         throw new ArrayIndexOutOfBoundsException(index
                                  + " > " + elementCount);
         ensureCapacityHelper(elementCount + 1);
         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
         elementData[index] = obj;
         elementCount++;
    * Adds the specified component to the end of this MyOwnVectorReallyItIs,
    * increasing its size by one. The capacity of this MyOwnVectorReallyItIs is
    * increased if its size becomes greater than its capacity. <p>
    * This method is identical in functionality to the add(Object) method
    * (which is part of the List interface).
    * @param obj the component to be added.
    * @see     #add(Object)
    * @see     List
    public synchronized void addElement(Object obj) {
         modCount++;
         ensureCapacityHelper(elementCount + 1);
         elementData[elementCount++] = obj;
    * Removes the first (lowest-indexed) occurrence of the argument
    * from this MyOwnVectorReallyItIs. If the object is found in this MyOwnVectorReallyItIs, each
    * component in the MyOwnVectorReallyItIs with an index greater or equal to the
    * object's index is shifted downward to have an index one smaller
    * than the value it had previously.<p>
    * This method is identical in functionality to the remove(Object)
    * method (which is part of the List interface).
    * @param obj the component to be removed.
    * @return <code>true</code> if the argument was a component of this
    * MyOwnVectorReallyItIs; <code>false</code> otherwise.
    * @see     List#remove(Object)
    * @see     List
    public synchronized boolean removeElement(Object obj) {
         modCount++;
         int i = indexOf(obj);
         if (i >= 0) {
         removeElementAt(i);
         return true;
         return false;
    * Removes all components from this MyOwnVectorReallyItIs and sets its size to zero.<p>
    * This method is identical in functionality to the clear method
    * (which is part of the List interface).
    * @see     #clear
    * @see     List
    public synchronized void removeAllElements() {
    modCount++;
         // Let gc do its work
         for (int i = 0; i < elementCount; i++)
         elementData[i] = null;
         elementCount = 0;
    * Returns a clone of this MyOwnVectorReallyItIs. The copy will contain a
    * reference to a clone of the internal data array, not a reference
    * to the original internal data array of this <tt>MyOwnVectorReallyItIs</tt> object.
    * @return a clone of this MyOwnVectorReallyItIs.
    public synchronized Object clone() {
         try {
         MyOwnVectorReallyItIs v = (MyOwnVectorReallyItIs)super.clone();
         v.elementData = new Object[elementCount];
         System.arraycopy(elementData, 0, v.elementData, 0, elementCount);
         v.modCount = 0;
         return v;
         } catch (CloneNotSupportedException e) {
         // this shouldn't happen, since we are Cloneable
         throw new InternalError();
    * Returns an array containing all of the elements in this MyOwnVectorReallyItIs
    * in the correct order.
    * @since 1.2
    public synchronized Object[] toArray() {
         Object[] result = new Object[elementCount];
         System.arraycopy(elementData, 0, result, 0, elementCount);
         return result;
    * Returns an array containing all of the elements in this MyOwnVectorReallyItIs in the
    * correct order; the runtime type of the returned array is that of the
    * specified array. If the MyOwnVectorReallyItIs fits in the specified array, it is
    * returned therein. Otherwise, a new array is allocated with the runtime
    * type of the specified array and the size of this MyOwnVectorReallyItIs.<p>
    * If the MyOwnVectorReallyItIs fits in the specified array with room to spare
    * (i.e., the array has more elements than the MyOwnVectorReallyItIs),
    * the element in the array immediately following the end of the
    * MyOwnVectorReallyItIs is set to null. This is useful in determining the length
    * of the MyOwnVectorReallyItIs <em>only</em> if the caller knows that the MyOwnVectorReallyItIs
    * does not contain any null elements.
    * @param a the array into which the elements of the MyOwnVectorReallyItIs are to
    *          be stored, if it is big enough; otherwise, a new array of the
    *           same runtime type is allocated for this purpose.
    * @return an array containing the elements of the MyOwnVectorReallyItIs.
    * @exception ArrayStoreException the runtime type of a is not a supertype
    * of the runtime type of every element in this MyOwnVectorReallyItIs.
    * @throws NullPointerException if the given array is null.
    * @since 1.2
    public synchronized Object[] toArray(Object a[]) {
    if (a.length < elementCount)
    a = (Object[])java.lang.reflect.Array.newInstance(
    a.getClass().getComponentType(), elementCount);
         System.arraycopy(elementData, 0, a, 0, elementCount);
    if (a.length > elementCount)
    a[elementCount] = null;
    return a;
    // Positional Access Operations
    * Returns the element at the specified position in this MyOwnVectorReallyItIs.
    * @param index index of element to return.
    * @return object at the specified index
    * @exception ArrayIndexOutOfBoundsException index is out of range (index
    *           < 0 || index >= size()).
    * @since 1.2
    public synchronized Object get(int index) {
         if (index >= elementCount)
         throw new ArrayIndexOutOfBoundsException(index);
         return elementData[index];
    * Replaces the element at the specified position in this MyOwnVectorReallyItIs with the
    * specified element.
    * @param index index of element to replace.
    * @param element element to be stored at the specified position.
    * @return the element previously at the specified position.
    * @exception ArrayIndexOutOfBoundsException index out of range
    *          (index < 0 || index >= size()).
    * @since 1.2
    public synchronized Object set(int index, Object element) {
         if (index >= elementCount)
         throw new ArrayIndexOutOfBoundsException(index);
         Object oldValue = elementData[index];
         elementData[index] = element;
         return oldValue;
    * Appends the specified element to the end of this MyOwnVectorReallyItIs.
    * @param o element to be appended to this MyOwnVectorReallyItIs.
    * @return true (as per the general contract of Collection.add).
    * @since 1.2
    public synchronized boolean add(Object o) {
         modCount++;
         ensureCapacityHelper(elementCount + 1);
         elementData[elementCount++] = o;
    return true;
    * Removes the first occurrence of the specified element in this MyOwnVectorReallyItIs
    * If the MyOwnVectorReallyItIs does not contain the element, it is unchanged. More
    * formally, removes the element with the lowest index i such that
    * <code>(o==null ? get(i)==null : o.equals(get(i)))</code> (if such
    * an element exists).
    * @param o element to be removed from this MyOwnVectorReallyItIs, if present.
    * @return true if the MyOwnVectorReallyItIs contained the specified element.
    * @since 1.2
    public boolean remove(Object o) {
    return removeElement(o);
    * Inserts the specified element at the specified position in this MyOwnVectorReallyItIs.
    * Shifts the element currently at that position (if any) and any
    * subsequent elements to the right (adds one to their indices).
    * @param index index at which the specified element is to be inserted.
    * @param

  • HashMap, HashSet and infinite loop

    hi,
    our code ended up in an infinite loop while parsing the entries of a HashMap with this code:
            Iterator it = myHashMap.entrySet().iterator();
            while (it.hasNext()) {
                field = (Map.Entry) it.next();
                // code that access content of "field"
            } as the loop creates some kind of objects, the JVM terminated with a out-of-memory. luckily we got a heap-dump file and that shows:
    - the hash-map has 325 entries
    - the loop was iterated more than 3 million times
    - the iterator "it" has a current and a next field pointing at the same element of the HashMap
    a snapshot of the heap-analysis of the iterator can be seen at
    http://www.sbox.tugraz.at/home/a/archmage/hashset/EntryIterator.html
    maybe the HashMap was accessed concurrently, but then there should be a ConcurrentModificationException.
    we are using
    > java -version
    java version "1.4.2_12"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_12-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_12-b03, mixed mode)for me, this looks like a JVM bug, but i cannot really believe that (and i could not find a bug stating this behaviour).
    is there anything i did not notice during using hashmaps/hashsets/iterators?
    regards, werner

    there should be aConcurrentModificationException.
    Not necessarily. The iterators cannot always detectConcurrentModificationException.
    api-docs of HashMap say:
    A structural modification is any operation that adds
    or deletes one or more mappings
    if the map is structurally modified at any time after
    the iterator is created, in any way except through
    the iterator's own remove or add methods, the
    iterator will throw a
    ConcurrentModificationException.
    for me, that means, the iterator should detect any
    "add" or "delete" operation like map.put(...). am i
    wrong? or are the docs wrong here?Immediately AFTER the paragraph you quoted, it says
    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
    Furthermore, did you READ what I said after that?
    It's FAR MORE LIKELY to be a result of data corruption, rather than multiple simultaneous iterators.

  • Dynamic Array resizing

    I have a class with some data members in it. Data for the objects comes frm a XML file. I have to parse out the xml file and create objects. Before reading the XML file i dunno as to how many objects i need to create. I wud like to know a way where I can dynamically increase the size of the object array as I read through the XMl file.
    Thanks in advance,
    Kris.

    This is the source:
    * @(#)ArrayList.java     1.36 01/12/03
    * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    package java.util;
    * Resizable-array implementation of the <tt>List</tt> interface.  Implements
    * all optional list operations, and permits all elements, including
    * <tt>null</tt>.  In addition to implementing the <tt>List</tt> interface,
    * this class provides methods to manipulate the size of the array that is
    * used internally to store the list.  (This class is roughly equivalent to
    * <tt>Vector</tt>, except that it is unsynchronized.)<p>
    * The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
    * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
    * time.  The <tt>add</tt> operation runs in <i>amortized constant time</i>,
    * that is, adding n elements requires O(n) time.  All of the other operations
    * run in linear time (roughly speaking).  The constant factor is low compared
    * to that for the <tt>LinkedList</tt> implementation.<p>
    * Each <tt>ArrayList</tt> instance has a <i>capacity</i>.  The capacity is
    * the size of the array used to store the elements in the list.  It is always
    * at least as large as the list size.  As elements are added an ArrayList,
    * its capacity grows automatically.  The details of the growth policy are not
    * specified beyond the fact that adding an element has constant amortized
    * time cost.<p>
    * An application can increase the capacity of an <tt>ArrayList</tt> instance
    * before adding a large number of elements using the <tt>ensureCapacity</tt>
    * operation.  This may reduce the amount of incremental reallocation.<p>
    * <strong>Note that this implementation is not synchronized.</strong> If
    * multiple threads access an <tt>ArrayList</tt> instance concurrently, and at
    * least one of the threads modifies the list structurally, it <i>must</i> be
    * synchronized externally.  (A structural modification is any operation that
    * adds or deletes one or more elements, or explicitly resizes the backing
    * array; merely setting the value of an element is not a structural
    * modification.)  This is typically accomplished by synchronizing on some
    * object that naturally encapsulates the list.  If no such object exists, the
    * list should be "wrapped" using the <tt>Collections.synchronizedList</tt>
    * method.  This is best done at creation time, to prevent accidental
    * unsynchronized access to the list:
    * <pre>
    *     List list = Collections.synchronizedList(new ArrayList(...));
    * </pre><p>
    * The iterators returned by this class's <tt>iterator</tt> and
    * <tt>listIterator</tt> methods are <i>fail-fast</i>: if list is structurally
    * modified at any time after the iterator is created, in any way except
    * through the iterator's own remove or add methods, the iterator will throw a
    * ConcurrentModificationException.  Thus, in the face of concurrent
    * modification, the iterator fails quickly and cleanly, rather than risking
    * arbitrary, non-deterministic behavior at an undetermined time in the
    * future.
    * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
    * as it is, generally speaking, impossible to make any hard guarantees in the
    * presence of unsynchronized concurrent modification.  Fail-fast iterators
    * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
    * Therefore, it would be wrong to write a program that depended on this
    * exception for its correctness: <i>the fail-fast behavior of iterators
    * should be used only to detect bugs.</i>
    * @author  Josh Bloch
    * @version 1.36, 12/03/01
    * @see         Collection
    * @see         List
    * @see         LinkedList
    * @see         Vector
    * @see         Collections#synchronizedList(List)
    * @since   1.2
    public class ArrayList extends AbstractList
            implements List, RandomAccess, Cloneable, java.io.Serializable
        private static final long serialVersionUID = 8683452581122892189L;
         * The array buffer into which the elements of the ArrayList are stored.
         * The capacity of the ArrayList is the length of this array buffer.
        private transient Object elementData[];
         * The size of the ArrayList (the number of elements it contains).
         * @serial
        private int size;
         * Constructs an empty list with the specified initial capacity.
         * @param   initialCapacity   the initial capacity of the list.
         * @exception IllegalArgumentException if the specified initial capacity
         *            is negative
        public ArrayList(int initialCapacity) {
         super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
         this.elementData = new Object[initialCapacity];
         * Constructs an empty list with an initial capacity of ten.
        public ArrayList() {
         this(10);
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.  The <tt>ArrayList</tt> instance has an initial capacity of
         * 110% the size of the specified collection.
         * @param c the collection whose elements are to be placed into this list.
         * @throws NullPointerException if the specified collection is null.
        public ArrayList(Collection c) {
            size = c.size();
            // Allow 10% room for growth
            elementData = new Object[
                          (int)Math.min((size*110L)/100,Integer.MAX_VALUE)];
            c.toArray(elementData);
         * Trims the capacity of this <tt>ArrayList</tt> instance to be the
         * list's current size.  An application can use this operation to minimize
         * the storage of an <tt>ArrayList</tt> instance.
        public void trimToSize() {
         modCount++;
         int oldCapacity = elementData.length;
         if (size < oldCapacity) {
             Object oldData[] = elementData;
             elementData = new Object[size];
             System.arraycopy(oldData, 0, elementData, 0, size);
         * Increases the capacity of this <tt>ArrayList</tt> instance, if
         * necessary, to ensure  that it can hold at least the number of elements
         * specified by the minimum capacity argument.
         * @param   minCapacity   the desired minimum capacity.
        public void ensureCapacity(int minCapacity) {
         modCount++;
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
             Object oldData[] = elementData;
             int newCapacity = (oldCapacity * 3)/2 + 1;
                 if (newCapacity < minCapacity)
              newCapacity = minCapacity;
             elementData = new Object[newCapacity];
             System.arraycopy(oldData, 0, elementData, 0, size);
         * Returns the number of elements in this list.
         * @return  the number of elements in this list.
        public int size() {
         return size;
         * Tests if this list has no elements.
         * @return  <tt>true</tt> if this list has no elements;
         *          <tt>false</tt> otherwise.
        public boolean isEmpty() {
         return size == 0;
         * Returns <tt>true</tt> if this list contains the specified element.
         * @param elem element whose presence in this List is to be tested.
         * @return  <code>true</code> if the specified element is present;
         *          <code>false</code> otherwise.
        public boolean contains(Object elem) {
         return indexOf(elem) >= 0;
         * Searches for the first occurence of the given argument, testing
         * for equality using the <tt>equals</tt> method.
         * @param   elem   an object.
         * @return  the index of the first occurrence of the argument in this
         *          list; returns <tt>-1</tt> if the object is not found.
         * @see     Object#equals(Object)
        public int indexOf(Object elem) {
         if (elem == null) {
             for (int i = 0; i < size; i++)
              if (elementData==null)
              return i;
         } else {
         for (int i = 0; i < size; i++)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns the index of the last occurrence of the specified object in
    * this list.
    * @param elem the desired element.
    * @return the index of the last occurrence of the specified object in
    * this list; returns -1 if the object is not found.
    public int lastIndexOf(Object elem) {
         if (elem == null) {
         for (int i = size-1; i >= 0; i--)
              if (elementData[i]==null)
              return i;
         } else {
         for (int i = size-1; i >= 0; i--)
              if (elem.equals(elementData[i]))
              return i;
         return -1;
    * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
    * elements themselves are not copied.)
    * @return a clone of this <tt>ArrayList</tt> instance.
    public Object clone() {
         try {
         ArrayList v = (ArrayList)super.clone();
         v.elementData = new Object[size];
         System.arraycopy(elementData, 0, v.elementData, 0, size);
         v.modCount = 0;
         return v;
         } catch (CloneNotSupportedException e) {
         // this shouldn't happen, since we are Cloneable
         throw new InternalError();
    * Returns an array containing all of the elements in this list
    * in the correct order.
    * @return an array containing all of the elements in this list
    *      in the correct order.
    public Object[] toArray() {
         Object[] result = new Object[size];
         System.arraycopy(elementData, 0, result, 0, size);
         return result;
    * Returns an array containing all of the elements in this list in the
    * correct order; the runtime type of the returned array is that of the
    * specified array. If the list fits in the specified array, it is
    * returned therein. Otherwise, a new array is allocated with the runtime
    * type of the specified array and the size of this list.<p>
    * If the list fits in the specified array with room to spare (i.e., the
    * array has more elements than the list), the element in the array
    * immediately following the end of the collection is set to
    * <tt>null</tt>. This is useful in determining the length of the list
    * <i>only</i> if the caller knows that the list does not contain any
    * <tt>null</tt> elements.
    * @param a the array into which the elements of the list are to
    *          be stored, if it is big enough; otherwise, a new array of the
    *           same runtime type is allocated for this purpose.
    * @return an array containing the elements of the list.
    * @throws ArrayStoreException if the runtime type of a is not a supertype
    * of the runtime type of every element in this list.
    public Object[] toArray(Object a[]) {
    if (a.length < size)
    a = (Object[])java.lang.reflect.Array.newInstance(
    a.getClass().getComponentType(), size);
         System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
    a[size] = null;
    return a;
    // Positional Access Operations
    * Returns the element at the specified position in this list.
    * @param index index of element to return.
    * @return the element at the specified position in this list.
    * @throws IndexOutOfBoundsException if index is out of range <tt>(index
    *           < 0 || index >= size())</tt>.
    public Object get(int index) {
         RangeCheck(index);
         return elementData[index];
    * Replaces the element at the specified position in this list with
    * the specified element.
    * @param index index of element to replace.
    * @param element element to be stored at the specified position.
    * @return the element previously at the specified position.
    * @throws IndexOutOfBoundsException if index out of range
    *          <tt>(index < 0 || index >= size())</tt>.
    public Object set(int index, Object element) {
         RangeCheck(index);
         Object oldValue = elementData[index];
         elementData[index] = element;
         return oldValue;
    * Appends the specified element to the end of this list.
    * @param o element to be appended to this list.
    * @return <tt>true</tt> (as per the general contract of Collection.add).
    public boolean add(Object o) {
         ensureCapacity(size + 1); // Increments modCount!!
         elementData[size++] = o;
         return true;
    * Inserts the specified element at the specified position in this
    * list. Shifts the element currently at that position (if any) and
    * any subsequent elements to the right (adds one to their indices).
    * @param index index at which the specified element is to be inserted.
    * @param element element to be inserted.
    * @throws IndexOutOfBoundsException if index is out of range
    *          <tt>(index < 0 || index > size())</tt>.
    public void add(int index, Object element) {
         if (index > size || index < 0)
         throw new IndexOutOfBoundsException(
              "Index: "+index+", Size: "+size);
         ensureCapacity(size+1); // Increments modCount!!
         System.arraycopy(elementData, index, elementData, index + 1,
                   size - index);
         elementData[index] = element;
         size++;
    * Removes the element at the specified position in this list.
    * Shifts any subsequent elements to the left (subtracts one from their
    * indices).
    * @param index the index of the element to removed.
    * @return the element that was removed from the list.
    * @throws IndexOutOfBoundsException if index out of range <tt>(index
    *           < 0 || index >= size())</tt>.
    public Object remove(int index) {
         RangeCheck(index);
         modCount++;
         Object oldValue = elementData[index];
         int numMoved = size - index - 1;
         if (numMoved > 0)
         System.arraycopy(elementData, index+1, elementData, index,
                   numMoved);
         elementData[--size] = null; // Let gc do its work
         return oldValue;
    * Removes all of the elements from this list. The list will
    * be empty after this call returns.
    public void clear() {
         modCount++;
         // Let gc do its work
         for (int i = 0; i < size; i++)
         elementData[i] = null;
         size = 0;
    * Appends all of the elements in the specified Collection to the end of
    * this list, in the order that they are returned by the
    * specified Collection's Iterator. The behavior of this operation is
    * undefined if the specified Collection is modified while the operation
    * is in progress. (This implies that the behavior of this call is
    * undefined if the specified Collection is this list, and this
    * list is nonempty.)
    * @param c the elements to be inserted into this list.
    * @return <tt>true</tt> if this list changed as a result of the call.
    * @throws IndexOutOfBoundsException if index out of range <tt>(index
    *          < 0 || index > size())</tt>.
    * @throws NullPointerException if the specified collection is null.
    public boolean addAll(Collection c) {
         modCount++;
         int numNew = c.size();
         ensureCapacity(size + numNew);
         Iterator e = c.iterator();
         for (int i=0; i<numNew; i++)
         elementData[size++] = e.next();
         return numNew != 0;
    * Inserts all of the elements in the specified Collection into this
    * list, starting at the specified position. Shifts the element
    * currently at that position (if any) and any subsequent elements to
    * the right (increases their indices). The new elements will appear
    * in the list in the order that they are returned by the
    * specified Collection's iterator.
    * @param index index at which to insert first element
    *          from the specified collection.
    * @param c elements to be inserted into this list.
    * @return <tt>true</tt> if this list changed as a result of the call.
    * @throws IndexOutOfBoundsException if index out of range <tt>(index
    *          < 0 || index > size())</tt>.
    * @throws NullPointerException if the specified Collection is null.
    public boolean addAll(int index, Collection c) {
         if (index > size || index < 0)
         throw new IndexOutOfBoundsException(
              "Index: "+index+", Size: "+size);
         int numNew = c.size();
         ensureCapacity(size + numNew); // Increments modCount!!
         int numMoved = size - index;
         if (numMoved > 0)
         System.arraycopy(elementData, index, elementData, index + numNew,
                   numMoved);
         Iterator e = c.iterator();
         for (int i=0; i<numNew; i++)
         elementData[index++] = e.next();
         size += numNew;
         return numNew != 0;
    * Removes from this List all of the elements whose index is between
    * fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding
    * elements to the left (reduces their index).
    * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
    * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
    * @param fromIndex index of first element to be removed.
    * @param toIndex index after last element to be removed.
    protected void removeRange(int fromIndex, int toIndex) {
         modCount++;
         int numMoved = size - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
    numMoved);
         // Let gc do its work
         int newSize = size - (toIndex-fromIndex);
         while (size != newSize)
         elementData[--size] = null;
    * Check if the given index is in range. If not, throw an appropriate
    * runtime exception.
    private void RangeCheck(int index) {
         if (index >= size || index < 0)
         throw new IndexOutOfBoundsException(
              "Index: "+index+", Size: "+size);
    * Save the state of the <tt>ArrayList</tt> instance to a stream (that
    * is, serialize it).
    * @serialData The length of the array backing the <tt>ArrayList</tt>
    * instance is emitted (int), followed by all of its elements
    * (each an <tt>Object</tt>) in the proper order.
    private synchronized void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException{
         // Write out element count, and any hidden stuff
         s.defaultWriteObject();
    // Write out array length
    s.writeInt(elementData.length);
         // Write out all elements in the proper order.
         for (int i=0; i<size; i++)
    s.writeObject(elementData[i]);
    * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
    * deserialize it).
    private synchronized void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
         // Read in size, and any hidden stuff
         s.defaultReadObject();
    // Read in array length and allocate array
    int arrayLength = s.readInt();
    elementData = new Object[arrayLength];
         // Read in all elements in the proper order.
         for (int i=0; i<size; i++)
    elementData[i] = s.readObject();

  • Problems with M-Audio Fast Track Pro interface & FCP\Logic

    Hi gang,
    I'm using a small M-Audio (Fast Track Pro) external interface to pump sound from the Mac to my speakers (and to input live sound).
    I use it a lot with Logic Audio. No problems.
    With FCP it does odd things on occasion. It suddenly starts to feedback, creating a horrendous din. Then I have to shut down FCP, replug the USB connect, even restart the computer to get it working normally again. And sometimes it just goes dead ... NO sound to the speakers.
    Anybody come across this kind of thing? Any suggestions?
    Ben

    I'm seeing similar things in Logic Express 8.0.1. I didn't experienced this with Logic Express 8.0, though I only used it a handful of times before getting the update.
    Using the Fast Track Pro as an output device seems to work fine, but when I create an audio track and monitor my bass the audio tends to drop out after between 5 to 30 seconds; using inserts on the track seems to make it fail faster. Logic looks like its still monitoring, going by the monitor level, for a little longer, then it gets "stuck". If I record the audio track while its stuck and then play back through built-in audio its a clip of the bass, about a half a second or so long, repeating over and over again making it seem like the Fast Track Pro is, itself, stuck.
    While it's doing all this Logic and the whole OS have a tendency to lock up for up to probably half a minute, sometimes longer.

  • Xperia Z2 driver fails to install.

    I have reciently upgraded to the Z2 phone, my iphone 4 was stolen.  My issue is that my phone won't connect to my pc.
    I have tried a pc at the phone store and it connects, so I know it's not the phone.  I have pc companion on my computer as well as what I'm told is drivers for the phone in a downloaded file.  I've extracte the drivers into the same file but when I search for the files via update driver computer does not find it even though I'm in the correct folder.  I've searched the net for drivers via update driver, computer starts install, then tells me it fails. S1 driver fails (fast boot) D4305 fails (this is another name for the phone not sure if I got the numbers right in this post but I'm close. I've tried rebooting system, unpluging all usb devices, turning off win firewall and antivirus software.  I'm not sure what's blocking the installation of the phone drivers.  I'm pretty sure if I can get the driver's installed on my ccomputer, I can get pc companion to see my phone.  I've got it to connect to my Null, which I assume is my phone, but when I open pc companion It's not connected, probably because of drivers. Tried connecting with phone turned off and on, turning on with up volume key pressed, debugging with developer still can't find thi issue.
    Solved!
    Go to Solution.

    I must admit I am running out ways to get around this. The only other things I have seen block this kind of install are below:
    1. Do not use a USB Hub.
    2. Do you have any MP3 Player software installed for another MTP device?
    3. Do you have any camera software for connecting a camera that may also operate in MTP mode?
    4. The last option would be to test on another PC if possible to rule out the phone/cable as the problem.
    What are your thoughts about this forum? Let us know by doing this short survey.
     - Official Sony Xperia Support Staff
    If you're new to our forums make sure that you have read our Discussion guidelines.
    If you want to get in touch with the local support team for your country please visit our contact page.

  • Message queue like in C++ threads

    Hi,
    I have a question. Does java support threads sending messages to each other like in C++ threads on Windows?
    On Win32, a thread sends message to another thread. This message gets queued up in a message queue, I think, by the OS. The receiver thread can Peek or Get a message from the message queue by doing a such a request.
    Thanks.
    Tri

    That code does not check my "claim". You never directly modify the list in that code. This code does verify my "claim" ... lol
    import java.util.*;
    public class test {
    public static void main(String[] args) {
      List list = new LinkedList();
      list.add(new Object());
      Iterator itr = list.iterator();
      list.add(new Object());
      itr.next();
    }Save compile it.. run it... you'll get ConcurrentModificationException. This isn't a "claim" of mine. Iterators in java are what's called "Fail Fast". This means if you directly modify the underlying collection, then try to use the iterator again, it fails, in java with an Exception.
    In your code you posted above you had a "list.add(p);" that's a direct modification of the list. Once that happens, all iterators are invalid, and will throw an exception if used. With more then one thread this can get kinda weird. That's why Doug Lea has created the util.concurrent package. Check out the read write locks. You can put them over a collection with just a few lines of code. Much faster then fully synchronized collections. This package will appear in java version 1.5 ... check out JSR 166. Links inside the site below.. for more info.
    http://g.cs.oswego.edu

  • Is this a bug in AbstractList Iterator?

    Hello,
    Just wanted to share my findings.
    Seems that for a list containing exactly 2 elements (not 1 or 3) direct (i.e. through list.remove(Object)) removal operation while iterating over will somewhat succeed - will not throw an exeption and will modify the list. As far as I understand this contradicts to the ArrayList JavaDoc:
    The iterators returned by this class's iterator and listIterator methods are fail-fast: if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
    import java.util.ArrayList;
    import java.util.List;
    public class Test {
        public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            list.add("a");
            list.add("b");
            for (String str : list) {
                // intentionally making illegal call
                list.remove(str);
            // the list still has one element, which will be printed out
            for (String str : list) {
                System.out.println("str = " + str);
    }

    Also, in general, this will happen when the second to last item in a list is removed:
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    public class Test35
      public static void main(String[] args)
        List<String> list = new ArrayList<String>();
        int numItems = new Random().nextInt(10) + 5;
        for (int i = 0; i < numItems; i++)
          list.add(String.valueOf("Item #" + i));
        int index = 0;
        for (String s : list)
          if (++index == (list.size() - 1))
            System.out.println("Removing: " + s);
            list.remove(s);
        for (String s : list)
          System.out.println("LIST: " + s);
    }

  • Can you remove elements of hash while enumerating through its keys?

    I am running through each element of a hash table using the keys() method which returns an
    enumeration. Some values I will wish to remove from the hash after I view them while I am still enumerating through its keys. Can you do this without causing an error in the next call enumeration.nextElement()? I know its not a good idea to do this when using an iterator, but I didn't see any documentaion about it regarding enumerations. I could do a test run to check this but I'm not sure that that proves anything, I don't want it to fail ever.

    It's never a good idea to remove or add elements to a collection except by means of the enumerator or iterator that you've got for it. I don't know of any collections library in any language that allows this operation.
    You may be referring to the fact that Iterators are fail-fast, meaning that you get an error if you change the collection while you've got an iterator on it. But this is a good thing, because it alerts you to the fact that you're doing something horribly wrong. With an Enumerator, the code will simply silently fail. :-(

  • What would happen if two concurrent threads try and remove ....

    Hello,
    I have a java test to give back tomorrow and I'm stuck on this question, could you help me please.
    Question: What is the difference between java.util.Vectorand java.util.ArrayList?
    I read everywhere that: The main difference between Vectors and ArrayLists is that Vectors are synchronized so any method that touches the Vector’s content is thread safe, which is not the case for ArrayLists.
    This part is ok.
    Now the second part of the question is:
    What would happen if two concurrent threads try and remove the third object
    of such a collection?
    I don't know what to answer. I could tell that if the vector or arraylist is smaller than 3 il will return an ArrayOutOfBoundException but what happen if they are longer?
    Thank you very much.

    RaptorKiller wrote:
    Hello,
    I have a java test to give back tomorrow and I'm stuck on this question, could you help me please.
    Question: What is the difference between java.util.Vectorand java.util.ArrayList?
    I read everywhere that: The main difference between Vectors and ArrayLists is that Vectors are synchronized so any method that touches the Vector&#146;s content is thread safe ...hm. hmmm...
    I wouldn't say anything about Vector or its methods being thread safe.
    Thing is, [Vector javadoc|http://java.sun.com/javase/6/docs/api/java/util/Vector.html|javadoc] does not state anything like that.
    Rather opposite, javadoc says Vector hates concurrent modification just like any other non-concurrent collection: +"...The Iterators returned by Vector's iterator and listIterator methods are fail-fast: if the Vector is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException... Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification..."+
    This part is ok.I don't think this part is OK. I would stick with wording given in javadoc: +"Unlike the new collection implementations, Vector is synchronized"+ // synchronized does not necessarily mean thread safe, and Vector is the case proving that

  • Unable to remove object from arraylist

    Hello,
    I am trying to remove a few objects from an arraylist and it isnt happeneing in one loop :
                         for(int i=0;i<someList.size();i++){
                             empVo = (EmpVO)colList.get(i);
                             if(empVo.getempName().trim().equalsIgnoreCase("A") ||empVo.getempName().trim().equalsIgnoreCase("B") ||empVo.getempName().trim().equalsIgnoreCase("C") )
                                colList.remove(i);
                         }So, it doesnt remove the object all the time whenever the names of A,B or C appear, so I have to run this loop thrice so it deletes all the data pertaining to these three emp names. Then I thought may be the size of the arraylist is changing and used a temp var for the someList.size, but that doesnt work either. Could you please tell me what is going wrong ?
    Edited by: Sarvananda on Sep 3, 2010 12:10 PM
    Also, the exact test has names A to F. So say A, D and E will be deleted in the first loop, then I have to specifically sysout and see which ones were deleted and then write another loop for B,C and F. Ofcourse at the end A - F are removed. But why two loops for it

    Encephalopathic wrote:
    What if you do this using an iterator to remove items, or if you start from the top of the list and iterate down to the first item?thanks for your reply. I was just looking at the API, and stumbled on this :
    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.Any pointers on where I could look or how I could I move from here ?
    Another question I had was, there is no efficient way to 'move' objects in an arraylist (based on their indexes), isn't it ?
    I always have to remove and add at a certain index.

  • List Concurrent Modification Exception

    The following codes throws the java.util.ConcurrentModificationException
    public static void main(String[] args) {
            List<Integer> list1 = new LinkedList<Integer>();
            ListIterator head = list1.listIterator();
            list1.add(1);
            while(head.hasNext()) {
                System.out.println(head.next());
        }But if I put list1.add(1) before
       ListIterator head = list1.listIterator();, then it runs fine.
    I've googled the exception and get the idea that it is caused by 2 threads accessing the list. Where are the 2 threads?
    Edited by: pinkyDeveloper on Feb 17, 2009 3:00 PM

    nothing to do with threads and everything to do with changing the list after getting the iterator and then iterating with the iterator. Don't do this unless you change the list through the iterator. You might want to read the API on LinkedList which states:
    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
    Edited by: Encephalopathic on Feb 17, 2009 3:13 PM

  • Windows 8.1 Random Slow Startups, "Improper Shutdowns"

    Is this the right subforum? I almost chose frezes/hangs but that's not exactly what it is so...
    Please note that this is a copy/paste from another forum where I sought help. Today is another day from the one referenced in the indented text below. In fact, my system had a clean and safe boot with no speed issues or stalling tonight. The issue is not consistent. Though I was seeking help at another forum, I grew uncomfortable with the steps asked of me (deleting caches and temp files that I'd rather keep and using a third-party defragger; getting standoffish when I requested explanation for why I was being asked to run three or more "cleaner" programs and if defragging was honestly necessary on a mostly-new machine that just got a clean bill of health from HP) and was brushed aside with something of an attitude. Here's the original info on the issue:
    Alright, so, yesterday I noticed that it seemed to take a little longer than usual to start up my laptop (HP Pavilion 17-7042nr with Windows 8.1 64-bit; I've only had it a short amount of time and it was purchased refurbished). I didn't think too much of it, however, since I was starting it at the same time as my seven-year-old Vista machine so by comparison it was still way faster (20+ seconds vs. the old one's 2 minutes). After that, didn't think anything of it...
    Today, however, I started it up on its own and it took far too long compared to how it used to behave. I've noticed this a few times in the past, but always figured Windows was adjusting itself after I'd installed stuff etc. But since there was no need for it to do that this time, I got suspicious and started looking in the event viewer. To my shock, it claimed that the last shutdown was improper and that's why it took forever; it was actually rebooting.
    Trouble is, as far as I knew, no it most certainly did not shut down improperly. I turned it off using the power button, which is set from the power plan to perform a shut down. It did the normal thing: processed the shut down, turned off the screen, and shortly after turned off all system lights except of course the one to indicate that it was plugged in. All seemed well, and was not slower than usual or anything of that sort. So I have no clue why or how it's shutting down improperly.
    But not only that, I tracked it back and several times, as far back as the 19th of February (as well as a couple of times while it was in HP's custody for unrelated maintenance; they apparently did not notice it, either, as it was given a clean bill of health before return) this has been occurring. I've transferred a ton of files, settings, programs, etc. since then so I really didn't want to do a Restore. I did, however, consider it... only to discover that my previous Restore Points before the system was returned by HP have been destroyed. So no chance of going back before the 19th, even if I wanted to (I don't, frankly).
    I have no clue what's going on, but here's the events from the first ever time it happened:
    the logoff/power down is listed as:
    Information    2/19/2015 5:09:11 AM    Kernel-Power    109    (103)
               --  "The kernel power manager has initiated a shutdown transition."
    Information    2/19/2015 5:09:37 AM    Winlogon    7002    (1102)
              -- "User Logoff Notification for Customer Experience Improvement Program"
    after that the next relevant things which involve the boot up:
    Information    2/19/2015 4:42:36 PM    Kernel-Boot    20    None
              -- "The last shutdown's sucess status was true. The last boot's success status was true."
    Error    2/19/2015 4:42:36 PM    Kernel-Boot    29    None
             -- "Windows failed fast startup with error status 0xC00000D4"
    Critical    2/19/2015 4:42:45 PM    Kernel-Power    41    (63)
               --"The system has rebooted without cleanly shutting down first. This error could be caused if the system stopped responding, crashed, or lost power unexpectedly."
    Error    2/19/2015 4:43:14 PM    EventLog    6008    None
             -- "The previous system shutdown at 4:59:42 AM on 2/19/2015 was unexpected."
    Information    2/19/2015 4:43:21 PM    Service Control Manager    7026    None
              --"The following boot-start or system-start driver(s) did not load: dam"
    Those were from the 19 of February, the first time it seems to have happened. The most recent (today) incident is very similar, but not entirely identical.
    The shutdown was:
    Information    3/17/2015 5:12:16 AM    Kernel-Power    109    (103)
             -- "The kernel power manager has initiated a shutdown transition."
    Upon boot the seemingly relevant bits are:
    Information    3/17/2015 4:47:55 PM    Kernel-Boot    20    None
            --"THe last shutdown's success status was true. The last boot's success status was true."
    Error    3/17/2015 4:47:55 PM    Kernel-Boot    29    None
              --"Windows failed fast startup with error status 0xC00000D4."
    Information    3/17/2015 4:47:55 PM    Kernel-General    12    None
                --"The operating system started at system time 2015-03-17T21:47:45.491075600Z." (( What even is up with that time??? ))
    Critical    3/17/2015 4:48:01 PM    Kernel-Power    41    (63)
               --"The system has rebooted without cleanly shutting down first. This error could be caused if the system stopped responding, crashed, or lost power unexpectedly."
    Error    3/17/2015 4:48:24 PM    EventLog    6008    None
              --"THe previous system shutdown at 5:12:03 AM on 3/17/2015 was unexpected."
    I tried googling, to no avail, other than a suggestion that it might be caused by some sort of system file issue. So I ran "sfc /scannow" in an admin-level command prompt and when it was finished it said: "Windows Resource Protection found corrupt files but was unable to fix some of them. Details are included in the CBS.Log windir\Logs\CBS\CBS.log. For example C:\Windows\Logs\CBS\CBS.log. Note that logging is currently not supported in offline servicing scenarios."
    I tracked down the log file and it's rather huge but toward the end I found that "Amd64\CNBJ2530.DPB" was corrupted. Naturally, I investigated... But according to the thread I found it's some kind of printer-related thing, and I've never even connected a printer to this system, much less a Canon brand one as the info I found suggested. In fact, the thread I linked claims that it shouldn't cause any huge issues, so... Probably not the cause of my shutdown issues, which are more pressing. Thus, I can't find anything to indicate what's causing this problem.
    The only thing I can think of that I had done around the 19th was I was trying to get rid of Beats Audio crap on my laptop. (Don't even get me started on that hot mess!) So I'd been swapping between the Windows default audio drivers and versions of the Realtek High Definition Audio from both HP and Realtek. But I never had a corrupt install and I don't recall installing one over the other without uninstalling first, so I don't know if that's an issue. Somehow, I doubt it, especially since this issue isn't consistent. Then again, I don't consistently use the audio on my computer so who knows. (UPDATE: Used audio extensively, but it managed a clean shutdown after.)
    After all lights are off and the system is shut down, unless I've been using it on battery and it needs a charge, I unplug it to conserve energy. I only ever do this if the battery has a full charge, so I don't think that should be an issue even though hybrid shutdown/fast boot is some kind of hibernation-shutdown combination. I'd prefer to keep fast start/hybrid boot enabled because, well, it's convenient... and I'm extremely hesitant to tamper with the UEFI settings etc. But, of course, if that's the only fix then I'd prefer it to possible hard drive damage caused by the supposed/apparent improper shut down.
    Also of note: nothing is overclocked or running outside specifications, as far as I know. My system stats are:
    Windows 8.1 64-bit
    AMD A10-5745M APU
    AMD Radeon HD 8610G
    UEFI BIOS Mode
    Secure Boot Enabled
    Any help would be greatly appreciated!
    Now, for extra details. Things that were done during the process included looking for unnecessary startup items (not the real issue to be honest; when it doesn't forcibly reboot due to "improper shutdown" the startup is extremely speedy) and looking at some logs. In particular, here's the speccy log created for my system: http://speccy.piriform.com/results/vIEkYCelmSRyJjuJyye2jgD
    I also had to run several "cleaner" tools, which included installing CCleaner, though I chose some files I wished to keep / thought may be important to not just delete willy-nilly. I don't like to randomly delete things that could come back and bite me in the rear, after all. And I'm honestly confused how any of that would related to Windows having inconsistent and seemingly random "improper shutdown" issues which cause it to reboot instead of using fast boot. (I'm not saying it's impossible, I'm saying that I don't logically see how it'd make a difference and when I attempted to ask I was brushed aside.)
    Like I said, by all appearances it seems to shut down properly. It has also never crashed on me. Nor has it ever blue screened or randomly rebooted.  This is very much a silent, behind-the-scenes issue.

    Hi @Alley_Kitten , 
    Thank you for visiting the HP Support Forums and Welcome. I have looked into your issue about your HP Pavilion 17 f042nr Notebook and issues with performance issues or improper shutdowns. 
    I checked the specs of your system and with what you have posted here you have the incorrect Amd driver installed.  Your's as per your product page is a AMD Radeon HD 8610G . I would go to the device manager and remove all graphic driver, check the box for the driver as well.
    Here is a document on recovery options that are available. I do use the refresh your pc method with Windows 8. Please read all the documentation before starting the operation.
    Hope this helps you out.
    Thanks.
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos, Thumbs Up" on the bottom to say “Thanks” for helping!

Maybe you are looking for

  • Users on same mac using the same itunes library

    How can i allow another user on my mac access my library on their itunes, without copying all my tunes to shared folder, i.e, can change privileges to allow them access? cheers

  • Sapscript get spool when the delivery printed

    Hi all, i need such a thing: the user gets print out from printer and also wee need to send the same delivery items via email. We want to send the email while printing occurs. here i i need to get the spool id of sapscript and this convert this spool

  • How to create TableViewer in eclipse (Eclipse Plugin)

    Hi All, How to create a TableViewer using Eclipse plug-in development. here i want to create a Eclipse plug-in to show data from database using tableviewer, from that i have to perform CRUD operations. can any one please give me some overview of thes

  • Can I connect 9i server with 10g client

    Can I connect to 9i database, with 10g client installation. Thanks, Satish.

  • Help with internet security

    Well my family have just clean out our computer due to a virus and it had erased out Verizon anti virus. I tried to redownload it and it wants out user ID and i had put it in the same way and it says it doesn't match like can someone tell me if the a