// Returns just -1 or 1 on inequality; doing math might overflow.
return value > i.value?1:-1;
}
+
+ public static int bitCount(int x) {
+ // Successively collapse alternating bit groups into a sum.
+ x = ((x >> 1) & 0x55555555) + (x & 0x55555555);
+ x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
+ x = ((x >> 4) & 0x0f0f0f0f) + (x & 0x0f0f0f0f);
+ x = ((x >> 8) & 0x00ff00ff) + (x & 0x00ff00ff);
+ return ((x >> 16) & 0x0000ffff) + (x & 0x0000ffff);
+ }
+
+ public static int numberOfLeadingZeros(int value) {
+ value |= value >>> 1;
+ value |= value >>> 2;
+ value |= value >>> 4;
+ value |= value >>> 8;
+ value |= value >>> 16;
+ return bitCount(~value);
+ }
}
--- /dev/null
+class HashMapIterator implements Iterator {
+ HashMap map;
+ int type;
+ int bin;
+ HashEntry he;
+
+ public HashMapIterator(HashMap map, int type) {
+ this.map=map;
+ this.type=type;
+ this.bin=0;
+ this.he=null;
+ }
+
+ public boolean hasNext() {
+ if (he!=null&&he.next!=null)
+ return true;
+ int i=bin;
+ while((i<map.table.length)&&map.table[i]==null)
+ i++;
+ return (i<map.table.length);
+ }
+
+ public Object next() {
+ if (he!=null&&he.next!=null) {
+ he=he.next;
+ Object o;
+ if (type==0)
+ o=he.key;
+ else
+ o=he.value;
+ return o;
+ }
+ while((bin<map.table.length)&&
+ (map.table[bin]==null))
+ bin++;
+ if (bin<map.table.length) {
+ he=map.table[bin++];
+ Object o;
+ if (type==0)
+ o=he.key;
+ else
+ o=he.value;
+ return o;
+ } else System.error();
+ }
+
+ public void remove() {
+ System.out.println("HashMapIterator.remove() not implemented.");
+ System.exit(-1);
+ }
+}
* @since 1.2
* @status updated to 1.4
*/
-public interface Set//<E> extends Collection<E>
+public interface Set extends Collection
{
/**
* Adds the specified element to the set if it is not already present
*
* @return a set iterator
*/
- //Iterator<E> iterator();
+ Iterator/*<E>*/ iterator();
/**
* Removes the specified element from this set (optional operation). If
public static native long currentTimeMillis();
+ public static native long nanoTime();
+
public static native long microTimes();
public static native long getticks();
public class Thread implements Runnable {
private boolean finished;
Runnable target;
+ private boolean daemon;
public Thread(){
finished = false;
public final boolean isAlive() {
return !this.finished;
}
+
+ public native ThreadLocalMap getThreadLocals();
+
+ public final synchronized void setDaemon(boolean daemon) {
+ /*if (vmThread != null)
+ throw new IllegalThreadStateException();
+ checkAccess();*/
+ this.daemon = daemon;
+ }
}
--- /dev/null
+/* AbstractCollection.java -- Abstract implementation of most of Collection
+ Copyright (C) 1998, 2000, 2001, 2004, 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.util;
+
+import gnu.java.lang.CPStringBuilder;
+
+import java.lang.reflect.Array;
+
+/**
+ * A basic implementation of most of the methods in the Collection interface to
+ * make it easier to create a collection. To create an unmodifiable Collection,
+ * just subclass AbstractCollection and provide implementations of the
+ * iterator() and size() methods. The Iterator returned by iterator() need only
+ * provide implementations of hasNext() and next() (that is, it may throw an
+ * UnsupportedOperationException if remove() is called). To create a modifiable
+ * Collection, you must in addition provide an implementation of the
+ * add(Object) method and the Iterator returned by iterator() must provide an
+ * implementation of remove(). Other methods should be overridden if the
+ * backing data structure allows for a more efficient implementation. The
+ * precise implementation used by AbstractCollection is documented, so that
+ * subclasses can tell which methods could be implemented more efficiently.
+ * <p>
+ *
+ * The programmer should provide a no-argument constructor, and one that
+ * accepts another Collection, as recommended by the Collection interface.
+ * Unfortunately, there is no way to enforce this in Java.
+ *
+ * @author Original author unknown
+ * @author Bryce McKinlay
+ * @author Eric Blake (ebb9@email.byu.edu)
+ * @author Tom Tromey (tromey@redhat.com)
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @see Collection
+ * @see AbstractSet
+ * @see AbstractList
+ * @since 1.2
+ * @status updated to 1.4
+ */
+public abstract class AbstractCollection//<E>
+ implements Collection/*<E>*/, Iterable/*<E>*/
+{
+ /**
+ * The main constructor, for use by subclasses.
+ */
+ protected AbstractCollection()
+ {
+ }
+
+ /**
+ * Return an Iterator over this collection. The iterator must provide the
+ * hasNext and next methods and should in addition provide remove if the
+ * collection is modifiable.
+ *
+ * @return an iterator
+ */
+ public abstract Iterator/*<E>*/ iterator();
+
+ /**
+ * Return the number of elements in this collection. If there are more than
+ * Integer.MAX_VALUE elements, return Integer.MAX_VALUE.
+ *
+ * @return the size
+ */
+ public abstract int size();
+
+ /**
+ * Add an object to the collection (optional operation). This implementation
+ * always throws an UnsupportedOperationException - it should be
+ * overridden if the collection is to be modifiable. If the collection
+ * does not accept duplicates, simply return false. Collections may specify
+ * limitations on what may be added.
+ *
+ * @param o the object to add
+ * @return true if the add operation caused the Collection to change
+ * @throws UnsupportedOperationException if the add operation is not
+ * supported on this collection
+ * @throws NullPointerException if the collection does not support null
+ * @throws ClassCastException if the object is of the wrong type
+ * @throws IllegalArgumentException if some aspect of the object prevents
+ * it from being added
+ */
+ public boolean add(Object/*E*/ o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Add all the elements of a given collection to this collection (optional
+ * operation). This implementation obtains an Iterator over the given
+ * collection and iterates over it, adding each element with the
+ * add(Object) method (thus this method will fail with an
+ * UnsupportedOperationException if the add method does). The behavior is
+ * unspecified if the specified collection is modified during the iteration,
+ * including the special case of trying addAll(this) on a non-empty
+ * collection.
+ *
+ * @param c the collection to add the elements of to this collection
+ * @return true if the add operation caused the Collection to change
+ * @throws UnsupportedOperationException if the add operation is not
+ * supported on this collection
+ * @throws NullPointerException if the specified collection is null
+ * @throws ClassCastException if the type of any element in c is
+ * not a valid type for addition.
+ * @throws IllegalArgumentException if some aspect of any element
+ * in c prevents it being added.
+ * @throws NullPointerException if any element in c is null and this
+ * collection doesn't allow null values.
+ * @see #add(Object)
+ */
+ public boolean addAll(Collection/*<? extends E>*/ c)
+ {
+ Iterator/*<? extends E>*/ itr = c.iterator();
+ boolean modified = false;
+ int pos = c.size();
+ while (--pos >= 0)
+ modified |= add(itr.next());
+ return modified;
+ }
+
+ /**
+ * Remove all elements from the collection (optional operation). This
+ * implementation obtains an iterator over the collection and calls next
+ * and remove on it repeatedly (thus this method will fail with an
+ * UnsupportedOperationException if the Iterator's remove method does)
+ * until there are no more elements to remove.
+ * Many implementations will have a faster way of doing this.
+ *
+ * @throws UnsupportedOperationException if the Iterator returned by
+ * iterator does not provide an implementation of remove
+ * @see Iterator#remove()
+ */
+ public void clear()
+ {
+ Iterator/*<E>*/ itr = iterator();
+ int pos = size();
+ while (--pos >= 0)
+ {
+ itr.next();
+ itr.remove();
+ }
+ }
+
+ /**
+ * Test whether this collection contains a given object. That is, if the
+ * collection has an element e such that (o == null ? e == null :
+ * o.equals(e)). This implementation obtains an iterator over the collection
+ * and iterates over it, testing each element for equality with the given
+ * object. If it is equal, true is returned. Otherwise false is returned when
+ * the end of the collection is reached.
+ *
+ * @param o the object to remove from this collection
+ * @return true if this collection contains an object equal to o
+ */
+ public boolean contains(Object o)
+ {
+ Iterator/*<E>*/ itr = iterator();
+ int pos = size();
+ while (--pos >= 0)
+ if (equals(o, itr.next()))
+ return true;
+ return false;
+ }
+
+ /**
+ * Tests whether this collection contains all the elements in a given
+ * collection. This implementation iterates over the given collection,
+ * testing whether each element is contained in this collection. If any one
+ * is not, false is returned. Otherwise true is returned.
+ *
+ * @param c the collection to test against
+ * @return true if this collection contains all the elements in the given
+ * collection
+ * @throws NullPointerException if the given collection is null
+ * @see #contains(Object)
+ */
+ public boolean containsAll(Collection/*<?>*/ c)
+ {
+ Iterator/*<?>*/ itr = c.iterator();
+ int pos = c.size();
+ while (--pos >= 0)
+ if (!contains(itr.next()))
+ return false;
+ return true;
+ }
+
+ /**
+ * Test whether this collection is empty. This implementation returns
+ * size() == 0.
+ *
+ * @return true if this collection is empty.
+ * @see #size()
+ */
+ public boolean isEmpty()
+ {
+ return size() == 0;
+ }
+
+ /**
+ * Remove a single instance of an object from this collection (optional
+ * operation). That is, remove one element e such that
+ * <code>(o == null ? e == null : o.equals(e))</code>, if such an element
+ * exists. This implementation obtains an iterator over the collection
+ * and iterates over it, testing each element for equality with the given
+ * object. If it is equal, it is removed by the iterator's remove method
+ * (thus this method will fail with an UnsupportedOperationException if
+ * the Iterator's remove method does). After the first element has been
+ * removed, true is returned; if the end of the collection is reached, false
+ * is returned.
+ *
+ * @param o the object to remove from this collection
+ * @return true if the remove operation caused the Collection to change, or
+ * equivalently if the collection did contain o.
+ * @throws UnsupportedOperationException if this collection's Iterator
+ * does not support the remove method
+ * @see Iterator#remove()
+ */
+ public boolean remove(Object o)
+ {
+ Iterator/*<E>*/ itr = iterator();
+ int pos = size();
+ while (--pos >= 0)
+ if (equals(o, itr.next()))
+ {
+ itr.remove();
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Remove from this collection all its elements that are contained in a given
+ * collection (optional operation). This implementation iterates over this
+ * collection, and for each element tests if it is contained in the given
+ * collection. If so, it is removed by the Iterator's remove method (thus
+ * this method will fail with an UnsupportedOperationException if the
+ * Iterator's remove method does).
+ *
+ * @param c the collection to remove the elements of
+ * @return true if the remove operation caused the Collection to change
+ * @throws UnsupportedOperationException if this collection's Iterator
+ * does not support the remove method
+ * @throws NullPointerException if the collection, c, is null.
+ * @see Iterator#remove()
+ */
+ public boolean removeAll(Collection/*<?>*/ c)
+ {
+ return removeAllInternal(c);
+ }
+
+ /**
+ * Remove from this collection all its elements that are contained in a given
+ * collection (optional operation). This implementation iterates over this
+ * collection, and for each element tests if it is contained in the given
+ * collection. If so, it is removed by the Iterator's remove method (thus
+ * this method will fail with an UnsupportedOperationException if the
+ * Iterator's remove method does). This method is necessary for ArrayList,
+ * which cannot publicly override removeAll but can optimize this call.
+ *
+ * @param c the collection to remove the elements of
+ * @return true if the remove operation caused the Collection to change
+ * @throws UnsupportedOperationException if this collection's Iterator
+ * does not support the remove method
+ * @throws NullPointerException if the collection, c, is null.
+ * @see Iterator#remove()
+ */
+ // Package visible for use throughout java.util.
+ boolean removeAllInternal(Collection/*<?>*/ c)
+ {
+ Iterator/*<E>*/ itr = iterator();
+ boolean modified = false;
+ int pos = size();
+ while (--pos >= 0)
+ if (c.contains(itr.next()))
+ {
+ itr.remove();
+ modified = true;
+ }
+ return modified;
+ }
+
+ /**
+ * Remove from this collection all its elements that are not contained in a
+ * given collection (optional operation). This implementation iterates over
+ * this collection, and for each element tests if it is contained in the
+ * given collection. If not, it is removed by the Iterator's remove method
+ * (thus this method will fail with an UnsupportedOperationException if
+ * the Iterator's remove method does).
+ *
+ * @param c the collection to retain the elements of
+ * @return true if the remove operation caused the Collection to change
+ * @throws UnsupportedOperationException if this collection's Iterator
+ * does not support the remove method
+ * @throws NullPointerException if the collection, c, is null.
+ * @see Iterator#remove()
+ */
+ public boolean retainAll(Collection/*<?>*/ c)
+ {
+ return retainAllInternal(c);
+ }
+
+ /**
+ * Remove from this collection all its elements that are not contained in a
+ * given collection (optional operation). This implementation iterates over
+ * this collection, and for each element tests if it is contained in the
+ * given collection. If not, it is removed by the Iterator's remove method
+ * (thus this method will fail with an UnsupportedOperationException if
+ * the Iterator's remove method does). This method is necessary for
+ * ArrayList, which cannot publicly override retainAll but can optimize
+ * this call.
+ *
+ * @param c the collection to retain the elements of
+ * @return true if the remove operation caused the Collection to change
+ * @throws UnsupportedOperationException if this collection's Iterator
+ * does not support the remove method
+ * @throws NullPointerException if the collection, c, is null.
+ * @see Iterator#remove()
+ */
+ // Package visible for use throughout java.util.
+ boolean retainAllInternal(Collection/*<?>*/ c)
+ {
+ Iterator/*<E>*/ itr = iterator();
+ boolean modified = false;
+ int pos = size();
+ while (--pos >= 0)
+ if (!c.contains(itr.next()))
+ {
+ itr.remove();
+ modified = true;
+ }
+ return modified;
+ }
+
+ /**
+ * Return an array containing the elements of this collection. This
+ * implementation creates an Object array of size size() and then iterates
+ * over the collection, setting each element of the array from the value
+ * returned by the iterator. The returned array is safe, and is not backed
+ * by the collection.
+ *
+ * @return an array containing the elements of this collection
+ */
+ public Object[] toArray()
+ {
+ Iterator/*<E>*/ itr = iterator();
+ int size = size();
+ Object[] a = new Object[size];
+ for (int pos = 0; pos < size; pos++)
+ a[pos] = itr.next();
+ return a;
+ }
+
+ /**
+ * Copy the collection into a given array if it will fit, or into a
+ * dynamically created array of the same run-time type as the given array if
+ * not. If there is space remaining in the array, the first element after the
+ * end of the collection is set to null (this is only useful if the
+ * collection is known to contain no null elements, however). This
+ * implementation first tests whether the given array is large enough to hold
+ * all the elements of the collection. If not, the reflection API is used to
+ * allocate a new array of the same run-time type. Next an iterator is
+ * obtained over the collection and the elements are placed in the array as
+ * they are returned by the iterator. Finally the first spare element, if
+ * any, of the array is set to null, and the created array is returned.
+ * The returned array is safe; it is not backed by the collection. Note that
+ * null may not mark the last element, if the collection allows null
+ * elements.
+ *
+ * @param a the array to copy into, or of the correct run-time type
+ * @return the array that was produced
+ * @throws NullPointerException if the given array is null
+ * @throws ArrayStoreException if the type of the array precludes holding
+ * one of the elements of the Collection
+ */
+ public /*<T> T*/Object[] toArray(Object/*T*/[] a)
+ {
+ int size = size();
+ if (a.length < size)
+ a = /*(T[]) Array.newInstance(a.getClass().getComponentType(),
+ size)*/new Object[size];
+ else if (a.length > size)
+ a[size] = null;
+
+ Iterator/*<E>*/ itr = iterator();
+ for (int pos = 0; pos < size; pos++)
+ a[pos] = /*(T)*/ (itr.next());
+ return a;
+ }
+
+ /**
+ * Creates a String representation of the Collection. The string returned is
+ * of the form "[a, b, ...]" where a and b etc are the results of calling
+ * toString on the elements of the collection. This implementation obtains an
+ * Iterator over the Collection and adds each element to a StringBuffer as it
+ * is returned by the iterator. "<this>" is inserted when the collection
+ * contains itself (only works for direct containment, not for collections
+ * inside collections).
+ *
+ * @return a String representation of the Collection
+ */
+ /*public String toString()
+ {
+ Iterator itr = iterator();
+ CPStringBuilder r = new CPStringBuilder("[");
+ boolean hasNext = itr.hasNext();
+ while (hasNext)
+ {
+ Object o = itr.next();
+ if (o == this)
+ r.append("<this>");
+ else
+ r.append(o);
+ hasNext = itr.hasNext();
+ if (hasNext)
+ r.append(", ");
+ }
+ r.append("]");
+ return r.toString();
+ }*/
+
+ /**
+ * Compare two objects according to Collection semantics.
+ *
+ * @param o1 the first object
+ * @param o2 the second object
+ * @return o1 == null ? o2 == null : o1.equals(o2)
+ */
+ // Package visible for use throughout java.util.
+ // It may be inlined since it is final.
+ static final boolean equals(Object o1, Object o2)
+ {
+ return o1 == null ? o2 == null : o1.equals(o2);
+ }
+
+ /**
+ * Hash an object according to Collection semantics.
+ *
+ * @param o the object to hash
+ * @return o1 == null ? 0 : o1.hashCode()
+ */
+ // Package visible for use throughout java.util.
+ // It may be inlined since it is final.
+ static final int hashCode(Object o)
+ {
+ return o == null ? 0 : o.hashCode();
+ }
+}
--- /dev/null
+/*
+ * Written by Josh Bloch of Google Inc. and released to the public domain,
+ * as explained at http://creativecommons.org/licenses/publicdomain.
+ */
+
+package java.util;
+import java.io.*;
+
+/**
+ * Resizable-array implementation of the {@link Deque} interface. Array
+ * deques have no capacity restrictions; they grow as necessary to support
+ * usage. They are not thread-safe; in the absence of external
+ * synchronization, they do not support concurrent access by multiple threads.
+ * Null elements are prohibited. This class is likely to be faster than
+ * {@link Stack} when used as a stack, and faster than {@link LinkedList}
+ * when used as a queue.
+ *
+ * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
+ * Exceptions include {@link #remove(Object) remove}, {@link
+ * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
+ * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
+ * iterator.remove()}, and the bulk operations, all of which run in linear
+ * time.
+ *
+ * <p>The iterators returned by this class's <tt>iterator</tt> method are
+ * <i>fail-fast</i>: If the deque is modified at any time after the iterator
+ * is created, in any way except through the iterator's own <tt>remove</tt>
+ * method, the iterator will generally throw a {@link
+ * 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>
+ *
+ * <p>This class and its iterator implement all of the
+ * <em>optional</em> methods of the {@link Collection} and {@link
+ * Iterator} interfaces.
+ *
+ * <p>This class is a member of the
+ * <a href="{@docRoot}/../technotes/guides/collections/index.html">
+ * Java Collections Framework</a>.
+ *
+ * @author Josh Bloch and Doug Lea
+ * @since 1.6
+ * @param <E> the type of elements held in this collection
+ */
+//public class ArrayDeque<E> extends AbstractCollection<E>
+public class ArrayDeque extends AbstractCollection
+ implements Deque/*<E>*/, Cloneable, Serializable
+{
+ /**
+ * The array in which the elements of the deque are stored.
+ * The capacity of the deque is the length of this array, which is
+ * always a power of two. The array is never allowed to become
+ * full, except transiently within an addX method where it is
+ * resized (see doubleCapacity) immediately upon becoming full,
+ * thus avoiding head and tail wrapping around to equal each
+ * other. We also guarantee that all array cells not holding
+ * deque elements are always null.
+ */
+ private transient Object/*E*/[] elements;
+
+ /**
+ * The index of the element at the head of the deque (which is the
+ * element that would be removed by remove() or pop()); or an
+ * arbitrary number equal to tail if the deque is empty.
+ */
+ private transient int head;
+
+ /**
+ * The index at which the next element would be added to the tail
+ * of the deque (via addLast(E), add(E), or push(E)).
+ */
+ private transient int tail;
+
+ /**
+ * The minimum capacity that we'll use for a newly created deque.
+ * Must be a power of 2.
+ */
+ private static final int MIN_INITIAL_CAPACITY = 8;
+
+ // ****** Array allocation and resizing utilities ******
+
+ /**
+ * Allocate empty array to hold the given number of elements.
+ *
+ * @param numElements the number of elements to hold
+ */
+ private void allocateElements(int numElements) {
+ int initialCapacity = MIN_INITIAL_CAPACITY;
+ // Find the best power of two to hold elements.
+ // Tests "<=" because arrays aren't kept full.
+ if (numElements >= initialCapacity) {
+ initialCapacity = numElements;
+ initialCapacity |= (initialCapacity >>> 1);
+ initialCapacity |= (initialCapacity >>> 2);
+ initialCapacity |= (initialCapacity >>> 4);
+ initialCapacity |= (initialCapacity >>> 8);
+ initialCapacity |= (initialCapacity >>> 16);
+ initialCapacity++;
+
+ if (initialCapacity < 0) // Too many elements, must back off
+ initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
+ }
+ elements = /*(E[])*/ new Object[initialCapacity];
+ }
+
+ /**
+ * Double the capacity of this deque. Call only when full, i.e.,
+ * when head and tail have wrapped around to become equal.
+ */
+ private void doubleCapacity() {
+ //assert head == tail;
+ int p = head;
+ int n = elements.length;
+ int r = n - p; // number of elements to the right of p
+ int newCapacity = n << 1;
+ if (newCapacity < 0)
+ throw new IllegalStateException("Sorry, deque too big");
+ Object[] a = new Object[newCapacity];
+ System.arraycopy(elements, p, a, 0, r);
+ System.arraycopy(elements, 0, a, r, p);
+ elements = /*(E[])*/a;
+ head = 0;
+ tail = n;
+ }
+
+ /**
+ * Copies the elements from our element array into the specified array,
+ * in order (from first to last element in the deque). It is assumed
+ * that the array is large enough to hold all elements in the deque.
+ *
+ * @return its argument
+ */
+ private /*<T> T*/Object[] copyElements(Object/*T*/[] a) {
+ if (head < tail) {
+ System.arraycopy(elements, head, a, 0, size());
+ } else if (head > tail) {
+ int headPortionLen = elements.length - head;
+ System.arraycopy(elements, head, a, 0, headPortionLen);
+ System.arraycopy(elements, 0, a, headPortionLen, tail);
+ }
+ return a;
+ }
+
+ /**
+ * Constructs an empty array deque with an initial capacity
+ * sufficient to hold 16 elements.
+ */
+ public ArrayDeque() {
+ elements = (Objecxt/*E*/[]) new Object[16];
+ }
+
+ /**
+ * Constructs an empty array deque with an initial capacity
+ * sufficient to hold the specified number of elements.
+ *
+ * @param numElements lower bound on initial capacity of the deque
+ */
+ public ArrayDeque(int numElements) {
+ allocateElements(numElements);
+ }
+
+ /**
+ * Constructs a deque containing the elements of the specified
+ * collection, in the order they are returned by the collection's
+ * iterator. (The first element returned by the collection's
+ * iterator becomes the first element, or <i>front</i> of the
+ * deque.)
+ *
+ * @param c the collection whose elements are to be placed into the deque
+ * @throws NullPointerException if the specified collection is null
+ */
+ public ArrayDeque(Collection/*<? extends E>*/ c) {
+ allocateElements(c.size());
+ addAll(c);
+ }
+
+ // The main insertion and extraction methods are addFirst,
+ // addLast, pollFirst, pollLast. The other methods are defined in
+ // terms of these.
+
+ /**
+ * Inserts the specified element at the front of this deque.
+ *
+ * @param e the element to add
+ * @throws NullPointerException if the specified element is null
+ */
+ public void addFirst(Object/*E*/ e) {
+ if (e == null)
+ throw new NullPointerException();
+ elements[head = (head - 1) & (elements.length - 1)] = e;
+ if (head == tail)
+ doubleCapacity();
+ }
+
+ /**
+ * Inserts the specified element at the end of this deque.
+ *
+ * <p>This method is equivalent to {@link #add}.
+ *
+ * @param e the element to add
+ * @throws NullPointerException if the specified element is null
+ */
+ public void addLast(Object/*E*/ e) {
+ if (e == null)
+ throw new NullPointerException();
+ elements[tail] = e;
+ if ( (tail = (tail + 1) & (elements.length - 1)) == head)
+ doubleCapacity();
+ }
+
+ /**
+ * Inserts the specified element at the front of this deque.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
+ * @throws NullPointerException if the specified element is null
+ */
+ public boolean offerFirst(Object/*E*/ e) {
+ addFirst(e);
+ return true;
+ }
+
+ /**
+ * Inserts the specified element at the end of this deque.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
+ * @throws NullPointerException if the specified element is null
+ */
+ public boolean offerLast(Object/*E*/ e) {
+ addLast(e);
+ return true;
+ }
+
+ /**
+ * @throws NoSuchElementException {@inheritDoc}
+ */
+ public Object/*E*/ removeFirst() {
+ Object/*E*/ x = pollFirst();
+ if (x == null)
+ throw new NoSuchElementException();
+ return x;
+ }
+
+ /**
+ * @throws NoSuchElementException {@inheritDoc}
+ */
+ public Object/*E*/ removeLast() {
+ Object/*E*/ x = pollLast();
+ if (x == null)
+ throw new NoSuchElementException();
+ return x;
+ }
+
+ public Object/*E*/ pollFirst() {
+ int h = head;
+ Object/*E*/ result = elements[h]; // Element is null if deque empty
+ if (result == null)
+ return null;
+ elements[h] = null; // Must null out slot
+ head = (h + 1) & (elements.length - 1);
+ return result;
+ }
+
+ public Object/*E*/ pollLast() {
+ int t = (tail - 1) & (elements.length - 1);
+ Object/*E*/ result = elements[t];
+ if (result == null)
+ return null;
+ elements[t] = null;
+ tail = t;
+ return result;
+ }
+
+ /**
+ * @throws NoSuchElementException {@inheritDoc}
+ */
+ public Object/*E*/ getFirst() {
+ Object/*E*/ x = elements[head];
+ if (x == null)
+ throw new NoSuchElementException();
+ return x;
+ }
+
+ /**
+ * @throws NoSuchElementException {@inheritDoc}
+ */
+ public Object/*E*/ getLast() {
+ Object/*E*/ x = elements[(tail - 1) & (elements.length - 1)];
+ if (x == null)
+ throw new NoSuchElementException();
+ return x;
+ }
+
+ public Object/*E*/ peekFirst() {
+ return elements[head]; // elements[head] is null if deque empty
+ }
+
+ public Object/*E*/ peekLast() {
+ return elements[(tail - 1) & (elements.length - 1)];
+ }
+
+ /**
+ * Removes the first occurrence of the specified element in this
+ * deque (when traversing the deque from head to tail).
+ * If the deque does not contain the element, it is unchanged.
+ * More formally, removes the first element <tt>e</tt> such that
+ * <tt>o.equals(e)</tt> (if such an element exists).
+ * Returns <tt>true</tt> if this deque contained the specified element
+ * (or equivalently, if this deque changed as a result of the call).
+ *
+ * @param o element to be removed from this deque, if present
+ * @return <tt>true</tt> if the deque contained the specified element
+ */
+ public boolean removeFirstOccurrence(Object o) {
+ if (o == null)
+ return false;
+ int mask = elements.length - 1;
+ int i = head;
+ Object/*E*/ x;
+ while ( (x = elements[i]) != null) {
+ if (o.equals(x)) {
+ delete(i);
+ return true;
+ }
+ i = (i + 1) & mask;
+ }
+ return false;
+ }
+
+ /**
+ * Removes the last occurrence of the specified element in this
+ * deque (when traversing the deque from head to tail).
+ * If the deque does not contain the element, it is unchanged.
+ * More formally, removes the last element <tt>e</tt> such that
+ * <tt>o.equals(e)</tt> (if such an element exists).
+ * Returns <tt>true</tt> if this deque contained the specified element
+ * (or equivalently, if this deque changed as a result of the call).
+ *
+ * @param o element to be removed from this deque, if present
+ * @return <tt>true</tt> if the deque contained the specified element
+ */
+ public boolean removeLastOccurrence(Object o) {
+ if (o == null)
+ return false;
+ int mask = elements.length - 1;
+ int i = (tail - 1) & mask;
+ Object/*E*/ x;
+ while ( (x = elements[i]) != null) {
+ if (o.equals(x)) {
+ delete(i);
+ return true;
+ }
+ i = (i - 1) & mask;
+ }
+ return false;
+ }
+
+ // *** Queue methods ***
+
+ /**
+ * Inserts the specified element at the end of this deque.
+ *
+ * <p>This method is equivalent to {@link #addLast}.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> (as specified by {@link Collection#add})
+ * @throws NullPointerException if the specified element is null
+ */
+ public boolean add(Object/*E*/ e) {
+ addLast(e);
+ return true;
+ }
+
+ /**
+ * Inserts the specified element at the end of this deque.
+ *
+ * <p>This method is equivalent to {@link #offerLast}.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> (as specified by {@link Queue#offer})
+ * @throws NullPointerException if the specified element is null
+ */
+ public boolean offer(Object/*E*/ e) {
+ return offerLast(e);
+ }
+
+ /**
+ * Retrieves and removes the head of the queue represented by this deque.
+ *
+ * This method differs from {@link #poll poll} only in that it throws an
+ * exception if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #removeFirst}.
+ *
+ * @return the head of the queue represented by this deque
+ * @throws NoSuchElementException {@inheritDoc}
+ */
+ public Object/*E*/ remove() {
+ return removeFirst();
+ }
+
+ /**
+ * Retrieves and removes the head of the queue represented by this deque
+ * (in other words, the first element of this deque), or returns
+ * <tt>null</tt> if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #pollFirst}.
+ *
+ * @return the head of the queue represented by this deque, or
+ * <tt>null</tt> if this deque is empty
+ */
+ public Object/*E*/ poll() {
+ return pollFirst();
+ }
+
+ /**
+ * Retrieves, but does not remove, the head of the queue represented by
+ * this deque. This method differs from {@link #peek peek} only in
+ * that it throws an exception if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #getFirst}.
+ *
+ * @return the head of the queue represented by this deque
+ * @throws NoSuchElementException {@inheritDoc}
+ */
+ public Object/*E*/ element() {
+ return getFirst();
+ }
+
+ /**
+ * Retrieves, but does not remove, the head of the queue represented by
+ * this deque, or returns <tt>null</tt> if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #peekFirst}.
+ *
+ * @return the head of the queue represented by this deque, or
+ * <tt>null</tt> if this deque is empty
+ */
+ public Object/*E*/ peek() {
+ return peekFirst();
+ }
+
+ // *** Stack methods ***
+
+ /**
+ * Pushes an element onto the stack represented by this deque. In other
+ * words, inserts the element at the front of this deque.
+ *
+ * <p>This method is equivalent to {@link #addFirst}.
+ *
+ * @param e the element to push
+ * @throws NullPointerException if the specified element is null
+ */
+ public void push(Object/*E*/ e) {
+ addFirst(e);
+ }
+
+ /**
+ * Pops an element from the stack represented by this deque. In other
+ * words, removes and returns the first element of this deque.
+ *
+ * <p>This method is equivalent to {@link #removeFirst()}.
+ *
+ * @return the element at the front of this deque (which is the top
+ * of the stack represented by this deque)
+ * @throws NoSuchElementException {@inheritDoc}
+ */
+ public Object/*E*/ pop() {
+ return removeFirst();
+ }
+
+ /*private void checkInvariants() {
+ assert elements[tail] == null;
+ assert head == tail ? elements[head] == null :
+ (elements[head] != null &&
+ elements[(tail - 1) & (elements.length - 1)] != null);
+ assert elements[(head - 1) & (elements.length - 1)] == null;
+ }*/
+
+ /**
+ * Removes the element at the specified position in the elements array,
+ * adjusting head and tail as necessary. This can result in motion of
+ * elements backwards or forwards in the array.
+ *
+ * <p>This method is called delete rather than remove to emphasize
+ * that its semantics differ from those of {@link List#remove(int)}.
+ *
+ * @return true if elements moved backwards
+ */
+ private boolean delete(int i) {
+ //checkInvariants();
+ final Object/*E*/[] elements = this.elements;
+ final int mask = elements.length - 1;
+ final int h = head;
+ final int t = tail;
+ final int front = (i - h) & mask;
+ final int back = (t - i) & mask;
+
+ // Invariant: head <= i < tail mod circularity
+ if (front >= ((t - h) & mask))
+ throw new ConcurrentModificationException();
+
+ // Optimize for least element motion
+ if (front < back) {
+ if (h <= i) {
+ System.arraycopy(elements, h, elements, h + 1, front);
+ } else { // Wrap around
+ System.arraycopy(elements, 0, elements, 1, i);
+ elements[0] = elements[mask];
+ System.arraycopy(elements, h, elements, h + 1, mask - h);
+ }
+ elements[h] = null;
+ head = (h + 1) & mask;
+ return false;
+ } else {
+ if (i < t) { // Copy the null tail as well
+ System.arraycopy(elements, i + 1, elements, i, back);
+ tail = t - 1;
+ } else { // Wrap around
+ System.arraycopy(elements, i + 1, elements, i, mask - i);
+ elements[mask] = elements[0];
+ System.arraycopy(elements, 1, elements, 0, t);
+ tail = (t - 1) & mask;
+ }
+ return true;
+ }
+ }
+
+ // *** Collection Methods ***
+
+ /**
+ * Returns the number of elements in this deque.
+ *
+ * @return the number of elements in this deque
+ */
+ public int size() {
+ return (tail - head) & (elements.length - 1);
+ }
+
+ /**
+ * Returns <tt>true</tt> if this deque contains no elements.
+ *
+ * @return <tt>true</tt> if this deque contains no elements
+ */
+ public boolean isEmpty() {
+ return head == tail;
+ }
+
+ /**
+ * Returns an iterator over the elements in this deque. The elements
+ * will be ordered from first (head) to last (tail). This is the same
+ * order that elements would be dequeued (via successive calls to
+ * {@link #remove} or popped (via successive calls to {@link #pop}).
+ *
+ * @return an iterator over the elements in this deque
+ */
+ public Iterator/*<E>*/ iterator() {
+ return new DeqIterator();
+ }
+
+ public Iterator/*<E>*/ descendingIterator() {
+ return new DescendingIterator();
+ }
+
+ private class DeqIterator implements Iterator/*<E>*/ {
+ /**
+ * Index of element to be returned by subsequent call to next.
+ */
+ private int cursor = head;
+
+ /**
+ * Tail recorded at construction (also in remove), to stop
+ * iterator and also to check for comodification.
+ */
+ private int fence = tail;
+
+ /**
+ * Index of element returned by most recent call to next.
+ * Reset to -1 if element is deleted by a call to remove.
+ */
+ private int lastRet = -1;
+
+ public DeqIterator() {}
+
+ public boolean hasNext() {
+ return cursor != fence;
+ }
+
+ public Object/*E*/ next() {
+ if (cursor == fence)
+ throw new NoSuchElementException();
+ Object/*E*/ result = elements[cursor];
+ // This check doesn't catch all possible comodifications,
+ // but does catch the ones that corrupt traversal
+ if (tail != fence || result == null)
+ throw new ConcurrentModificationException();
+ lastRet = cursor;
+ cursor = (cursor + 1) & (elements.length - 1);
+ return result;
+ }
+
+ public void remove() {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ if (delete(lastRet)) { // if left-shifted, undo increment in next()
+ cursor = (cursor - 1) & (elements.length - 1);
+ fence = tail;
+ }
+ lastRet = -1;
+ }
+ }
+
+ private class DescendingIterator implements Iterator/*<E>*/ {
+ /*
+ * This class is nearly a mirror-image of DeqIterator, using
+ * tail instead of head for initial cursor, and head instead of
+ * tail for fence.
+ */
+ private int cursor = tail;
+ private int fence = head;
+ private int lastRet = -1;
+
+ public boolean hasNext() {
+ return cursor != fence;
+ }
+
+ public Object/*E*/ next() {
+ if (cursor == fence)
+ throw new NoSuchElementException();
+ cursor = (cursor - 1) & (elements.length - 1);
+ Object/*E*/ result = elements[cursor];
+ if (head != fence || result == null)
+ throw new ConcurrentModificationException();
+ lastRet = cursor;
+ return result;
+ }
+
+ public void remove() {
+ if (lastRet < 0)
+ throw new IllegalStateException();
+ if (!delete(lastRet)) {
+ cursor = (cursor + 1) & (elements.length - 1);
+ fence = head;
+ }
+ lastRet = -1;
+ }
+ }
+
+ /**
+ * Returns <tt>true</tt> if this deque contains the specified element.
+ * More formally, returns <tt>true</tt> if and only if this deque contains
+ * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
+ *
+ * @param o object to be checked for containment in this deque
+ * @return <tt>true</tt> if this deque contains the specified element
+ */
+ public boolean contains(Object o) {
+ if (o == null)
+ return false;
+ int mask = elements.length - 1;
+ int i = head;
+ Object/*E*/ x;
+ while ( (x = elements[i]) != null) {
+ if (o.equals(x))
+ return true;
+ i = (i + 1) & mask;
+ }
+ return false;
+ }
+
+ /**
+ * Removes a single instance of the specified element from this deque.
+ * If the deque does not contain the element, it is unchanged.
+ * More formally, removes the first element <tt>e</tt> such that
+ * <tt>o.equals(e)</tt> (if such an element exists).
+ * Returns <tt>true</tt> if this deque contained the specified element
+ * (or equivalently, if this deque changed as a result of the call).
+ *
+ * <p>This method is equivalent to {@link #removeFirstOccurrence}.
+ *
+ * @param o element to be removed from this deque, if present
+ * @return <tt>true</tt> if this deque contained the specified element
+ */
+ public boolean remove(Object o) {
+ return removeFirstOccurrence(o);
+ }
+
+ /**
+ * Removes all of the elements from this deque.
+ * The deque will be empty after this call returns.
+ */
+ public void clear() {
+ int h = head;
+ int t = tail;
+ if (h != t) { // clear all cells
+ head = tail = 0;
+ int i = h;
+ int mask = elements.length - 1;
+ do {
+ elements[i] = null;
+ i = (i + 1) & mask;
+ } while (i != t);
+ }
+ }
+
+ /**
+ * Returns an array containing all of the elements in this deque
+ * in proper sequence (from first to last element).
+ *
+ * <p>The returned array will be "safe" in that no references to it are
+ * maintained by this deque. (In other words, this method must allocate
+ * a new array). The caller is thus free to modify the returned array.
+ *
+ * <p>This method acts as bridge between array-based and collection-based
+ * APIs.
+ *
+ * @return an array containing all of the elements in this deque
+ */
+ public Object[] toArray() {
+ return copyElements(new Object[size()]);
+ }
+
+ /**
+ * Returns an array containing all of the elements in this deque in
+ * proper sequence (from first to last element); the runtime type of the
+ * returned array is that of the specified array. If the deque 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 deque.
+ *
+ * <p>If this deque fits in the specified array with room to spare
+ * (i.e., the array has more elements than this deque), the element in
+ * the array immediately following the end of the deque is set to
+ * <tt>null</tt>.
+ *
+ * <p>Like the {@link #toArray()} method, this method acts as bridge between
+ * array-based and collection-based APIs. Further, this method allows
+ * precise control over the runtime type of the output array, and may,
+ * under certain circumstances, be used to save allocation costs.
+ *
+ * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
+ * The following code can be used to dump the deque into a newly
+ * allocated array of <tt>String</tt>:
+ *
+ * <pre>
+ * String[] y = x.toArray(new String[0]);</pre>
+ *
+ * Note that <tt>toArray(new Object[0])</tt> is identical in function to
+ * <tt>toArray()</tt>.
+ *
+ * @param a the array into which the elements of the deque 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 all of the elements in this deque
+ * @throws ArrayStoreException if the runtime type of the specified array
+ * is not a supertype of the runtime type of every element in
+ * this deque
+ * @throws NullPointerException if the specified array is null
+ */
+ public /*<T> T*/Object[] toArray(Object/*T*/[] a) {
+ int size = size();
+ if (a.length < size)
+ a = /*(T[])java.lang.reflect.*/Array.newInstance(
+ a.getClass().getComponentType(), size);
+ copyElements(a);
+ if (a.length > size)
+ a[size] = null;
+ return a;
+ }
+
+ // *** Object methods ***
+
+ /**
+ * Returns a copy of this deque.
+ *
+ * @return a copy of this deque
+ */
+ /*public ArrayDeque<E> clone() {
+ try {
+ ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
+ // Classpath local: we don't have Arrays.copyOf yet.
+ // result.elements = Arrays.copyOf(elements, elements.length);
+ result.elements = elements.clone();
+ return result;
+
+ } catch (CloneNotSupportedException e) {
+ throw new AssertionError();
+ }
+ }*/
+
+ /**
+ * Appease the serialization gods.
+ */
+ private static final long serialVersionUID = 2340985798034038923L;
+
+ /**
+ * Serialize this deque.
+ *
+ * @serialData The current size (<tt>int</tt>) of the deque,
+ * followed by all of its elements (each an object reference) in
+ * first-to-last order.
+ */
+ /*private void writeObject(ObjectOutputStream s) throws IOException {
+ s.defaultWriteObject();
+
+ // Write out size
+ s.writeInt(size());
+
+ // Write out elements in order.
+ int mask = elements.length - 1;
+ for (int i = head; i != tail; i = (i + 1) & mask)
+ s.writeObject(elements[i]);
+ }*/
+
+ /**
+ * Deserialize this deque.
+ */
+ /*private void readObject(ObjectInputStream s)
+ throws IOException, ClassNotFoundException {
+ s.defaultReadObject();
+
+ // Read in size and allocate array
+ int size = s.readInt();
+ allocateElements(size);
+ head = 0;
+ tail = size;
+
+ // Read in all elements in the proper order.
+ for (int i = 0; i < size; i++)
+ elements[i] = (E)s.readObject();
+ }*/
+}
*/
//public class ArrayList<E> extends AbstractList<E>
// implements List<E>, RandomAccess, Cloneable, Serializable
-public class ArrayList
+public class ArrayList implements List, Cloneable, Serializable
{
protected transient int modCount;
/**
* @param c the collection whose elements will initialize this list
* @throws NullPointerException if c is null
*/
- /*public ArrayList(Collection<? extends E> c)
+ public ArrayList(Collection/*<? extends E>*/ c)
{
this((int) (c.size() * 1.1f));
addAll(c);
- }*/
+ }
/**
* Trims the capacity of this List to be equal to its size;
-public class ArrayListIterator extends Iterator {
+public class ArrayListIterator implements Iterator {
private int pos;
private int size;
private int last;
size--;
last = -1;
}
-}
\ No newline at end of file
+}
--- /dev/null
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+/*package java.util.concurrent.atomic;
+import sun.misc.Unsafe;*/
+
+/**
+ * An <tt>int</tt> value that may be updated atomically. See the
+ * {@link java.util.concurrent.atomic} package specification for
+ * description of the properties of atomic variables. An
+ * <tt>AtomicInteger</tt> is used in applications such as atomically
+ * incremented counters, and cannot be used as a replacement for an
+ * {@link java.lang.Integer}. However, this class does extend
+ * <tt>Number</tt> to allow uniform access by tools and utilities that
+ * deal with numerically-based classes.
+ *
+ * @since 1.5
+ * @author Doug Lea
+*/
+public class AtomicInteger /*extends Number*/ implements /*java.io.*/Serializable {
+ private static final long serialVersionUID = 6214790243416807050L;
+
+ // setup to use Unsafe.compareAndSwapInt for updates
+ /*private static final Unsafe unsafe = Unsafe.getUnsafe();
+ private static final long valueOffset;
+
+ static {
+ try {
+ valueOffset = unsafe.objectFieldOffset
+ (AtomicInteger.class.getDeclaredField("value"));
+ } catch (Exception ex) { throw new Error(ex); }
+ }*/
+
+ private volatile int value;
+
+ /**
+ * Creates a new AtomicInteger with the given initial value.
+ *
+ * @param initialValue the initial value
+ */
+ public AtomicInteger(int initialValue) {
+ value = initialValue;
+ }
+
+ /**
+ * Creates a new AtomicInteger with initial value <tt>0</tt>.
+ */
+ public AtomicInteger() {
+ }
+
+ /**
+ * Gets the current value.
+ *
+ * @return the current value
+ */
+ public final int get() {
+ return value;
+ }
+
+ /**
+ * Sets to the given value.
+ *
+ * @param newValue the new value
+ */
+ public final void set(int newValue) {
+ value = newValue;
+ }
+
+ /**
+ * Eventually sets to the given value.
+ *
+ * @param newValue the new value
+ * @since 1.6
+ */
+ public final void lazySet(int newValue) {
+ //unsafe.putOrderedInt(this, valueOffset, newValue);
+ System.out.println("Unimplemented AtomicInteger.lazySet()!");
+ }
+
+ /**
+ * Atomically sets to the given value and returns the old value.
+ *
+ * @param newValue the new value
+ * @return the previous value
+ */
+ public final int getAndSet(int newValue) {
+ for (;;) {
+ int current = get();
+ if (compareAndSet(current, newValue))
+ return current;
+ }
+ }
+
+ /**
+ * Atomically sets the value to the given updated value
+ * if the current value <tt>==</tt> the expected value.
+ *
+ * @param expect the expected value
+ * @param update the new value
+ * @return true if successful. False return indicates that
+ * the actual value was not equal to the expected value.
+ */
+ public final boolean compareAndSet(int expect, int update) {
+ System.out.println("Unimplemented AtomicInteger.compareAndSet()!");
+ return false; //unsafe.compareAndSwapInt(this, valueOffset, expect, update);
+ }
+
+ /**
+ * Atomically sets the value to the given updated value
+ * if the current value <tt>==</tt> the expected value.
+ * May fail spuriously and does not provide ordering guarantees,
+ * so is only rarely an appropriate alternative to <tt>compareAndSet</tt>.
+ *
+ * @param expect the expected value
+ * @param update the new value
+ * @return true if successful.
+ */
+ public final boolean weakCompareAndSet(int expect, int update) {
+ System.out.println("Unimplemented AtomicInteger.weakCompareAndSet()!");
+ return false; //unsafe.compareAndSwapInt(this, valueOffset, expect, update);
+ }
+
+ /**
+ * Atomically increments by one the current value.
+ *
+ * @return the previous value
+ */
+ public final int getAndIncrement() {
+ for (;;) {
+ int current = get();
+ int next = current + 1;
+ if (compareAndSet(current, next))
+ return current;
+ }
+ }
+
+ /**
+ * Atomically decrements by one the current value.
+ *
+ * @return the previous value
+ */
+ public final int getAndDecrement() {
+ for (;;) {
+ int current = get();
+ int next = current - 1;
+ if (compareAndSet(current, next))
+ return current;
+ }
+ }
+
+ /**
+ * Atomically adds the given value to the current value.
+ *
+ * @param delta the value to add
+ * @return the previous value
+ */
+ public final int getAndAdd(int delta) {
+ for (;;) {
+ int current = get();
+ int next = current + delta;
+ if (compareAndSet(current, next))
+ return current;
+ }
+ }
+
+ /**
+ * Atomically increments by one the current value.
+ *
+ * @return the updated value
+ */
+ public final int incrementAndGet() {
+ for (;;) {
+ int current = get();
+ int next = current + 1;
+ if (compareAndSet(current, next))
+ return next;
+ }
+ }
+
+ /**
+ * Atomically decrements by one the current value.
+ *
+ * @return the updated value
+ */
+ public final int decrementAndGet() {
+ for (;;) {
+ int current = get();
+ int next = current - 1;
+ if (compareAndSet(current, next))
+ return next;
+ }
+ }
+
+ /**
+ * Atomically adds the given value to the current value.
+ *
+ * @param delta the value to add
+ * @return the updated value
+ */
+ public final int addAndGet(int delta) {
+ for (;;) {
+ int current = get();
+ int next = current + delta;
+ if (compareAndSet(current, next))
+ return next;
+ }
+ }
+
+ /**
+ * Returns the String representation of the current value.
+ * @return the String representation of the current value.
+ */
+ /*public String toString() {
+ return Integer.toString(get());
+ }*/
+
+
+ public int intValue() {
+ return get();
+ }
+
+ public long longValue() {
+ return (long)get();
+ }
+
+ public float floatValue() {
+ return (float)get();
+ }
+
+ public double doubleValue() {
+ return (double)get();
+ }
+
+}
--- /dev/null
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+//package java.util.concurrent.atomic;
+//import sun.misc.Unsafe;
+
+/**
+ * An object reference that may be updated atomically. See the {@link
+ * java.util.concurrent.atomic} package specification for description
+ * of the properties of atomic variables.
+ * @since 1.5
+ * @author Doug Lea
+ * @param <V> The type of object referred to by this reference
+ */
+public class AtomicReference/*<V>*/ implements /*java.io.*/Serializable {
+ private static final long serialVersionUID = -1848883965231344442L;
+
+ //private static final Unsafe unsafe = Unsafe.getUnsafe();
+ // private static final long valueOffset;
+
+ /*static {
+ try {
+ valueOffset = unsafe.objectFieldOffset
+ (AtomicReference.class.getDeclaredField("value"));
+ } catch (Exception ex) { throw new Error(ex); }
+ }*/
+
+ private volatile Object/*V*/ value;
+
+ /**
+ * Creates a new AtomicReference with the given initial value.
+ *
+ * @param initialValue the initial value
+ */
+ public AtomicReference(Object/*V*/ initialValue) {
+ value = initialValue;
+ }
+
+ /**
+ * Creates a new AtomicReference with null initial value.
+ */
+ public AtomicReference() {
+ }
+
+ /**
+ * Gets the current value.
+ *
+ * @return the current value
+ */
+ public final Object/*V*/ get() {
+ return value;
+ }
+
+ /**
+ * Sets to the given value.
+ *
+ * @param newValue the new value
+ */
+ public final void set(Object/*V*/ newValue) {
+ value = newValue;
+ }
+
+ /**
+ * Eventually sets to the given value.
+ *
+ * @param newValue the new value
+ * @since 1.6
+ */
+ public final void lazySet(Object/*V*/ newValue) {
+ //unsafe.putOrderedObject(this, valueOffset, newValue);
+ System.out.println("Unimplemented AtomicReference.lazySet()!");
+ }
+
+ /**
+ * Atomically sets the value to the given updated value
+ * if the current value <tt>==</tt> the expected value.
+ * @param expect the expected value
+ * @param update the new value
+ * @return true if successful. False return indicates that
+ * the actual value was not equal to the expected value.
+ */
+ public final boolean compareAndSet(Object/*V*/ expect, Object/*V*/ update) {
+ //return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
+ System.out.println("Unimplemented AtomicReference.compareAndSet()!");
+ }
+
+ /**
+ * Atomically sets the value to the given updated value
+ * if the current value <tt>==</tt> the expected value.
+ * May fail spuriously and does not provide ordering guarantees,
+ * so is only rarely an appropriate alternative to <tt>compareAndSet</tt>.
+ *
+ * @param expect the expected value
+ * @param update the new value
+ * @return true if successful.
+ */
+ public final boolean weakCompareAndSet(Object/*V*/ expect, Object/*V*/ update) {
+ //return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
+ System.out.println("Unimplemented AtomicReference.weakCompareAndSet()!");
+ }
+
+ /**
+ * Atomically sets to the given value and returns the old value.
+ *
+ * @param newValue the new value
+ * @return the previous value
+ */
+ public final Object/*V*/ getAndSet(Object/*V*/ newValue) {
+ while (true) {
+ Object/*V*/ x = get();
+ if (compareAndSet(x, newValue))
+ return x;
+ }
+ }
+
+ /**
+ * Returns the String representation of the current value.
+ * @return the String representation of the current value.
+ */
+ /*public String toString() {
+ return String.valueOf(get());
+ }*/
+
+}
--- /dev/null
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+
+/**
+ * A task that returns a result and may throw an exception.
+ * Implementors define a single method with no arguments called
+ * <tt>call</tt>.
+ *
+ * <p>The <tt>Callable</tt> interface is similar to {@link
+ * java.lang.Runnable}, in that both are designed for classes whose
+ * instances are potentially executed by another thread. A
+ * <tt>Runnable</tt>, however, does not return a result and cannot
+ * throw a checked exception.
+ *
+ * <p> The {@link Executors} class contains utility methods to
+ * convert from other common forms to <tt>Callable</tt> classes.
+ *
+ * @see Executor
+ * @since 1.5
+ * @author Doug Lea
+ * @param <V> the result type of method <tt>call</tt>
+ */
+public interface Callable/*<V>*/ {
+ /**
+ * Computes a result, or throws an exception if unable to do so.
+ *
+ * @return computed result
+ * @throws Exception if unable to compute a result
+ */
+ /*V*/Object call() throws Exception;
+}
--- /dev/null
+/* Collection.java -- Interface that represents a collection of objects
+ Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.util;
+
+/**
+ * Interface that represents a collection of objects. This interface is the
+ * root of the collection hierarchy, and does not provide any guarantees about
+ * the order of its elements or whether or not duplicate elements are
+ * permitted.
+ * <p>
+ * All methods of this interface that are defined to modify the collection are
+ * defined as <dfn>optional</dfn>. An optional operation may throw an
+ * UnsupportedOperationException if the data backing this collection does not
+ * support such a modification. This may mean that the data structure is
+ * immutable, or that it is read-only but may change ("unmodifiable"), or
+ * that it is modifiable but of fixed size (such as an array), or any number
+ * of other combinations.
+ * <p>
+ * A class that wishes to implement this interface should consider subclassing
+ * AbstractCollection, which provides basic implementations of most of the
+ * methods of this interface. Classes that are prepared to make guarantees
+ * about ordering or about absence of duplicate elements should consider
+ * implementing List or Set respectively, both of which are subinterfaces of
+ * Collection.
+ * <p>
+ * A general-purpose implementation of the Collection interface should in most
+ * cases provide at least two constructors: One which takes no arguments and
+ * creates an empty collection, and one which takes a Collection as an argument
+ * and returns a collection containing the same elements (that is, creates a
+ * copy of the argument using its own implementation).
+ *
+ * @author Original author unknown
+ * @author Eric Blake (ebb9@email.byu.edu)
+ * @author Tom Tromey (tromey@redhat.com)
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @see List
+ * @see Set
+ * @see Map
+ * @see SortedSet
+ * @see SortedMap
+ * @see HashSet
+ * @see TreeSet
+ * @see ArrayList
+ * @see LinkedList
+ * @see Vector
+ * @see Collections
+ * @see Arrays
+ * @see AbstractCollection
+ * @since 1.2
+ * @status updated to 1.4
+ */
+public interface Collection/*<E>*/ extends Iterable/*<E>*/
+{
+ /**
+ * Add an element to this collection.
+ *
+ * @param o the object to add.
+ * @return true if the collection was modified as a result of this action.
+ * @throws UnsupportedOperationException if this collection does not
+ * support the add operation.
+ * @throws ClassCastException if o cannot be added to this collection due
+ * to its type.
+ * @throws NullPointerException if o is null and this collection doesn't
+ * support the addition of null values.
+ * @throws IllegalArgumentException if o cannot be added to this
+ * collection for some other reason.
+ */
+ boolean add(Object/*E*/ o);
+
+ /**
+ * Add the contents of a given collection to this collection.
+ *
+ * @param c the collection to add.
+ * @return true if the collection was modified as a result of this action.
+ * @throws UnsupportedOperationException if this collection does not
+ * support the addAll operation.
+ * @throws ClassCastException if some element of c cannot be added to this
+ * collection due to its type.
+ * @throws NullPointerException if some element of c is null and this
+ * collection does not support the addition of null values.
+ * @throws NullPointerException if c itself is null.
+ * @throws IllegalArgumentException if some element of c cannot be added
+ * to this collection for some other reason.
+ */
+ boolean addAll(Collection/*<? extends E>*/ c);
+
+ /**
+ * Clear the collection, such that a subsequent call to isEmpty() would
+ * return true.
+ *
+ * @throws UnsupportedOperationException if this collection does not
+ * support the clear operation.
+ */
+ void clear();
+
+ /**
+ * Test whether this collection contains a given object as one of its
+ * elements.
+ *
+ * @param o the element to look for.
+ * @return true if this collection contains at least one element e such that
+ * <code>o == null ? e == null : o.equals(e)</code>.
+ * @throws ClassCastException if the type of o is not a valid type for this
+ * collection.
+ * @throws NullPointerException if o is null and this collection doesn't
+ * support null values.
+ */
+ boolean contains(Object o);
+
+ /**
+ * Test whether this collection contains every element in a given collection.
+ *
+ * @param c the collection to test for.
+ * @return true if for every element o in c, contains(o) would return true.
+ * @throws ClassCastException if the type of any element in c is not a valid
+ * type for this collection.
+ * @throws NullPointerException if some element of c is null and this
+ * collection does not support null values.
+ * @throws NullPointerException if c itself is null.
+ */
+ boolean containsAll(Collection/*<?>*/ c);
+
+ /**
+ * Test whether this collection is equal to some object. The Collection
+ * interface does not explicitly require any behaviour from this method, and
+ * it may be left to the default implementation provided by Object. The Set
+ * and List interfaces do, however, require specific behaviour from this
+ * method.
+ * <p>
+ * If an implementation of Collection, which is not also an implementation of
+ * Set or List, should choose to implement this method, it should take care
+ * to obey the contract of the equals method of Object. In particular, care
+ * should be taken to return false when o is a Set or a List, in order to
+ * preserve the symmetry of the relation.
+ *
+ * @param o the object to compare to this collection.
+ * @return true if the o is equal to this collection.
+ */
+ //boolean equals(Object o);
+
+ /**
+ * Obtain a hash code for this collection. The Collection interface does not
+ * explicitly require any behaviour from this method, and it may be left to
+ * the default implementation provided by Object. The Set and List interfaces
+ * do, however, require specific behaviour from this method.
+ * <p>
+ * If an implementation of Collection, which is not also an implementation of
+ * Set or List, should choose to implement this method, it should take care
+ * to obey the contract of the hashCode method of Object. Note that this
+ * method renders it impossible to correctly implement both Set and List, as
+ * the required implementations are mutually exclusive.
+ *
+ * @return a hash code for this collection.
+ */
+ //int hashCode();
+
+ /**
+ * Test whether this collection is empty, that is, if size() == 0.
+ *
+ * @return true if this collection contains no elements.
+ */
+ boolean isEmpty();
+
+ /**
+ * Obtain an Iterator over this collection.
+ *
+ * @return an Iterator over the elements of this collection, in any order.
+ */
+ Iterator/*<E>*/ iterator();
+
+ /**
+ * Remove a single occurrence of an object from this collection. That is,
+ * remove an element e, if one exists, such that <code>o == null ? e == null
+ * : o.equals(e)</code>.
+ *
+ * @param o the object to remove.
+ * @return true if the collection changed as a result of this call, that is,
+ * if the collection contained at least one occurrence of o.
+ * @throws UnsupportedOperationException if this collection does not
+ * support the remove operation.
+ * @throws ClassCastException if the type of o is not a valid type
+ * for this collection.
+ * @throws NullPointerException if o is null and the collection doesn't
+ * support null values.
+ */
+ boolean remove(Object o);
+
+ /**
+ * Remove all elements of a given collection from this collection. That is,
+ * remove every element e such that c.contains(e).
+ *
+ * @param c The collection of objects to be removed.
+ * @return true if this collection was modified as a result of this call.
+ * @throws UnsupportedOperationException if this collection does not
+ * support the removeAll operation.
+ * @throws ClassCastException if the type of any element in c is not a valid
+ * type for this collection.
+ * @throws NullPointerException if some element of c is null and this
+ * collection does not support removing null values.
+ * @throws NullPointerException if c itself is null.
+ */
+ boolean removeAll(Collection/*<?>*/ c);
+
+ /**
+ * Remove all elements of this collection that are not contained in a given
+ * collection. That is, remove every element e such that !c.contains(e).
+ *
+ * @param c The collection of objects to be retained.
+ * @return true if this collection was modified as a result of this call.
+ * @throws UnsupportedOperationException if this collection does not
+ * support the retainAll operation.
+ * @throws ClassCastException if the type of any element in c is not a valid
+ * type for this collection.
+ * @throws NullPointerException if some element of c is null and this
+ * collection does not support retaining null values.
+ * @throws NullPointerException if c itself is null.
+ */
+ //boolean retainAll(Collection/*<?>*/ c);
+
+ /**
+ * Get the number of elements in this collection.
+ *
+ * @return the number of elements in the collection.
+ */
+ int size();
+
+ /**
+ * Copy the current contents of this collection into an array.
+ *
+ * @return an array of type Object[] and length equal to the size of this
+ * collection, containing the elements currently in this collection, in
+ * any order.
+ */
+ //Object[] toArray();
+
+ /**
+ * Copy the current contents of this collection into an array. If the array
+ * passed as an argument has length less than the size of this collection, an
+ * array of the same run-time type as a, and length equal to the size of this
+ * collection, is allocated using Reflection. Otherwise, a itself is used.
+ * The elements of this collection are copied into it, and if there is space
+ * in the array, the following element is set to null. The resultant array is
+ * returned.
+ * Note: The fact that the following element is set to null is only useful
+ * if it is known that this collection does not contain any null elements.
+ *
+ * @param a the array to copy this collection into.
+ * @return an array containing the elements currently in this collection, in
+ * any order.
+ * @throws ArrayStoreException if the type of any element of the
+ * collection is not a subtype of the element type of a.
+ */
+ ///*<T> T*/Object[] toArray(Object/*T*/[] a);
+}
--- /dev/null
+/* Comparator.java -- Interface for objects that specify an ordering
+ Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.util;
+
+/**
+ * Interface for objects that specify an ordering between objects. The ordering
+ * should be <em>total</em>, such that any two objects of the correct type
+ * can be compared, and the comparison is reflexive, anti-symmetric, and
+ * transitive. It is also recommended that the comparator be <em>consistent
+ * with equals</em>, although this is not a strict requirement. A relation
+ * is consistent with equals if these two statements always have the same
+ * results (if no exceptions occur):<br>
+ * <code>compare((Object) e1, (Object) e2) == 0</code> and
+ * <code>e1.equals((Object) e2)</code><br>
+ * Comparators that violate consistency with equals may cause strange behavior
+ * in sorted lists and sets. For example, a case-sensitive dictionary order
+ * comparison of Strings is consistent with equals, but if it is
+ * case-insensitive it is not, because "abc" and "ABC" compare as equal even
+ * though "abc".equals("ABC") returns false.
+ * <P>
+ * In general, Comparators should be Serializable, because when they are passed
+ * to Serializable data structures such as SortedMap or SortedSet, the entire
+ * data structure will only serialize correctly if the comparator is
+ * Serializable.
+ *
+ * @author Original author unknown
+ * @author Eric Blake (ebb9@email.byu.edu)
+ * @see Comparable
+ * @see TreeMap
+ * @see TreeSet
+ * @see SortedMap
+ * @see SortedSet
+ * @see Arrays#sort(Object[], Comparator)
+ * @see java.io.Serializable
+ * @since 1.2
+ * @status updated to 1.4
+ */
+public interface Comparator/*<T>*/
+{
+ /**
+ * Return an integer that is negative, zero or positive depending on whether
+ * the first argument is less than, equal to or greater than the second
+ * according to this ordering. This method should obey the following
+ * contract:
+ * <ul>
+ * <li>if compare(a, b) < 0 then compare(b, a) > 0</li>
+ * <li>if compare(a, b) throws an exception, so does compare(b, a)</li>
+ * <li>if compare(a, b) < 0 and compare(b, c) < 0 then compare(a, c)
+ * < 0</li>
+ * <li>if compare(a, b) == 0 then compare(a, c) and compare(b, c) must
+ * have the same sign</li>
+ * </ul>
+ * To be consistent with equals, the following additional constraint is
+ * in place:
+ * <ul>
+ * <li>if a.equals(b) or both a and b are null, then
+ * compare(a, b) == 0.</li>
+ * </ul><p>
+ *
+ * Although it is permissible for a comparator to provide an order
+ * inconsistent with equals, that should be documented.
+ *
+ * @param o1 the first object
+ * @param o2 the second object
+ * @return the comparison
+ * @throws ClassCastException if the elements are not of types that can be
+ * compared by this ordering.
+ */
+ int compare(Object/*T*/ o1, Object/*T*/ o2);
+
+ /**
+ * Return true if the object is equal to this object. To be
+ * considered equal, the argument object must satisfy the constraints
+ * of <code>Object.equals()</code>, be a Comparator, and impose the
+ * same ordering as this Comparator. The default implementation
+ * inherited from Object is usually adequate.
+ *
+ * @param obj The object
+ * @return true if it is a Comparator that imposes the same order
+ * @see Object#equals(Object)
+ */
+ boolean equals(Object obj);
+}
--- /dev/null
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent.locks;
+import java.util.concurrent.*;
+import java.util.Date;
+
+/**
+ * {@code Condition} factors out the {@code Object} monitor
+ * methods ({@link Object#wait() wait}, {@link Object#notify notify}
+ * and {@link Object#notifyAll notifyAll}) into distinct objects to
+ * give the effect of having multiple wait-sets per object, by
+ * combining them with the use of arbitrary {@link Lock} implementations.
+ * Where a {@code Lock} replaces the use of {@code synchronized} methods
+ * and statements, a {@code Condition} replaces the use of the Object
+ * monitor methods.
+ *
+ * <p>Conditions (also known as <em>condition queues</em> or
+ * <em>condition variables</em>) provide a means for one thread to
+ * suspend execution (to "wait") until notified by another
+ * thread that some state condition may now be true. Because access
+ * to this shared state information occurs in different threads, it
+ * must be protected, so a lock of some form is associated with the
+ * condition. The key property that waiting for a condition provides
+ * is that it <em>atomically</em> releases the associated lock and
+ * suspends the current thread, just like {@code Object.wait}.
+ *
+ * <p>A {@code Condition} instance is intrinsically bound to a lock.
+ * To obtain a {@code Condition} instance for a particular {@link Lock}
+ * instance use its {@link Lock#newCondition newCondition()} method.
+ *
+ * <p>As an example, suppose we have a bounded buffer which supports
+ * {@code put} and {@code take} methods. If a
+ * {@code take} is attempted on an empty buffer, then the thread will block
+ * until an item becomes available; if a {@code put} is attempted on a
+ * full buffer, then the thread will block until a space becomes available.
+ * We would like to keep waiting {@code put} threads and {@code take}
+ * threads in separate wait-sets so that we can use the optimization of
+ * only notifying a single thread at a time when items or spaces become
+ * available in the buffer. This can be achieved using two
+ * {@link Condition} instances.
+ * <pre>
+ * class BoundedBuffer {
+ * <b>final Lock lock = new ReentrantLock();</b>
+ * final Condition notFull = <b>lock.newCondition(); </b>
+ * final Condition notEmpty = <b>lock.newCondition(); </b>
+ *
+ * final Object[] items = new Object[100];
+ * int putptr, takeptr, count;
+ *
+ * public void put(Object x) throws InterruptedException {
+ * <b>lock.lock();
+ * try {</b>
+ * while (count == items.length)
+ * <b>notFull.await();</b>
+ * items[putptr] = x;
+ * if (++putptr == items.length) putptr = 0;
+ * ++count;
+ * <b>notEmpty.signal();</b>
+ * <b>} finally {
+ * lock.unlock();
+ * }</b>
+ * }
+ *
+ * public Object take() throws InterruptedException {
+ * <b>lock.lock();
+ * try {</b>
+ * while (count == 0)
+ * <b>notEmpty.await();</b>
+ * Object x = items[takeptr];
+ * if (++takeptr == items.length) takeptr = 0;
+ * --count;
+ * <b>notFull.signal();</b>
+ * return x;
+ * <b>} finally {
+ * lock.unlock();
+ * }</b>
+ * }
+ * }
+ * </pre>
+ *
+ * (The {@link java.util.concurrent.ArrayBlockingQueue} class provides
+ * this functionality, so there is no reason to implement this
+ * sample usage class.)
+ *
+ * <p>A {@code Condition} implementation can provide behavior and semantics
+ * that is
+ * different from that of the {@code Object} monitor methods, such as
+ * guaranteed ordering for notifications, or not requiring a lock to be held
+ * when performing notifications.
+ * If an implementation provides such specialized semantics then the
+ * implementation must document those semantics.
+ *
+ * <p>Note that {@code Condition} instances are just normal objects and can
+ * themselves be used as the target in a {@code synchronized} statement,
+ * and can have their own monitor {@link Object#wait wait} and
+ * {@link Object#notify notification} methods invoked.
+ * Acquiring the monitor lock of a {@code Condition} instance, or using its
+ * monitor methods, has no specified relationship with acquiring the
+ * {@link Lock} associated with that {@code Condition} or the use of its
+ * {@linkplain #await waiting} and {@linkplain #signal signalling} methods.
+ * It is recommended that to avoid confusion you never use {@code Condition}
+ * instances in this way, except perhaps within their own implementation.
+ *
+ * <p>Except where noted, passing a {@code null} value for any parameter
+ * will result in a {@link NullPointerException} being thrown.
+ *
+ * <h3>Implementation Considerations</h3>
+ *
+ * <p>When waiting upon a {@code Condition}, a "<em>spurious
+ * wakeup</em>" is permitted to occur, in
+ * general, as a concession to the underlying platform semantics.
+ * This has little practical impact on most application programs as a
+ * {@code Condition} should always be waited upon in a loop, testing
+ * the state predicate that is being waited for. An implementation is
+ * free to remove the possibility of spurious wakeups but it is
+ * recommended that applications programmers always assume that they can
+ * occur and so always wait in a loop.
+ *
+ * <p>The three forms of condition waiting
+ * (interruptible, non-interruptible, and timed) may differ in their ease of
+ * implementation on some platforms and in their performance characteristics.
+ * In particular, it may be difficult to provide these features and maintain
+ * specific semantics such as ordering guarantees.
+ * Further, the ability to interrupt the actual suspension of the thread may
+ * not always be feasible to implement on all platforms.
+ *
+ * <p>Consequently, an implementation is not required to define exactly the
+ * same guarantees or semantics for all three forms of waiting, nor is it
+ * required to support interruption of the actual suspension of the thread.
+ *
+ * <p>An implementation is required to
+ * clearly document the semantics and guarantees provided by each of the
+ * waiting methods, and when an implementation does support interruption of
+ * thread suspension then it must obey the interruption semantics as defined
+ * in this interface.
+ *
+ * <p>As interruption generally implies cancellation, and checks for
+ * interruption are often infrequent, an implementation can favor responding
+ * to an interrupt over normal method return. This is true even if it can be
+ * shown that the interrupt occurred after another action may have unblocked
+ * the thread. An implementation should document this behavior.
+ *
+ * @since 1.5
+ * @author Doug Lea
+ */
+public interface Condition {
+
+ /**
+ * Causes the current thread to wait until it is signalled or
+ * {@linkplain Thread#interrupt interrupted}.
+ *
+ * <p>The lock associated with this {@code Condition} is atomically
+ * released and the current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until <em>one</em> of four things happens:
+ * <ul>
+ * <li>Some other thread invokes the {@link #signal} method for this
+ * {@code Condition} and the current thread happens to be chosen as the
+ * thread to be awakened; or
+ * <li>Some other thread invokes the {@link #signalAll} method for this
+ * {@code Condition}; or
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
+ * current thread, and interruption of thread suspension is supported; or
+ * <li>A "<em>spurious wakeup</em>" occurs.
+ * </ul>
+ *
+ * <p>In all cases, before this method can return the current thread must
+ * re-acquire the lock associated with this condition. When the
+ * thread returns it is <em>guaranteed</em> to hold this lock.
+ *
+ * <p>If the current thread:
+ * <ul>
+ * <li>has its interrupted status set on entry to this method; or
+ * <li>is {@linkplain Thread#interrupt interrupted} while waiting
+ * and interruption of thread suspension is supported,
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared. It is not specified, in the first
+ * case, whether or not the test for interruption occurs before the lock
+ * is released.
+ *
+ * <p><b>Implementation Considerations</b>
+ *
+ * <p>The current thread is assumed to hold the lock associated with this
+ * {@code Condition} when this method is called.
+ * It is up to the implementation to determine if this is
+ * the case and if not, how to respond. Typically, an exception will be
+ * thrown (such as {@link IllegalMonitorStateException}) and the
+ * implementation must document that fact.
+ *
+ * <p>An implementation can favor responding to an interrupt over normal
+ * method return in response to a signal. In that case the implementation
+ * must ensure that the signal is redirected to another waiting thread, if
+ * there is one.
+ *
+ * @throws InterruptedException if the current thread is interrupted
+ * (and interruption of thread suspension is supported)
+ */
+ void await() throws InterruptedException;
+
+ /**
+ * Causes the current thread to wait until it is signalled.
+ *
+ * <p>The lock associated with this condition is atomically
+ * released and the current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until <em>one</em> of three things happens:
+ * <ul>
+ * <li>Some other thread invokes the {@link #signal} method for this
+ * {@code Condition} and the current thread happens to be chosen as the
+ * thread to be awakened; or
+ * <li>Some other thread invokes the {@link #signalAll} method for this
+ * {@code Condition}; or
+ * <li>A "<em>spurious wakeup</em>" occurs.
+ * </ul>
+ *
+ * <p>In all cases, before this method can return the current thread must
+ * re-acquire the lock associated with this condition. When the
+ * thread returns it is <em>guaranteed</em> to hold this lock.
+ *
+ * <p>If the current thread's interrupted status is set when it enters
+ * this method, or it is {@linkplain Thread#interrupt interrupted}
+ * while waiting, it will continue to wait until signalled. When it finally
+ * returns from this method its interrupted status will still
+ * be set.
+ *
+ * <p><b>Implementation Considerations</b>
+ *
+ * <p>The current thread is assumed to hold the lock associated with this
+ * {@code Condition} when this method is called.
+ * It is up to the implementation to determine if this is
+ * the case and if not, how to respond. Typically, an exception will be
+ * thrown (such as {@link IllegalMonitorStateException}) and the
+ * implementation must document that fact.
+ */
+ void awaitUninterruptibly();
+
+ /**
+ * Causes the current thread to wait until it is signalled or interrupted,
+ * or the specified waiting time elapses.
+ *
+ * <p>The lock associated with this condition is atomically
+ * released and the current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until <em>one</em> of five things happens:
+ * <ul>
+ * <li>Some other thread invokes the {@link #signal} method for this
+ * {@code Condition} and the current thread happens to be chosen as the
+ * thread to be awakened; or
+ * <li>Some other thread invokes the {@link #signalAll} method for this
+ * {@code Condition}; or
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
+ * current thread, and interruption of thread suspension is supported; or
+ * <li>The specified waiting time elapses; or
+ * <li>A "<em>spurious wakeup</em>" occurs.
+ * </ul>
+ *
+ * <p>In all cases, before this method can return the current thread must
+ * re-acquire the lock associated with this condition. When the
+ * thread returns it is <em>guaranteed</em> to hold this lock.
+ *
+ * <p>If the current thread:
+ * <ul>
+ * <li>has its interrupted status set on entry to this method; or
+ * <li>is {@linkplain Thread#interrupt interrupted} while waiting
+ * and interruption of thread suspension is supported,
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared. It is not specified, in the first
+ * case, whether or not the test for interruption occurs before the lock
+ * is released.
+ *
+ * <p>The method returns an estimate of the number of nanoseconds
+ * remaining to wait given the supplied {@code nanosTimeout}
+ * value upon return, or a value less than or equal to zero if it
+ * timed out. This value can be used to determine whether and how
+ * long to re-wait in cases where the wait returns but an awaited
+ * condition still does not hold. Typical uses of this method take
+ * the following form:
+ *
+ * <pre>
+ * synchronized boolean aMethod(long timeout, TimeUnit unit) {
+ * long nanosTimeout = unit.toNanos(timeout);
+ * while (!conditionBeingWaitedFor) {
+ * if (nanosTimeout > 0)
+ * nanosTimeout = theCondition.awaitNanos(nanosTimeout);
+ * else
+ * return false;
+ * }
+ * // ...
+ * }
+ * </pre>
+ *
+ * <p> Design note: This method requires a nanosecond argument so
+ * as to avoid truncation errors in reporting remaining times.
+ * Such precision loss would make it difficult for programmers to
+ * ensure that total waiting times are not systematically shorter
+ * than specified when re-waits occur.
+ *
+ * <p><b>Implementation Considerations</b>
+ *
+ * <p>The current thread is assumed to hold the lock associated with this
+ * {@code Condition} when this method is called.
+ * It is up to the implementation to determine if this is
+ * the case and if not, how to respond. Typically, an exception will be
+ * thrown (such as {@link IllegalMonitorStateException}) and the
+ * implementation must document that fact.
+ *
+ * <p>An implementation can favor responding to an interrupt over normal
+ * method return in response to a signal, or over indicating the elapse
+ * of the specified waiting time. In either case the implementation
+ * must ensure that the signal is redirected to another waiting thread, if
+ * there is one.
+ *
+ * @param nanosTimeout the maximum time to wait, in nanoseconds
+ * @return an estimate of the {@code nanosTimeout} value minus
+ * the time spent waiting upon return from this method.
+ * A positive value may be used as the argument to a
+ * subsequent call to this method to finish waiting out
+ * the desired time. A value less than or equal to zero
+ * indicates that no time remains.
+ * @throws InterruptedException if the current thread is interrupted
+ * (and interruption of thread suspension is supported)
+ */
+ long awaitNanos(long nanosTimeout) throws InterruptedException;
+
+ /**
+ * Causes the current thread to wait until it is signalled or interrupted,
+ * or the specified waiting time elapses. This method is behaviorally
+ * equivalent to:<br>
+ * <pre>
+ * awaitNanos(unit.toNanos(time)) > 0
+ * </pre>
+ * @param time the maximum time to wait
+ * @param unit the time unit of the {@code time} argument
+ * @return {@code false} if the waiting time detectably elapsed
+ * before return from the method, else {@code true}
+ * @throws InterruptedException if the current thread is interrupted
+ * (and interruption of thread suspension is supported)
+ */
+ //boolean await(long time, TimeUnit unit) throws InterruptedException;
+
+ /**
+ * Causes the current thread to wait until it is signalled or interrupted,
+ * or the specified deadline elapses.
+ *
+ * <p>The lock associated with this condition is atomically
+ * released and the current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until <em>one</em> of five things happens:
+ * <ul>
+ * <li>Some other thread invokes the {@link #signal} method for this
+ * {@code Condition} and the current thread happens to be chosen as the
+ * thread to be awakened; or
+ * <li>Some other thread invokes the {@link #signalAll} method for this
+ * {@code Condition}; or
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
+ * current thread, and interruption of thread suspension is supported; or
+ * <li>The specified deadline elapses; or
+ * <li>A "<em>spurious wakeup</em>" occurs.
+ * </ul>
+ *
+ * <p>In all cases, before this method can return the current thread must
+ * re-acquire the lock associated with this condition. When the
+ * thread returns it is <em>guaranteed</em> to hold this lock.
+ *
+ *
+ * <p>If the current thread:
+ * <ul>
+ * <li>has its interrupted status set on entry to this method; or
+ * <li>is {@linkplain Thread#interrupt interrupted} while waiting
+ * and interruption of thread suspension is supported,
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared. It is not specified, in the first
+ * case, whether or not the test for interruption occurs before the lock
+ * is released.
+ *
+ *
+ * <p>The return value indicates whether the deadline has elapsed,
+ * which can be used as follows:
+ * <pre>
+ * synchronized boolean aMethod(Date deadline) {
+ * boolean stillWaiting = true;
+ * while (!conditionBeingWaitedFor) {
+ * if (stillWaiting)
+ * stillWaiting = theCondition.awaitUntil(deadline);
+ * else
+ * return false;
+ * }
+ * // ...
+ * }
+ * </pre>
+ *
+ * <p><b>Implementation Considerations</b>
+ *
+ * <p>The current thread is assumed to hold the lock associated with this
+ * {@code Condition} when this method is called.
+ * It is up to the implementation to determine if this is
+ * the case and if not, how to respond. Typically, an exception will be
+ * thrown (such as {@link IllegalMonitorStateException}) and the
+ * implementation must document that fact.
+ *
+ * <p>An implementation can favor responding to an interrupt over normal
+ * method return in response to a signal, or over indicating the passing
+ * of the specified deadline. In either case the implementation
+ * must ensure that the signal is redirected to another waiting thread, if
+ * there is one.
+ *
+ * @param deadline the absolute time to wait until
+ * @return {@code false} if the deadline has elapsed upon return, else
+ * {@code true}
+ * @throws InterruptedException if the current thread is interrupted
+ * (and interruption of thread suspension is supported)
+ */
+ boolean awaitUntil(Date deadline) throws InterruptedException;
+
+ /**
+ * Wakes up one waiting thread.
+ *
+ * <p>If any threads are waiting on this condition then one
+ * is selected for waking up. That thread must then re-acquire the
+ * lock before returning from {@code await}.
+ */
+ void signal();
+
+ /**
+ * Wakes up all waiting threads.
+ *
+ * <p>If any threads are waiting on this condition then they are
+ * all woken up. Each thread must re-acquire the lock before it can
+ * return from {@code await}.
+ */
+ void signalAll();
+}
--- /dev/null
+/*
+ * Written by Doug Lea and Josh Bloch with assistance from members of
+ * JCP JSR-166 Expert Group and released to the public domain, as explained
+ * at http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util;
+
+/**
+ * A linear collection that supports element insertion and removal at
+ * both ends. The name <i>deque</i> is short for "double ended queue"
+ * and is usually pronounced "deck". Most <tt>Deque</tt>
+ * implementations place no fixed limits on the number of elements
+ * they may contain, but this interface supports capacity-restricted
+ * deques as well as those with no fixed size limit.
+ *
+ * <p>This interface defines methods to access the elements at both
+ * ends of the deque. Methods are provided to insert, remove, and
+ * examine the element. Each of these methods exists in two forms:
+ * one throws an exception if the operation fails, the other returns a
+ * special value (either <tt>null</tt> or <tt>false</tt>, depending on
+ * the operation). The latter form of the insert operation is
+ * designed specifically for use with capacity-restricted
+ * <tt>Deque</tt> implementations; in most implementations, insert
+ * operations cannot fail.
+ *
+ * <p>The twelve methods described above are summarized in the
+ * following table:
+ *
+ * <p>
+ * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <tr>
+ * <td></td>
+ * <td ALIGN=CENTER COLSPAN = 2> <b>First Element (Head)</b></td>
+ * <td ALIGN=CENTER COLSPAN = 2> <b>Last Element (Tail)</b></td>
+ * </tr>
+ * <tr>
+ * <td></td>
+ * <td ALIGN=CENTER><em>Throws exception</em></td>
+ * <td ALIGN=CENTER><em>Special value</em></td>
+ * <td ALIGN=CENTER><em>Throws exception</em></td>
+ * <td ALIGN=CENTER><em>Special value</em></td>
+ * </tr>
+ * <tr>
+ * <td><b>Insert</b></td>
+ * <td>{@link #addFirst addFirst(e)}</td>
+ * <td>{@link #offerFirst offerFirst(e)}</td>
+ * <td>{@link #addLast addLast(e)}</td>
+ * <td>{@link #offerLast offerLast(e)}</td>
+ * </tr>
+ * <tr>
+ * <td><b>Remove</b></td>
+ * <td>{@link #removeFirst removeFirst()}</td>
+ * <td>{@link #pollFirst pollFirst()}</td>
+ * <td>{@link #removeLast removeLast()}</td>
+ * <td>{@link #pollLast pollLast()}</td>
+ * </tr>
+ * <tr>
+ * <td><b>Examine</b></td>
+ * <td>{@link #getFirst getFirst()}</td>
+ * <td>{@link #peekFirst peekFirst()}</td>
+ * <td>{@link #getLast getLast()}</td>
+ * <td>{@link #peekLast peekLast()}</td>
+ * </tr>
+ * </table>
+ *
+ * <p>This interface extends the {@link Queue} interface. When a deque is
+ * used as a queue, FIFO (First-In-First-Out) behavior results. Elements are
+ * added at the end of the deque and removed from the beginning. The methods
+ * inherited from the <tt>Queue</tt> interface are precisely equivalent to
+ * <tt>Deque</tt> methods as indicated in the following table:
+ *
+ * <p>
+ * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <tr>
+ * <td ALIGN=CENTER> <b><tt>Queue</tt> Method</b></td>
+ * <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td>
+ * </tr>
+ * <tr>
+ * <td>{@link java.util.Queue#add add(e)}</td>
+ * <td>{@link #addLast addLast(e)}</td>
+ * </tr>
+ * <tr>
+ * <td>{@link java.util.Queue#offer offer(e)}</td>
+ * <td>{@link #offerLast offerLast(e)}</td>
+ * </tr>
+ * <tr>
+ * <td>{@link java.util.Queue#remove remove()}</td>
+ * <td>{@link #removeFirst removeFirst()}</td>
+ * </tr>
+ * <tr>
+ * <td>{@link java.util.Queue#poll poll()}</td>
+ * <td>{@link #pollFirst pollFirst()}</td>
+ * </tr>
+ * <tr>
+ * <td>{@link java.util.Queue#element element()}</td>
+ * <td>{@link #getFirst getFirst()}</td>
+ * </tr>
+ * <tr>
+ * <td>{@link java.util.Queue#peek peek()}</td>
+ * <td>{@link #peek peekFirst()}</td>
+ * </tr>
+ * </table>
+ *
+ * <p>Deques can also be used as LIFO (Last-In-First-Out) stacks. This
+ * interface should be used in preference to the legacy {@link Stack} class.
+ * When a deque is used as a stack, elements are pushed and popped from the
+ * beginning of the deque. Stack methods are precisely equivalent to
+ * <tt>Deque</tt> methods as indicated in the table below:
+ *
+ * <p>
+ * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <tr>
+ * <td ALIGN=CENTER> <b>Stack Method</b></td>
+ * <td ALIGN=CENTER> <b>Equivalent <tt>Deque</tt> Method</b></td>
+ * </tr>
+ * <tr>
+ * <td>{@link #push push(e)}</td>
+ * <td>{@link #addFirst addFirst(e)}</td>
+ * </tr>
+ * <tr>
+ * <td>{@link #pop pop()}</td>
+ * <td>{@link #removeFirst removeFirst()}</td>
+ * </tr>
+ * <tr>
+ * <td>{@link #peek peek()}</td>
+ * <td>{@link #peekFirst peekFirst()}</td>
+ * </tr>
+ * </table>
+ *
+ * <p>Note that the {@link #peek peek} method works equally well when
+ * a deque is used as a queue or a stack; in either case, elements are
+ * drawn from the beginning of the deque.
+ *
+ * <p>This interface provides two methods to remove interior
+ * elements, {@link #removeFirstOccurrence removeFirstOccurrence} and
+ * {@link #removeLastOccurrence removeLastOccurrence}.
+ *
+ * <p>Unlike the {@link List} interface, this interface does not
+ * provide support for indexed access to elements.
+ *
+ * <p>While <tt>Deque</tt> implementations are not strictly required
+ * to prohibit the insertion of null elements, they are strongly
+ * encouraged to do so. Users of any <tt>Deque</tt> implementations
+ * that do allow null elements are strongly encouraged <i>not</i> to
+ * take advantage of the ability to insert nulls. This is so because
+ * <tt>null</tt> is used as a special return value by various methods
+ * to indicated that the deque is empty.
+ *
+ * <p><tt>Deque</tt> implementations generally do not define
+ * element-based versions of the <tt>equals</tt> and <tt>hashCode</tt>
+ * methods, but instead inherit the identity-based versions from class
+ * <tt>Object</tt>.
+ *
+ * <p>This interface is a member of the <a
+ * href="{@docRoot}/../technotes/guides/collections/index.html"> Java Collections
+ * Framework</a>.
+ *
+ * @author Doug Lea
+ * @author Josh Bloch
+ * @since 1.6
+ * @param <E> the type of elements held in this collection
+ */
+
+//public interface Deque<E> extends Queue<E> {
+public interface Deque extends Queue {
+
+ /**
+ * Inserts the specified element at the front of this deque if it is
+ * possible to do so immediately without violating capacity restrictions.
+ * When using a capacity-restricted deque, it is generally preferable to
+ * use method {@link #offerFirst}.
+ *
+ * @param e the element to add
+ * @throws IllegalStateException if the element cannot be added at this
+ * time due to capacity restrictions
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this deque
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements
+ * @throws IllegalArgumentException if some property of the specified
+ * element prevents it from being added to this deque
+ */
+ void addFirst(Object/*E*/ e);
+
+ /**
+ * Inserts the specified element at the end of this deque if it is
+ * possible to do so immediately without violating capacity restrictions.
+ * When using a capacity-restricted deque, it is generally preferable to
+ * use method {@link #offerLast}.
+ *
+ * <p>This method is equivalent to {@link #add}.
+ *
+ * @param e the element to add
+ * @throws IllegalStateException if the element cannot be added at this
+ * time due to capacity restrictions
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this deque
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements
+ * @throws IllegalArgumentException if some property of the specified
+ * element prevents it from being added to this deque
+ */
+ void addLast(Object/*E*/ e);
+
+ /**
+ * Inserts the specified element at the front of this deque unless it would
+ * violate capacity restrictions. When using a capacity-restricted deque,
+ * this method is generally preferable to the {@link #addFirst} method,
+ * which can fail to insert an element only by throwing an exception.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> if the element was added to this deque, else
+ * <tt>false</tt>
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this deque
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements
+ * @throws IllegalArgumentException if some property of the specified
+ * element prevents it from being added to this deque
+ */
+ boolean offerFirst(Object/*E*/ e);
+
+ /**
+ * Inserts the specified element at the end of this deque unless it would
+ * violate capacity restrictions. When using a capacity-restricted deque,
+ * this method is generally preferable to the {@link #addLast} method,
+ * which can fail to insert an element only by throwing an exception.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> if the element was added to this deque, else
+ * <tt>false</tt>
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this deque
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements
+ * @throws IllegalArgumentException if some property of the specified
+ * element prevents it from being added to this deque
+ */
+ boolean offerLast(Object/*E*/ e);
+
+ /**
+ * Retrieves and removes the first element of this deque. This method
+ * differs from {@link #pollFirst pollFirst} only in that it throws an
+ * exception if this deque is empty.
+ *
+ * @return the head of this deque
+ * @throws NoSuchElementException if this deque is empty
+ */
+ Object/*E*/ removeFirst();
+
+ /**
+ * Retrieves and removes the last element of this deque. This method
+ * differs from {@link #pollLast pollLast} only in that it throws an
+ * exception if this deque is empty.
+ *
+ * @return the tail of this deque
+ * @throws NoSuchElementException if this deque is empty
+ */
+ Object/*E*/ removeLast();
+
+ /**
+ * Retrieves and removes the first element of this deque,
+ * or returns <tt>null</tt> if this deque is empty.
+ *
+ * @return the head of this deque, or <tt>null</tt> if this deque is empty
+ */
+ Object/*E*/ pollFirst();
+
+ /**
+ * Retrieves and removes the last element of this deque,
+ * or returns <tt>null</tt> if this deque is empty.
+ *
+ * @return the tail of this deque, or <tt>null</tt> if this deque is empty
+ */
+ Object/*E*/ pollLast();
+
+ /**
+ * Retrieves, but does not remove, the first element of this deque.
+ *
+ * This method differs from {@link #peekFirst peekFirst} only in that it
+ * throws an exception if this deque is empty.
+ *
+ * @return the head of this deque
+ * @throws NoSuchElementException if this deque is empty
+ */
+ Object/*E*/ getFirst();
+
+ /**
+ * Retrieves, but does not remove, the last element of this deque.
+ * This method differs from {@link #peekLast peekLast} only in that it
+ * throws an exception if this deque is empty.
+ *
+ * @return the tail of this deque
+ * @throws NoSuchElementException if this deque is empty
+ */
+ Object/*E*/ getLast();
+
+ /**
+ * Retrieves, but does not remove, the first element of this deque,
+ * or returns <tt>null</tt> if this deque is empty.
+ *
+ * @return the head of this deque, or <tt>null</tt> if this deque is empty
+ */
+ Object/*E*/ peekFirst();
+
+ /**
+ * Retrieves, but does not remove, the last element of this deque,
+ * or returns <tt>null</tt> if this deque is empty.
+ *
+ * @return the tail of this deque, or <tt>null</tt> if this deque is empty
+ */
+ Object/*E*/ peekLast();
+
+ /**
+ * Removes the first occurrence of the specified element from this deque.
+ * If the deque does not contain the element, it is unchanged.
+ * More formally, removes the first element <tt>e</tt> such that
+ * <tt>(o==null ? e==null : o.equals(e))</tt>
+ * (if such an element exists).
+ * Returns <tt>true</tt> if this deque contained the specified element
+ * (or equivalently, if this deque changed as a result of the call).
+ *
+ * @param o element to be removed from this deque, if present
+ * @return <tt>true</tt> if an element was removed as a result of this call
+ * @throws ClassCastException if the class of the specified element
+ * is incompatible with this deque (optional)
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements (optional)
+ */
+ boolean removeFirstOccurrence(Object o);
+
+ /**
+ * Removes the last occurrence of the specified element from this deque.
+ * If the deque does not contain the element, it is unchanged.
+ * More formally, removes the last element <tt>e</tt> such that
+ * <tt>(o==null ? e==null : o.equals(e))</tt>
+ * (if such an element exists).
+ * Returns <tt>true</tt> if this deque contained the specified element
+ * (or equivalently, if this deque changed as a result of the call).
+ *
+ * @param o element to be removed from this deque, if present
+ * @return <tt>true</tt> if an element was removed as a result of this call
+ * @throws ClassCastException if the class of the specified element
+ * is incompatible with this deque (optional)
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements (optional)
+ */
+ boolean removeLastOccurrence(Object o);
+
+ // *** Queue methods ***
+
+ /**
+ * Inserts the specified element into the queue represented by this deque
+ * (in other words, at the tail of this deque) if it is possible to do so
+ * immediately without violating capacity restrictions, returning
+ * <tt>true</tt> upon success and throwing an
+ * <tt>IllegalStateException</tt> if no space is currently available.
+ * When using a capacity-restricted deque, it is generally preferable to
+ * use {@link #offer(Object) offer}.
+ *
+ * <p>This method is equivalent to {@link #addLast}.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> (as specified by {@link Collection#add})
+ * @throws IllegalStateException if the element cannot be added at this
+ * time due to capacity restrictions
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this deque
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements
+ * @throws IllegalArgumentException if some property of the specified
+ * element prevents it from being added to this deque
+ */
+ boolean add(Object/*E*/ e);
+
+ /**
+ * Inserts the specified element into the queue represented by this deque
+ * (in other words, at the tail of this deque) if it is possible to do so
+ * immediately without violating capacity restrictions, returning
+ * <tt>true</tt> upon success and <tt>false</tt> if no space is currently
+ * available. When using a capacity-restricted deque, this method is
+ * generally preferable to the {@link #add} method, which can fail to
+ * insert an element only by throwing an exception.
+ *
+ * <p>This method is equivalent to {@link #offerLast}.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> if the element was added to this deque, else
+ * <tt>false</tt>
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this deque
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements
+ * @throws IllegalArgumentException if some property of the specified
+ * element prevents it from being added to this deque
+ */
+ boolean offer(Object/*E*/ e);
+
+ /**
+ * Retrieves and removes the head of the queue represented by this deque
+ * (in other words, the first element of this deque).
+ * This method differs from {@link #poll poll} only in that it throws an
+ * exception if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #removeFirst()}.
+ *
+ * @return the head of the queue represented by this deque
+ * @throws NoSuchElementException if this deque is empty
+ */
+ Object/*E*/ remove();
+
+ /**
+ * Retrieves and removes the head of the queue represented by this deque
+ * (in other words, the first element of this deque), or returns
+ * <tt>null</tt> if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #pollFirst()}.
+ *
+ * @return the first element of this deque, or <tt>null</tt> if
+ * this deque is empty
+ */
+ Object/*E*/ poll();
+
+ /**
+ * Retrieves, but does not remove, the head of the queue represented by
+ * this deque (in other words, the first element of this deque).
+ * This method differs from {@link #peek peek} only in that it throws an
+ * exception if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #getFirst()}.
+ *
+ * @return the head of the queue represented by this deque
+ * @throws NoSuchElementException if this deque is empty
+ */
+ Object/*E*/ element();
+
+ /**
+ * Retrieves, but does not remove, the head of the queue represented by
+ * this deque (in other words, the first element of this deque), or
+ * returns <tt>null</tt> if this deque is empty.
+ *
+ * <p>This method is equivalent to {@link #peekFirst()}.
+ *
+ * @return the head of the queue represented by this deque, or
+ * <tt>null</tt> if this deque is empty
+ */
+ Object/*E*/ peek();
+
+
+ // *** Stack methods ***
+
+ /**
+ * Pushes an element onto the stack represented by this deque (in other
+ * words, at the head of this deque) if it is possible to do so
+ * immediately without violating capacity restrictions, returning
+ * <tt>true</tt> upon success and throwing an
+ * <tt>IllegalStateException</tt> if no space is currently available.
+ *
+ * <p>This method is equivalent to {@link #addFirst}.
+ *
+ * @param e the element to push
+ * @throws IllegalStateException if the element cannot be added at this
+ * time due to capacity restrictions
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this deque
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements
+ * @throws IllegalArgumentException if some property of the specified
+ * element prevents it from being added to this deque
+ */
+ void push(Object/*E*/ e);
+
+ /**
+ * Pops an element from the stack represented by this deque. In other
+ * words, removes and returns the first element of this deque.
+ *
+ * <p>This method is equivalent to {@link #removeFirst()}.
+ *
+ * @return the element at the front of this deque (which is the top
+ * of the stack represented by this deque)
+ * @throws NoSuchElementException if this deque is empty
+ */
+ Object/*E*/ pop();
+
+
+ // *** Collection methods ***
+
+ /**
+ * Removes the first occurrence of the specified element from this deque.
+ * If the deque does not contain the element, it is unchanged.
+ * More formally, removes the first element <tt>e</tt> such that
+ * <tt>(o==null ? e==null : o.equals(e))</tt>
+ * (if such an element exists).
+ * Returns <tt>true</tt> if this deque contained the specified element
+ * (or equivalently, if this deque changed as a result of the call).
+ *
+ * <p>This method is equivalent to {@link #removeFirstOccurrence}.
+ *
+ * @param o element to be removed from this deque, if present
+ * @return <tt>true</tt> if an element was removed as a result of this call
+ * @throws ClassCastException if the class of the specified element
+ * is incompatible with this deque (optional)
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements (optional)
+ */
+ boolean remove(Object o);
+
+ /**
+ * Returns <tt>true</tt> if this deque contains the specified element.
+ * More formally, returns <tt>true</tt> if and only if this deque contains
+ * at least one element <tt>e</tt> such that
+ * <tt>(o==null ? e==null : o.equals(e))</tt>.
+ *
+ * @param o element whose presence in this deque is to be tested
+ * @return <tt>true</tt> if this deque contains the specified element
+ * @throws ClassCastException if the type of the specified element
+ * is incompatible with this deque (optional)
+ * @throws NullPointerException if the specified element is null and this
+ * deque does not permit null elements (optional)
+ */
+ boolean contains(Object o);
+
+ /**
+ * Returns the number of elements in this deque.
+ *
+ * @return the number of elements in this deque
+ */
+ public int size();
+
+ /**
+ * Returns an iterator over the elements in this deque in proper sequence.
+ * The elements will be returned in order from first (head) to last (tail).
+ *
+ * @return an iterator over the elements in this deque in proper sequence
+ */
+ Iterator/*<E>*/ iterator();
+
+ /**
+ * Returns an iterator over the elements in this deque in reverse
+ * sequential order. The elements will be returned in order from
+ * last (tail) to first (head).
+ *
+ * @return an iterator over the elements in this deque in reverse
+ * sequence
+ */
+ Iterator/*<E>*/ descendingIterator();
+
+}
--- /dev/null
+/* GarbageCollectorMXBean.java - Interface for a garbage collector bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package java.lang.management;
+
+/**
+ * Provides access to information about the garbage collectors
+ * of the virtual machine. Garbage collectors are responsible
+ * for removing unreferenced objects from memory. A garbage
+ * collector is a type of memory manager, so this interface
+ * is combined with that of generic memory managers. An instance
+ * of this bean for each garbage collector is obtained by calling
+ * {@link ManagementFactory#getGarbageCollectorMXBeans()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public interface GarbageCollectorMXBean
+ extends MemoryManagerMXBean
+{
+
+ /**
+ * Returns the number of collections the garbage collector
+ * represented by this bean has made. -1 is returned if the
+ * collection count is undefined.
+ *
+ * @return the number of collections made, or -1 if this is
+ * undefined.
+ */
+ long getCollectionCount();
+
+ /**
+ * Returns the accumulated number of milliseconds this garbage
+ * collector has spent freeing the memory used by unreferenced
+ * objects. -1 is returned if the collection time is undefined.
+ * Note that the accumulated time may not change, even when the
+ * collection count increases, if the time taken is sufficiently
+ * short; this depends on the resolution of the timer used.
+ *
+ * @return the accumulated number of milliseconds spent collecting,
+ * or -1 if this is undefined.
+ */
+ long getCollectionTime();
+
+}
--- /dev/null
+public class HashSet implements Set {
+ HashMap map;
+ HashSet() {
+ map=new HashMap();
+ }
+ HashSet(int initialCapacity) {
+ map=new HashMap(initialCapacity);
+ }
+ HashSet(int initialCapacity, float loadFactor) {
+ map=new HashMap(initialCapacity, loadFactor);
+ }
+ public boolean add(Object o) {
+ return (map.put(o, this)==null);
+ }
+ public boolean addAll(Collection c) {
+ Iterator it = c.iterator();
+ while(it.hasNext()) {
+ if(!this.add(it.next())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ public boolean remove(Object o) {
+ return (map.remove(o)!=null);
+ }
+ boolean removeAll(Collection c) {
+ Iterator it = c.iterator();
+ while(it.hasNext()) {
+ if(!this.remove(it.next())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ public boolean isEmpty() {
+ return map.isEmpty();
+ }
+ public void clear() {
+ map.clear();
+ }
+ public boolean contains(Object o) {
+ return map.containsKey(o);
+ }
+ public boolean containsAll(Collection c) {
+ Iterator it = c.iterator();
+ while(it.hasNext()) {
+ if(!this.contains(it.next())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ public int size() {
+ return map.size();
+ }
+ public Iterator iterator() {
+ return map.iterator(0);
+ }
+}
--- /dev/null
+/* Iterable.java -- Notes collection over which one may iterate
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.lang;
+
+// We only need Iterator, but we import * to support lib/mkcollections.pl
+import java.util.*;
+
+/**
+ * This interface is used to indicate that a given class can be
+ * iterated over. The compiler uses this interface to determine which
+ * classes are suitable targets of the <code>foreach</code> construct.
+ *
+ * @author Tom Tromey <tromey@redhat.com>
+ * @since 1.5
+ */
+public interface Iterable//<E>
+{
+ /**
+ * Returns an iterator for the collection.
+ *
+ * @return an iterator.
+ */
+ Iterator/*<E>*/ iterator ();
+}
--- /dev/null
+/* Iterator.java -- Interface for iterating over collections
+ Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.util;
+
+/**
+ * An object which iterates over a collection. An Iterator is used to return
+ * the items once only, in sequence, by successive calls to the next method.
+ * It is also possible to remove elements from the underlying collection by
+ * using the optional remove method. Iterator is intended as a replacement
+ * for the Enumeration interface of previous versions of Java, which did not
+ * have the remove method and had less conveniently named methods.
+ *
+ * @author Original author unknown
+ * @author Eric Blake (ebb9@email.byu.edu)
+ * @see Collection
+ * @see ListIterator
+ * @see Enumeration
+ * @since 1.2
+ * @status updated to 1.4
+ */
+public interface Iterator/*<E>*/
+{
+ /**
+ * Tests whether there are elements remaining in the collection. In other
+ * words, calling <code>next()</code> will not throw an exception.
+ *
+ * @return true if there is at least one more element in the collection
+ */
+ boolean hasNext();
+
+ /**
+ * Obtain the next element in the collection.
+ *
+ * @return the next element in the collection
+ * @throws NoSuchElementException if there are no more elements
+ */
+ Object/*E*/ next();
+
+ /**
+ * Remove from the underlying collection the last element returned by next
+ * (optional operation). This method can be called only once after each
+ * call to <code>next()</code>. It does not affect what will be returned
+ * by subsequent calls to next.
+ *
+ * @throws IllegalStateException if next has not yet been called or remove
+ * has already been called since the last call to next.
+ * @throws UnsupportedOperationException if this Iterator does not support
+ * the remove operation.
+ */
+ void remove();
+}
--- /dev/null
+public class LinkedListElement {
+ public LinkedListElement next;
+ public LinkedListElement prev;
+ public Object element;
+
+ public LinkedListElement(Object e,
+ LinkedListElement n,
+ LinkedListElement p) {
+ element = e;
+ next = n;
+ prev = p;
+ }
+}
+
+public class LinkedList implements Queue {
+ LinkedListElement head;
+ LinkedListElement tail;
+ int size;
+
+ public LinkedList() {
+ clear();
+ }
+
+ public void add(Object o) {
+ if( tail == null ) {
+ head = new LinkedListElement(o, null, null);
+ tail = head;
+
+ } else {
+ tail.next = new LinkedListElement(o, null, tail);
+ tail = tail.next;
+ }
+ size++;
+ }
+
+ public void addFirst(Object o) {
+ if( head == null ) {
+ head = new LinkedListElement(o, null, null);
+ tail = head;
+
+ } else {
+ head.prev = new LinkedListElement(o, head, null);
+ head = head.prev;
+ }
+ size++;
+ }
+
+ public void addLast(Object o) {
+ add(o);
+ }
+
+ public void clear() {
+ head = null;
+ tail = null;
+ size = 0;
+ }
+
+ public int size() {
+ return size;
+ }
+
+ public boolean isEmpty() {
+ return size == 0;
+ }
+
+ public Object clone() {
+ System.out.println("LinkedList.clone() not implemented.");
+ System.exit(-1);
+ }
+
+ public boolean contains(Object o) {
+ LinkedListElement e = head;
+ if (o==null) {
+ while(e!=null) {
+ if (e.element==null) {
+ return true;
+ }
+ e=e.next;
+ }
+ return false;
+ } else {
+ while( e != null ) {
+ if (o.equals(e.element)) {
+ return true;
+ }
+ e = e.next;
+ }
+ }
+ return false;
+ }
+
+ public Object getFirst() {
+ if( head == null ) {
+ return null;
+ }
+ return head.element;
+ }
+
+ public Object getLast() {
+ if( tail == null ) {
+ return null;
+ }
+ return tail.element;
+ }
+
+ public Object element() {
+ getFirst();
+ }
+
+ public Object peek() {
+ getFirst();
+ }
+
+ public Object peekFirst() {
+ getFirst();
+ }
+
+ public Object peekLast() {
+ getLast();
+ }
+
+ public Object removeFirst() {
+ if( head == null ) {
+ System.out.println("LinkedList: illegal removeFirst()");
+ System.exit(-1);
+ }
+ Object o = head.element;
+ head = head.next;
+ if( head != null ) {
+ head.prev = null;
+ } else {
+ tail = null;
+ }
+ size--;
+ return o;
+ }
+
+ public Object removeLast() {
+ if( tail == null ) {
+ System.out.println("LinkedList: illegal removeLast()");
+ System.exit(-1);
+ }
+ Object o = tail.element;
+ tail = tail.prev;
+ if( tail != null ) {
+ tail.next = null;
+ } else {
+ head = null;
+ }
+ size--;
+ return o;
+ }
+
+ public boolean remove(Object o) {
+ if( head == null ) {
+// System.out.println("LinkedList: illegal remove( Object o )");
+// System.exit(-1);
+ return false;
+ }
+ LinkedListElement e = head;
+ while (e != null) {
+ if (e.element == o) {
+ if (e.prev != null) {
+ e.prev.next = e.next;
+ }
+ if (e.next != null) {
+ e.next.prev = e.prev;
+ }
+ size--;
+ return true;
+ }
+ e = e.next;
+ }
+// System.out.println("LinkedList: illegal remove( Object o ), "+o+" not found");
+// System.exit(-1);
+ return false;
+ }
+
+ public Object pop() {
+ Object o = getFirst();
+ removeFirst();
+ return o;
+ }
+
+ public void push(Object o) {
+ addFirst(o);
+ }
+
+ public Iterator iterator() {
+ return new LinkedListIterator(this);
+ }
+}
+
+public class LinkedListIterator implements Iterator {
+ LinkedList ll;
+ LinkedListElement itr;
+ Object removeable;
+
+ public LinkedListIterator(LinkedList ll) {
+ this.ll = ll;
+ itr = ll.head;
+ removeable = null;
+ }
+
+ public boolean hasNext() {
+ return itr != null;
+ }
+
+ public Object next() {
+ if( itr == null ) {
+ System.out.println("LinkedListIterator: illegal next()");
+ System.exit(-1);
+ }
+ removeable = itr.element;
+ itr = itr.next;
+ return removeable;
+ }
+
+ public void remove() {
+ if( removeable == null ) {
+ System.out.println("LinkedListIterator: illegal remove()");
+ System.exit(-1);
+ }
+ ll.remove(removeable);
+ removeable = null;
+ }
+}
--- /dev/null
+/* List.java -- An ordered collection which allows indexed access
+ Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.util;
+
+/**
+ * An ordered collection (also known as a list). This collection allows
+ * access to elements by position, as well as control on where elements
+ * are inserted. Unlike sets, duplicate elements are permitted by this
+ * general contract (if a subclass forbids duplicates, this should be
+ * documented).
+ * <p>
+ *
+ * List places additional requirements on <code>iterator</code>,
+ * <code>add</code>, <code>remove</code>, <code>equals</code>, and
+ * <code>hashCode</code>, in addition to requiring more methods. List
+ * indexing is 0-based (like arrays), although some implementations may
+ * require time proportional to the index to obtain an arbitrary element.
+ * The List interface is incompatible with Set; you cannot implement both
+ * simultaneously.
+ * <p>
+ *
+ * Lists also provide a <code>ListIterator</code> which allows bidirectional
+ * traversal and other features atop regular iterators. Lists can be
+ * searched for arbitrary elements, and allow easy insertion and removal
+ * of multiple elements in one method call.
+ * <p>
+ *
+ * Note: While lists may contain themselves as elements, this leads to
+ * undefined (usually infinite recursive) behavior for some methods like
+ * hashCode or equals.
+ *
+ * @author Original author unknown
+ * @author Eric Blake (ebb9@email.byu.edu)
+ * @see Collection
+ * @see Set
+ * @see ArrayList
+ * @see LinkedList
+ * @see Vector
+ * @see Arrays#asList(Object[])
+ * @see Collections#nCopies(int, Object)
+ * @see Collections#EMPTY_LIST
+ * @see AbstractList
+ * @see AbstractSequentialList
+ * @since 1.2
+ * @status updated to 1.4
+ */
+public interface List/*<E>*/ extends Collection//<E>
+{
+ /**
+ * Insert an element into the list at a given position (optional operation).
+ * This shifts all existing elements from that position to the end one
+ * index to the right. This version of add has no return, since it is
+ * assumed to always succeed if there is no exception.
+ *
+ * @param index the location to insert the item
+ * @param o the object to insert
+ * @throws UnsupportedOperationException if this list does not support the
+ * add operation
+ * @throws IndexOutOfBoundsException if index < 0 || index > size()
+ * @throws ClassCastException if o cannot be added to this list due to its
+ * type
+ * @throws IllegalArgumentException if o cannot be added to this list for
+ * some other reason
+ * @throws NullPointerException if o is null and this list doesn't support
+ * the addition of null values.
+ */
+ void add(int index, Object/*E*/ o);
+
+ /**
+ * Add an element to the end of the list (optional operation). If the list
+ * imposes restraints on what can be inserted, such as no null elements,
+ * this should be documented.
+ *
+ * @param o the object to add
+ * @return true, as defined by Collection for a modified list
+ * @throws UnsupportedOperationException if this list does not support the
+ * add operation
+ * @throws ClassCastException if o cannot be added to this list due to its
+ * type
+ * @throws IllegalArgumentException if o cannot be added to this list for
+ * some other reason
+ * @throws NullPointerException if o is null and this list doesn't support
+ * the addition of null values.
+ */
+ boolean add(Object/*E*/ o);
+
+ /**
+ * Insert the contents of a collection into the list at a given position
+ * (optional operation). Shift all elements at that position to the right
+ * by the number of elements inserted. This operation is undefined if
+ * this list is modified during the operation (for example, if you try
+ * to insert a list into itself).
+ *
+ * @param index the location to insert the collection
+ * @param c the collection to insert
+ * @return true if the list was modified by this action, that is, if c is
+ * non-empty
+ * @throws UnsupportedOperationException if this list does not support the
+ * addAll operation
+ * @throws IndexOutOfBoundsException if index < 0 || index > size()
+ * @throws ClassCastException if some element of c cannot be added to this
+ * list due to its type
+ * @throws IllegalArgumentException if some element of c cannot be added
+ * to this list for some other reason
+ * @throws NullPointerException if some element of c is null and this list
+ * doesn't support the addition of null values.
+ * @throws NullPointerException if the specified collection is null
+ * @see #add(int, Object)
+ */
+ boolean addAll(int index, Collection/*<? extends E>*/ c);
+
+ /**
+ * Add the contents of a collection to the end of the list (optional
+ * operation). This operation is undefined if this list is modified
+ * during the operation (for example, if you try to insert a list into
+ * itself).
+ *
+ * @param c the collection to add
+ * @return true if the list was modified by this action, that is, if c is
+ * non-empty
+ * @throws UnsupportedOperationException if this list does not support the
+ * addAll operation
+ * @throws ClassCastException if some element of c cannot be added to this
+ * list due to its type
+ * @throws IllegalArgumentException if some element of c cannot be added
+ * to this list for some other reason
+ * @throws NullPointerException if the specified collection is null
+ * @throws NullPointerException if some element of c is null and this list
+ * doesn't support the addition of null values.
+ * @see #add(Object)
+ */
+ boolean addAll(Collection/*<? extends E>*/ c);
+
+ /**
+ * Clear the list, such that a subsequent call to isEmpty() would return
+ * true (optional operation).
+ *
+ * @throws UnsupportedOperationException if this list does not support the
+ * clear operation
+ */
+ void clear();
+
+ /**
+ * Test whether this list contains a given object as one of its elements.
+ * This is defined as the existence of an element e such that
+ * <code>o == null ? e == null : o.equals(e)</code>.
+ *
+ * @param o the element to look for
+ * @return true if this list contains the element
+ * @throws ClassCastException if the type of o is not a valid type
+ * for this list.
+ * @throws NullPointerException if o is null and the list doesn't
+ * support null values.
+ */
+ boolean contains(Object o);
+
+ /**
+ * Test whether this list contains every element in a given collection.
+ *
+ * @param c the collection to test for
+ * @return true if for every element o in c, contains(o) would return true
+ * @throws NullPointerException if the collection is null
+ * @throws ClassCastException if the type of any element in c is not a valid
+ * type for this list.
+ * @throws NullPointerException if some element of c is null and this
+ * list does not support null values.
+ * @see #contains(Object)
+ */
+ boolean containsAll(Collection/*<?>*/ c);
+
+ /**
+ * Test whether this list is equal to another object. A List is defined to be
+ * equal to an object if and only if that object is also a List, and the two
+ * lists have the same sequence. Two lists l1 and l2 are equal if and only
+ * if <code>l1.size() == l2.size()</code>, and for every integer n between 0
+ * and <code>l1.size() - 1</code> inclusive, <code>l1.get(n) == null ?
+ * l2.get(n) == null : l1.get(n).equals(l2.get(n))</code>.
+ *
+ * @param o the object to test for equality with this list
+ * @return true if o is equal to this list
+ * @see Object#equals(Object)
+ * @see #hashCode()
+ */
+ boolean equals(Object o);
+
+ /**
+ * Get the element at a given index in this list.
+ *
+ * @param index the index of the element to be returned
+ * @return the element at index index in this list
+ * @throws IndexOutOfBoundsException if index < 0 || index >= size()
+ */
+ Object/*E*/ get(int index);
+
+ /**
+ * Obtains a hash code for this list. In order to obey the general
+ * contract of the hashCode method of class Object, this value is
+ * calculated as follows:
+ *
+<p><pre>hashCode = 1;
+Iterator i = list.iterator();
+while (i.hasNext())
+{
+ Object obj = i.next();
+ hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
+}</pre>
+ *
+ * <p>This ensures that the general contract of Object.hashCode()
+ * is adhered to.
+ *
+ * @return the hash code of this list
+ * @see Object#hashCode()
+ * @see #equals(Object)
+ */
+ int hashCode();
+
+ /**
+ * Obtain the first index at which a given object is to be found in this
+ * list.
+ *
+ * @param o the object to search for
+ * @return the least integer n such that <code>o == null ? get(n) == null :
+ * o.equals(get(n))</code>, or -1 if there is no such index.
+ * @throws ClassCastException if the type of o is not a valid
+ * type for this list.
+ * @throws NullPointerException if o is null and this
+ * list does not support null values.
+ */
+ int indexOf(Object o);
+
+ /**
+ * Test whether this list is empty, that is, if size() == 0.
+ *
+ * @return true if this list contains no elements
+ */
+ boolean isEmpty();
+
+ /**
+ * Obtain an Iterator over this list, whose sequence is the list order.
+ *
+ * @return an Iterator over the elements of this list, in order
+ */
+ Iterator/*<E>*/ iterator();
+
+ /**
+ * Obtain the last index at which a given object is to be found in this
+ * list.
+ *
+ * @return the greatest integer n such that <code>o == null ? get(n) == null
+ * : o.equals(get(n))</code>, or -1 if there is no such index.
+ * @throws ClassCastException if the type of o is not a valid
+ * type for this list.
+ * @throws NullPointerException if o is null and this
+ * list does not support null values.
+ */
+ int lastIndexOf(Object o);
+
+ /**
+ * Obtain a ListIterator over this list, starting at the beginning.
+ *
+ * @return a ListIterator over the elements of this list, in order, starting
+ * at the beginning
+ */
+ ListIterator/*<E>*/ listIterator();
+
+ /**
+ * Obtain a ListIterator over this list, starting at a given position.
+ * A first call to next() would return the same as get(index), and a
+ * first call to previous() would return the same as get(index - 1).
+ *
+ * @param index the position, between 0 and size() inclusive, to begin the
+ * iteration from
+ * @return a ListIterator over the elements of this list, in order, starting
+ * at index
+ * @throws IndexOutOfBoundsException if index < 0 || index > size()
+ */
+ ListIterator/*<E>*/ listIterator(int index);
+
+ /**
+ * Remove the element at a given position in this list (optional operation).
+ * Shifts all remaining elements to the left to fill the gap.
+ *
+ * @param index the position within the list of the object to remove
+ * @return the object that was removed
+ * @throws UnsupportedOperationException if this list does not support the
+ * remove operation
+ * @throws IndexOutOfBoundsException if index < 0 || index >= size()
+ */
+ Object/*E*/ remove(int index);
+
+ /**
+ * Remove the first occurence of an object from this list (optional
+ * operation). That is, remove the first element e such that
+ * <code>o == null ? e == null : o.equals(e)</code>.
+ *
+ * @param o the object to remove
+ * @return true if the list changed as a result of this call, that is, if
+ * the list contained at least one occurrence of o
+ * @throws UnsupportedOperationException if this list does not support the
+ * remove operation
+ * @throws ClassCastException if the type of o is not a valid
+ * type for this list.
+ * @throws NullPointerException if o is null and this
+ * list does not support removing null values.
+ */
+ //boolean remove(Object o);
+
+ /**
+ * Remove all elements of a given collection from this list (optional
+ * operation). That is, remove every element e such that c.contains(e).
+ *
+ * @param c the collection to filter out
+ * @return true if this list was modified as a result of this call
+ * @throws UnsupportedOperationException if this list does not support the
+ * removeAll operation
+ * @throws NullPointerException if the collection is null
+ * @throws ClassCastException if the type of any element in c is not a valid
+ * type for this list.
+ * @throws NullPointerException if some element of c is null and this
+ * list does not support removing null values.
+ * @see #remove(Object)
+ * @see #contains(Object)
+ */
+ boolean removeAll(Collection/*<?>*/ c);
+
+ /**
+ * Remove all elements of this list that are not contained in a given
+ * collection (optional operation). That is, remove every element e such
+ * that !c.contains(e).
+ *
+ * @param c the collection to retain
+ * @return true if this list was modified as a result of this call
+ * @throws UnsupportedOperationException if this list does not support the
+ * retainAll operation
+ * @throws NullPointerException if the collection is null
+ * @throws ClassCastException if the type of any element in c is not a valid
+ * type for this list.
+ * @throws NullPointerException if some element of c is null and this
+ * list does not support retaining null values.
+ * @see #remove(Object)
+ * @see #contains(Object)
+ */
+ boolean retainAll(Collection/*<?>*/ c);
+
+ /**
+ * Replace an element of this list with another object (optional operation).
+ *
+ * @param index the position within this list of the element to be replaced
+ * @param o the object to replace it with
+ * @return the object that was replaced
+ * @throws UnsupportedOperationException if this list does not support the
+ * set operation
+ * @throws IndexOutOfBoundsException if index < 0 || index >= size()
+ * @throws ClassCastException if o cannot be added to this list due to its
+ * type
+ * @throws IllegalArgumentException if o cannot be added to this list for
+ * some other reason
+ * @throws NullPointerException if o is null and this
+ * list does not support null values.
+ */
+ Object/*E*/ set(int index, Object/*E*/ o);
+
+ /**
+ * Get the number of elements in this list. If the list contains more
+ * than Integer.MAX_VALUE elements, return Integer.MAX_VALUE.
+ *
+ * @return the number of elements in the list
+ */
+ int size();
+
+ /**
+ * Obtain a List view of a subsection of this list, from fromIndex
+ * (inclusive) to toIndex (exclusive). If the two indices are equal, the
+ * sublist is empty. The returned list should be modifiable if and only
+ * if this list is modifiable. Changes to the returned list should be
+ * reflected in this list. If this list is structurally modified in
+ * any way other than through the returned list, the result of any subsequent
+ * operations on the returned list is undefined.
+ *
+ * @param fromIndex the index that the returned list should start from
+ * (inclusive)
+ * @param toIndex the index that the returned list should go to (exclusive)
+ * @return a List backed by a subsection of this list
+ * @throws IndexOutOfBoundsException if fromIndex < 0
+ * || toIndex > size() || fromIndex > toIndex
+ */
+ List/*<E>*/ subList(int fromIndex, int toIndex);
+
+ /**
+ * Copy the current contents of this list into an array.
+ *
+ * @return an array of type Object[] and length equal to the length of this
+ * list, containing the elements currently in this list, in order
+ */
+ Object[] toArray();
+
+ /**
+ * Copy the current contents of this list into an array. If the array passed
+ * as an argument has length less than that of this list, an array of the
+ * same run-time type as a, and length equal to the length of this list, is
+ * allocated using Reflection. Otherwise, a itself is used. The elements of
+ * this list are copied into it, and if there is space in the array, the
+ * following element is set to null. The resultant array is returned.
+ * Note: The fact that the following element is set to null is only useful
+ * if it is known that this list does not contain any null elements.
+ *
+ * @param a the array to copy this list into
+ * @return an array containing the elements currently in this list, in
+ * order
+ * @throws ArrayStoreException if the type of any element of the
+ * collection is not a subtype of the element type of a
+ * @throws NullPointerException if the specified array is null
+ */
+ /*<T> T*/Object[] toArray(Object/*T*/[] a);
+}
--- /dev/null
+/* ListIterator.java -- Extended Iterator for iterating over ordered lists
+ Copyright (C) 1998, 1999, 2001, 2004, 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.util;
+
+/**
+ * An extended version of Iterator to support the extra features of Lists. The
+ * elements may be accessed in forward or reverse order, elements may be
+ * replaced as well as removed, and new elements may be inserted, during the
+ * traversal of the list.
+ * <p>
+ *
+ * A list with n elements provides n+1 iterator positions (the front, the end,
+ * or between two elements). Note that <code>remove</code> and <code>set</code>
+ * operate on the last element returned, whether it was by <code>next</code>
+ * or <code>previous</code>.
+ *
+ * @author Original author unknown
+ * @author Eric Blake (ebb9@email.byu.edu)
+ * @see Collection
+ * @see List
+ * @see Iterator
+ * @see Enumeration
+ * @since 1.2
+ * @status updated to 1.4
+ */
+public interface ListIterator/*<E>*/ extends Iterator//<E>
+{
+ /**
+ * Tests whether there are elements remaining in the list in the forward
+ * direction. In other words, next() will not fail with a
+ * NoSuchElementException.
+ *
+ * @return true if the list continues in the forward direction
+ */
+ boolean hasNext();
+
+ /**
+ * Tests whether there are elements remaining in the list in the reverse
+ * direction. In other words, previous() will not fail with a
+ * NoSuchElementException.
+ *
+ * @return true if the list continues in the reverse direction
+ */
+ boolean hasPrevious();
+
+ /**
+ * Obtain the next element in the list in the forward direction. Repeated
+ * calls to next may be used to iterate over the entire list, or calls to
+ * next and previous may be used together to go forwards and backwards.
+ * Alternating calls to next and previous will return the same element.
+ *
+ * @return the next element in the list in the forward direction
+ * @throws NoSuchElementException if there are no more elements
+ */
+ Object/*E*/ next();
+
+ /**
+ * Obtain the next element in the list in the reverse direction. Repeated
+ * calls to previous may be used to iterate backwards over the entire list,
+ * or calls to next and previous may be used together to go forwards and
+ * backwards. Alternating calls to next and previous will return the same
+ * element.
+ *
+ * @return the next element in the list in the reverse direction
+ * @throws NoSuchElementException if there are no more elements
+ */
+ Object/*E*/ previous();
+
+ /**
+ * Find the index of the element that would be returned by a call to next.
+ * If hasNext() returns false, this returns the list size.
+ *
+ * @return the index of the element that would be returned by next()
+ */
+ int nextIndex();
+
+ /**
+ * Find the index of the element that would be returned by a call to
+ * previous. If hasPrevious() returns false, this returns -1.
+ *
+ * @return the index of the element that would be returned by previous()
+ */
+ int previousIndex();
+
+ /**
+ * Insert an element into the list at the current position of the iterator
+ * (optional operation). The element is inserted in between the element that
+ * would be returned by previous and the element that would be returned by
+ * next. After the insertion, a subsequent call to next is unaffected, but
+ * a call to previous returns the item that was added. The values returned
+ * by nextIndex() and previousIndex() are incremented.
+ *
+ * @param o the object to insert into the list
+ * @throws ClassCastException if the object is of a type which cannot be added
+ * to this list.
+ * @throws IllegalArgumentException if some other aspect of the object stops
+ * it being added to this list.
+ * @throws UnsupportedOperationException if this ListIterator does not
+ * support the add operation.
+ */
+ void add(Object/*E*/ o);
+
+ /**
+ * Remove from the list the element last returned by a call to next or
+ * previous (optional operation). This method may only be called if neither
+ * add nor remove have been called since the last call to next or previous.
+ *
+ * @throws IllegalStateException if neither next or previous have been
+ * called, or if add or remove has been called since the last call
+ * to next or previous
+ * @throws UnsupportedOperationException if this ListIterator does not
+ * support the remove operation
+ */
+ void remove();
+
+ /**
+ * Replace the element last returned by a call to next or previous with a
+ * given object (optional operation). This method may only be called if
+ * neither add nor remove have been called since the last call to next or
+ * previous.
+ *
+ * @param o the object to replace the element with
+ * @throws ClassCastException the object is of a type which cannot be added
+ * to this list
+ * @throws IllegalArgumentException some other aspect of the object stops
+ * it being added to this list
+ * @throws IllegalStateException if neither next or previous have been
+ * called, or if add or remove has been called since the last call
+ * to next or previous
+ * @throws UnsupportedOperationException if this ListIterator does not
+ * support the set operation
+ */
+ void set(Object/*E*/ o);
+}
--- /dev/null
+/* ManagementFactory.java - Factory for obtaining system beans.
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package java.lang.management;
+
+/*import gnu.classpath.SystemProperties;
+
+import gnu.java.lang.management.ClassLoadingMXBeanImpl;
+import gnu.java.lang.management.CompilationMXBeanImpl;
+import gnu.java.lang.management.GarbageCollectorMXBeanImpl;
+import gnu.java.lang.management.OperatingSystemMXBeanImpl;
+import gnu.java.lang.management.MemoryMXBeanImpl;
+import gnu.java.lang.management.MemoryManagerMXBeanImpl;
+import gnu.java.lang.management.MemoryPoolMXBeanImpl;
+import gnu.java.lang.management.RuntimeMXBeanImpl;
+import gnu.java.lang.management.ThreadMXBeanImpl;
+
+import java.io.IOException;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import java.util.logging.LogManager;
+
+import javax.management.Attribute;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.MBeanRegistrationException;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerConnection;
+import javax.management.MBeanServerFactory;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.management.NotificationEmitter;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.TabularData;*/
+
+/**
+ * <p>
+ * Provides access to the system's management beans via a series
+ * of static methods.
+ * </p>
+ * <p>
+ * An instance of a system management bean can be obtained by
+ * using one of the following methods:
+ * </p>
+ * <ol>
+ * <li>Calling the appropriate static method of this factory.
+ * </li>
+ * <li>Using the platform {@link javax.management.MBeanServer}
+ * to access the beans locally, or an
+ * {@link javax.management.MBeanServerConnection} for remote
+ * access. The attributes and operations use the limited
+ * range of data types specified below.</li>
+ * </ol>
+ * <h2>Open Data Types</h2>
+ * <p>
+ * The data types used by the management beans are restricted
+ * to <emph>open</emph> data types to aid interoperability. This
+ * allows the beans to be accessed remotely, including from non-Java
+ * clients. Below is a table which lists the types used by the beans
+ * on the left, and the types they are converted to when returned via
+ * a bean server on the right. Type information is provided for each
+ * bean by obtaining its instance of {@link javax.management.MBeanInfo}.
+ * </p>
+ * <table>
+ * <th><td>Data Type Used</td><td>Data Type Returned</td></th>
+ * <tr>
+ * <td>Primitive types (<code>int</code>, <code>char</code>, etc.)</td>
+ * <td>Same</td>
+ * </tr><tr>
+ * <td>Wrapper classes ({@link{java.lang.Integer},
+ * @link{java.lang.Character}, etc.)</td>
+ * <td>Same</td>
+ * </tr><tr>
+ * <td>An {@link java.lang.Enum}</td>
+ * <td>The <code>name</code> of the enumeration constant</td>
+ * </tr><tr>
+ * <td>An array of type <code>E</code></td>
+ * <td>An array of the same dimensions with this mapping applied
+ * to <code>E</code>.</td>
+ * </tr><tr>
+ * <td>A class with `getter' methods and a
+ * <code>from({@link javax.management.openmbean.CompositeData})</code>
+ * method.</td>
+ * <td>The equivalent {@link javax.management.openmbean.CompositeData}
+ * instance, specified by the <code>from</code> method.</td>
+ * </tr><tr>
+ * <td>A map with keys of type <code>K</code> and values of
+ * type <code>V</code>.</td>
+ * <td>A {@link javax.management.openmbean.TabularData} instance,
+ * with the row type containing two items, <code>"key"</code> and
+ * <code>"value"</code> with the types <code>K</code> and <code>V</code>
+ * respectively (with translation applied).</td>
+ * </tr><tr>
+ * <td>A list of type <code>E</code>.</td>
+ * <td>An array with this mapping applied to <code>E</code>.</td>
+ * </tr></table>
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public class ManagementFactory
+{
+
+ /**
+ * The object name for the class loading bean.
+ */
+ public static final String CLASS_LOADING_MXBEAN_NAME =
+ "java.lang:type=ClassLoading";
+
+ /**
+ * The object name for the compilation bean.
+ */
+ public static final String COMPILATION_MXBEAN_NAME =
+ "java.lang:type=Compilation";
+
+ /**
+ * The domain for the garbage collecting beans.
+ */
+ public static final String GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE =
+ "java.lang:type=GarbageCollector";
+
+ /**
+ * The domain for the memory manager beans.
+ */
+ public static final String MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE =
+ "java.lang:type=MemoryManager";
+
+ /**
+ * The object name for the memory bean.
+ */
+ public static final String MEMORY_MXBEAN_NAME =
+ "java.lang:type=Memory";
+
+ /**
+ * The domain for the memory pool beans.
+ */
+ public static final String MEMORY_POOL_MXBEAN_DOMAIN_TYPE =
+ "java.lang:type=MemoryPool";
+
+ /**
+ * The object name for the operating system bean.
+ */
+ public static final String OPERATING_SYSTEM_MXBEAN_NAME =
+ "java.lang:type=OperatingSystem";
+
+ /**
+ * The object name for the runtime bean.
+ */
+ public static final String RUNTIME_MXBEAN_NAME =
+ "java.lang:type=Runtime";
+
+ /**
+ * The object name for the threading bean.
+ */
+ public static final String THREAD_MXBEAN_NAME =
+ "java.lang:type=Threading";
+
+ /**
+ * The operating system management bean.
+ */
+ //private static OperatingSystemMXBean osBean;
+
+ /**
+ * The runtime management bean.
+ */
+ //private static RuntimeMXBean runtimeBean;
+
+ /**
+ * The class loading management bean.
+ */
+ //private static ClassLoadingMXBean classLoadingBean;
+
+ /**
+ * The thread bean.
+ */
+ //private static ThreadMXBean threadBean;
+
+ /**
+ * The memory bean.
+ */
+ //private static MemoryMXBean memoryBean;
+
+ /**
+ * The compilation bean (may remain null).
+ */
+ //private static CompilationMXBean compilationBean;
+
+ /**
+ * The platform server.
+ */
+ //private static MBeanServer platformServer;
+
+ /**
+ * Private constructor to prevent instance creation.
+ */
+ private ManagementFactory() {}
+
+ /**
+ * Returns the operating system management bean for the
+ * operating system on which the virtual machine is running.
+ *
+ * @return an instance of {@link OperatingSystemMXBean} for
+ * the underlying operating system.
+ */
+ /*public static OperatingSystemMXBean getOperatingSystemMXBean()
+ {
+ if (osBean == null)
+ try
+ {
+ osBean = new OperatingSystemMXBeanImpl();
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "operating system bean is not a " +
+ "compliant management bean.");
+ }
+ return osBean;
+ }*/
+
+ /**
+ * Returns the runtime management bean for the
+ * running virtual machine.
+ *
+ * @return an instance of {@link RuntimeMXBean} for
+ * this virtual machine.
+ */
+ /*public static RuntimeMXBean getRuntimeMXBean()
+ {
+ if (runtimeBean == null)
+ try
+ {
+ runtimeBean = new RuntimeMXBeanImpl();
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "runtime bean is not a compliant " +
+ "management bean.");
+ }
+ return runtimeBean;
+ }*/
+
+ /**
+ * Returns the class loading management bean for the
+ * running virtual machine.
+ *
+ * @return an instance of {@link ClassLoadingMXBean} for
+ * this virtual machine.
+ */
+ /*public static ClassLoadingMXBean getClassLoadingMXBean()
+ {
+ if (classLoadingBean == null)
+ try
+ {
+ classLoadingBean = new ClassLoadingMXBeanImpl();
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "class loading bean is not a " +
+ "compliant management bean.");
+ }
+ return classLoadingBean;
+ }*/
+
+ /**
+ * Returns the thread management bean for the running
+ * virtual machine.
+ *
+ * @return an instance of {@link ThreadMXBean} for
+ * this virtual machine.
+ */
+ /*public static ThreadMXBean getThreadMXBean()
+ {
+ if (threadBean == null)
+ try
+ {
+ threadBean = new ThreadMXBeanImpl();
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "thread bean is not a compliant " +
+ "management bean.");
+ }
+ return threadBean;
+ }*/
+
+ /**
+ * Returns the memory management bean for the running
+ * virtual machine.
+ *
+ * @return an instance of {@link MemoryMXBean} for
+ * this virtual machine.
+ */
+ /*public static MemoryMXBean getMemoryMXBean()
+ {
+ if (memoryBean == null)
+ try
+ {
+ memoryBean = new MemoryMXBeanImpl();
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "memory bean is not a compliant " +
+ "management bean.");
+ }
+ return memoryBean;
+ }*/
+
+ /**
+ * Returns the compilation bean for the running
+ * virtual machine, if supported. Otherwise,
+ * it returns <code>null</code>.
+ *
+ * @return an instance of {@link CompilationMXBean} for
+ * this virtual machine, or <code>null</code>
+ * if the virtual machine doesn't include
+ * a Just-In-Time (JIT) compiler.
+ */
+ /*public static CompilationMXBean getCompilationMXBean()
+ {
+ if (compilationBean == null &&
+ SystemProperties.getProperty("gnu.java.compiler.name") != null)
+ try
+ {
+ compilationBean = new CompilationMXBeanImpl();
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "compilation bean is not a compliant " +
+ "management bean.");
+ }
+ return compilationBean;
+ }*/
+
+ /**
+ * Returns the memory pool beans for the running
+ * virtual machine. These may change during the course
+ * of execution.
+ *
+ * @return a list of memory pool beans, one for each pool.
+ */
+ /*public static List<MemoryPoolMXBean> getMemoryPoolMXBeans()
+ {
+ List<MemoryPoolMXBean> poolBeans =
+ new ArrayList<MemoryPoolMXBean>();
+ String[] names = VMManagementFactory.getMemoryPoolNames();
+ for (int a = 0; a < names.length; ++a)
+ try
+ {
+ poolBeans.add(new MemoryPoolMXBeanImpl(names[a]));
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "memory pool bean, " + a + ", is " +
+ "not a compliant management bean.");
+ }
+ return poolBeans;
+ }*/
+
+ /**
+ * Returns the memory manager beans for the running
+ * virtual machine. These may change during the course
+ * of execution.
+ *
+ * @return a list of memory manager beans, one for each manager.
+ */
+ /*public static List<MemoryManagerMXBean> getMemoryManagerMXBeans()
+ {
+ List<MemoryManagerMXBean> managerBeans =
+ new ArrayList<MemoryManagerMXBean>();
+ String[] names = VMManagementFactory.getMemoryManagerNames();
+ for (int a = 0; a < names.length; ++a)
+ try
+ {
+ managerBeans.add(new MemoryManagerMXBeanImpl(names[a]));
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "memory manager bean, " + a + ", is " +
+ "not a compliant management bean.");
+ }
+ managerBeans.addAll(getGarbageCollectorMXBeans());
+ return managerBeans;
+ }*/
+
+ /**
+ * Returns the garbage collector beans for the running
+ * virtual machine. These may change during the course
+ * of execution.
+ *
+ * @return a list of garbage collector beans, one for each pool.
+ */
+ public static List/*<GarbageCollectorMXBean>*/ getGarbageCollectorMXBeans()
+ {
+ List/*<GarbageCollectorMXBean>*/ gcBeans =
+ new ArrayList/*<GarbageCollectorMXBean>*/();
+ /*String[] names = VMManagementFactory.getGarbageCollectorNames();
+ for (int a = 0; a < names.length; ++a)
+ try
+ {
+ gcBeans.add(new GarbageCollectorMXBeanImpl(names[a]));
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw new InternalError("The GNU implementation of the " +
+ "garbage collector bean, " + a +
+ ", is not a compliant management " +
+ "bean.");
+ }*/
+ return gcBeans;
+ }
+
+ /**
+ * <p>
+ * Returns the platform {@link javax.management.MBeanServer}. On the
+ * first call to this method, a server instance is retrieved from
+ * the {@link javax.management.MBeanServerFactory} and each of the
+ * beans are registered with it. Subsequent calls return the existing
+ * instance. If the property <code>javax.management.builder.initial</code>
+ * is set, its value will be used as the name of the class which is used
+ * to provide the server instance.
+ * </p>
+ * <p>
+ * It is recommended that the platform server is used for other beans as
+ * well, in order to simplify their discovery and publication. Name conflicts
+ * should be avoided.
+ * </p>
+ *
+ * @return the platform {@link javax.management.MBeanServer}
+ * @throws SecurityException if a security manager exists and the
+ * caller's permissions don't imply {@link
+ * MBeanServerPermission(String)}("createMBeanServer")
+ * @see javax.management.MBeanServerFactory
+ * @see javax.management.MBeanServerFactory#createMBeanServer()
+ */
+ /*public static MBeanServer getPlatformMBeanServer()
+ {
+ if (platformServer == null)
+ {
+ platformServer = MBeanServerFactory.createMBeanServer();
+ try
+ {
+ platformServer.registerMBean(getOperatingSystemMXBean(),
+ new ObjectName(OPERATING_SYSTEM_MXBEAN_NAME));
+ platformServer.registerMBean(getRuntimeMXBean(),
+ new ObjectName(RUNTIME_MXBEAN_NAME));
+ platformServer.registerMBean(getClassLoadingMXBean(),
+ new ObjectName(CLASS_LOADING_MXBEAN_NAME));
+ platformServer.registerMBean(getThreadMXBean(),
+ new ObjectName(THREAD_MXBEAN_NAME));
+ platformServer.registerMBean(getMemoryMXBean(),
+ new ObjectName(MEMORY_MXBEAN_NAME));
+ CompilationMXBean compBean = getCompilationMXBean();
+ if (compBean != null)
+ platformServer.registerMBean(compBean,
+ new ObjectName(COMPILATION_MXBEAN_NAME));
+ Iterator beans = getMemoryPoolMXBeans().iterator();
+ while (beans.hasNext())
+ {
+ MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next();
+ platformServer.registerMBean(bean,
+ new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE +
+ ",name=" +
+ bean.getName()));
+ }
+ beans = getMemoryManagerMXBeans().iterator();
+ while (beans.hasNext())
+ {
+ MemoryManagerMXBean bean = (MemoryManagerMXBean) beans.next();
+ platformServer.registerMBean(bean,
+ new ObjectName(MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE +
+ ",name=" +
+ bean.getName()));
+ }
+ beans = getGarbageCollectorMXBeans().iterator();
+ while (beans.hasNext())
+ {
+ GarbageCollectorMXBean bean = (GarbageCollectorMXBean) beans.next();
+ platformServer.registerMBean(bean,
+ new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE +
+ ",name=" +
+ bean.getName()));
+ }
+ platformServer.registerMBean(LogManager.getLoggingMXBean(),
+ new ObjectName(LogManager.LOGGING_MXBEAN_NAME));
+ }
+ catch (InstanceAlreadyExistsException e)
+ {
+ throw (Error)
+ (new InternalError("One of the management beans is " +
+ "already registered.").initCause(e));
+ }
+ catch (MBeanRegistrationException e)
+ {
+ throw (Error)
+ (new InternalError("One of the management beans' preRegister " +
+ "methods threw an exception.").initCause(e));
+ }
+ catch (NotCompliantMBeanException e)
+ {
+ throw (Error)
+ (new InternalError("One of the management beans is " +
+ "not compliant.").initCause(e));
+ }
+ catch (MalformedObjectNameException e)
+ {
+ throw (Error)
+ (new InternalError("The object name of a management bean is " +
+ "not compliant.").initCause(e));
+ }
+ }
+ return platformServer;
+ }*/
+
+ /**
+ * <p>
+ * Returns a proxy for the specified platform bean. A proxy object is created
+ * using <code>Proxy.newProxyInstance(mxbeanInterface.getClassLoader(),
+ * new Class[] { mxbeanInterface }, handler)</code>. The
+ * {@link javax.management.NotificationEmitter} class is also added to the
+ * array if the bean provides notifications. <code>handler</code> refers
+ * to the invocation handler which forwards calls to the connection, and
+ * also provides translation between the Java data types used in the
+ * bean interfaces and the open data types, as specified in the description
+ * of this class. It is this translation that makes the
+ * usual {@link javax.management.MBeanServerInvocationHandler} inappropriate
+ * for providing such a proxy.
+ * </p>
+ * <p>
+ * <strong>Note</strong>: use of the proxy may result in
+ * {@link java.io.IOException}s from the underlying {@link MBeanServerConnection}
+ * and a {@link java.io.InvalidObjectException} if enum constants
+ * used on the client and the server don't match.
+ * </p>
+ *
+ * @param connection the server connection to use to access the bean.
+ * @param mxbeanName the {@link javax.management.ObjectName} of the
+ * bean to provide a proxy for.
+ * @param mxbeanInterface the interface for the bean being proxied.
+ * @return a proxy for the specified bean.
+ * @throws IllegalArgumentException if <code>mxbeanName</code> is not a valid
+ * {@link javax.management.ObjectName},
+ * the interface and name do not match the
+ * same bean, the name does not refer to a
+ * platform bean or the bean is not registered
+ * with the server accessed by <code>connection</code>.
+ * @throws IOException if the connection throws one.
+ */
+ /*public static <T> T newPlatformMXBeanProxy(MBeanServerConnection connection,
+ String mxbeanName,
+ Class<T> mxbeanInterface)
+ throws IOException
+ {
+ if (!(mxbeanName.equals(CLASS_LOADING_MXBEAN_NAME) ||
+ mxbeanName.equals(COMPILATION_MXBEAN_NAME) ||
+ mxbeanName.startsWith(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE) ||
+ mxbeanName.startsWith(MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE) ||
+ mxbeanName.equals(MEMORY_MXBEAN_NAME) ||
+ mxbeanName.startsWith(MEMORY_POOL_MXBEAN_DOMAIN_TYPE) ||
+ mxbeanName.equals(OPERATING_SYSTEM_MXBEAN_NAME) ||
+ mxbeanName.equals(RUNTIME_MXBEAN_NAME) ||
+ mxbeanName.equals(THREAD_MXBEAN_NAME)))
+ {
+ throw new IllegalArgumentException("The named bean, " + mxbeanName +
+ ", is not a platform name.");
+ }
+ if ((mxbeanName.equals(CLASS_LOADING_MXBEAN_NAME) &&
+ mxbeanInterface != ClassLoadingMXBean.class) ||
+ (mxbeanName.equals(COMPILATION_MXBEAN_NAME) &&
+ mxbeanInterface != CompilationMXBean.class) ||
+ (mxbeanName.startsWith(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE) &&
+ mxbeanInterface != GarbageCollectorMXBean.class) ||
+ (mxbeanName.startsWith(MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE) &&
+ mxbeanInterface != MemoryManagerMXBean.class) ||
+ (mxbeanName.equals(MEMORY_MXBEAN_NAME) &&
+ mxbeanInterface != MemoryMXBean.class) ||
+ (mxbeanName.startsWith(MEMORY_POOL_MXBEAN_DOMAIN_TYPE) &&
+ mxbeanInterface != MemoryPoolMXBean.class) ||
+ (mxbeanName.equals(OPERATING_SYSTEM_MXBEAN_NAME) &&
+ mxbeanInterface != OperatingSystemMXBean.class) ||
+ (mxbeanName.equals(RUNTIME_MXBEAN_NAME) &&
+ mxbeanInterface != RuntimeMXBean.class) ||
+ (mxbeanName.equals(THREAD_MXBEAN_NAME) &&
+ mxbeanInterface != ThreadMXBean.class))
+ throw new IllegalArgumentException("The interface, " + mxbeanInterface +
+ ", does not match the bean, " + mxbeanName);
+ ObjectName bean;
+ try
+ {
+ bean = new ObjectName(mxbeanName);
+ }
+ catch (MalformedObjectNameException e)
+ {
+ throw new IllegalArgumentException("The named bean is invalid.");
+ }
+ if (!(connection.isRegistered(bean)))
+ throw new IllegalArgumentException("The bean is not registered on this connection.");
+ Class[] interfaces;
+ if (mxbeanName.equals(MEMORY_MXBEAN_NAME))
+ interfaces = new Class[] { mxbeanInterface, NotificationEmitter.class };
+ else
+ interfaces = new Class[] { mxbeanInterface };
+ return (T) Proxy.newProxyInstance(mxbeanInterface.getClassLoader(),
+ interfaces,
+ new ManagementInvocationHandler(connection, bean));
+ }*/
+
+ /**
+ * This invocation handler provides method calls for a platform bean
+ * by forwarding them to a {@link MBeanServerConnection}. Translation from
+ * Java data types to open data types is performed as specified above.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+ /*private static class ManagementInvocationHandler
+ implements InvocationHandler
+ {
+
+ /**
+ * The encapsulated connection.
+ */
+ /*private MBeanServerConnection conn;
+
+ /**
+ * The bean being proxied.
+ */
+ /*private ObjectName bean;
+
+ /**
+ * Constructs a new {@link InvocationHandler} which proxies
+ * for the specified bean using the supplied connection.
+ *
+ * @param conn the connection on which to forward method calls.
+ * @param bean the bean to proxy.
+ */
+ /*public ManagementInvocationHandler(MBeanServerConnection conn,
+ ObjectName bean)
+ throws IOException
+ {
+ this.conn = conn;
+ this.bean = bean;
+ }
+
+ /**
+ * Called by the proxy class whenever a method is called. The method
+ * is emulated by retrieving an attribute from, setting an attribute on
+ * or invoking a method on the server connection as required. Translation
+ * between the Java data types supplied as arguments to the open types used
+ * by the bean is provided, as well as translation of the return value back
+ * in to the appropriate Java type.
+ *
+ * @param proxy the proxy on which the method was called.
+ * @param method the method which was called.
+ * @param args the arguments supplied to the method.
+ * @return the return value from the method.
+ * @throws Throwable if an exception is thrown in performing the
+ * method emulation.
+ */
+ /*public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable
+ {
+ String name = method.getName();
+ if (name.equals("toString"))
+ return "Proxy for " + bean + " using " + conn;
+ if (name.equals("addNotificationListener"))
+ {
+ conn.addNotificationListener(bean,
+ (NotificationListener) args[0],
+ (NotificationFilter) args[1],
+ args[2]);
+ return null;
+ }
+ if (name.equals("getNotificationInfo"))
+ return conn.getMBeanInfo(bean).getNotifications();
+ if (name.equals("removeNotificationListener"))
+ {
+ if (args.length == 1)
+ conn.removeNotificationListener(bean,
+ (NotificationListener)
+ args[0]);
+ else
+ conn.removeNotificationListener(bean,
+ (NotificationListener)
+ args[0],
+ (NotificationFilter)
+ args[1], args[2]);
+ return null;
+ }
+ String attrib = null;
+ if (name.startsWith("get"))
+ attrib = name.substring(3);
+ else if (name.startsWith("is"))
+ attrib = name.substring(2);
+ if (attrib != null)
+ return translate(conn.getAttribute(bean, attrib), method);
+ else if (name.startsWith("set"))
+ {
+ conn.setAttribute(bean, new Attribute(name.substring(3),
+ args[0]));
+ return null;
+ }
+ else
+ return translate(conn.invoke(bean, name, args, null), method);
+ }
+
+ /**
+ * Translates the returned open data type to the value
+ * required by the interface.
+ *
+ * @param otype the open type returned by the method call.
+ * @param method the method that was called.
+ * @return the equivalent return type required by the interface.
+ * @throws Throwable if an exception is thrown in performing the
+ * conversion.
+ */
+ /*private final Object translate(Object otype, Method method)
+ throws Throwable
+ {
+ Class<?> returnType = method.getReturnType();
+ if (returnType.isEnum())
+ {
+ String ename = (String) otype;
+ Enum[] constants = (Enum[]) returnType.getEnumConstants();
+ for (Enum c : constants)
+ if (c.name().equals(ename))
+ return c;
+ }
+ if (List.class.isAssignableFrom(returnType))
+ {
+ Object[] elems = (Object[]) otype;
+ List l = new ArrayList(elems.length);
+ for (Object elem : elems)
+ l.add(elem);
+ return l;
+ }
+ if (Map.class.isAssignableFrom(returnType))
+ {
+ TabularData data = (TabularData) otype;
+ Map m = new HashMap(data.size());
+ for (Object val : data.values())
+ {
+ CompositeData vals = (CompositeData) val;
+ m.put(vals.get("key"), vals.get("value"));
+ }
+ return m;
+ }
+ try
+ {
+ Method m = returnType.getMethod("from",
+ new Class[]
+ { CompositeData.class });
+ return m.invoke(null, (CompositeData) otype);
+ }
+ catch (NoSuchMethodException e)
+ {
+ /* Ignored; we expect this if this
+ isn't a from(CompositeData) class */
+ /*}
+ return otype;
+ }
+
+ }*/
+}
--- /dev/null
+/* MemoryManagerMXBean.java - Interface for a memory manager bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package java.lang.management;
+
+/**
+ * Provides access to information about the memory managers
+ * of the virtual machine. An instance of this bean for each
+ * memory manager is obtained by calling
+ * {@link ManagementFactory#getMemoryManagerMXBeans()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public interface MemoryManagerMXBean
+{
+
+ /**
+ * Returns an array containing the names of the memory pools
+ * this memory manager manages.
+ *
+ * @return an array containing the name of each memory pool
+ * this manager is responsible for.
+ */
+ String[] getMemoryPoolNames();
+
+ /**
+ * Returns the name of the memory manager.
+ *
+ * @return the memory manager name.
+ */
+ String getName();
+
+ /**
+ * Returns true if this memory manager is still valid. A memory
+ * manager becomes invalid when it is removed by the virtual machine
+ * and no longer used.
+ *
+ * @return true if this memory manager is valid.
+ */
+ boolean isValid();
+
+}
print(c);
return this;
}
+
+ public PrintStream append(String s)
+ {
+ print(s==null?"null":s);
+ return this;
+ }
/** @since 1.5 */
/*public PrintStream append(CharSequence cs)
--- /dev/null
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util;
+
+/**
+ * A collection designed for holding elements prior to processing.
+ * Besides basic {@link java.util.Collection Collection} operations,
+ * queues provide additional insertion, extraction, and inspection
+ * operations. Each of these methods exists in two forms: one throws
+ * an exception if the operation fails, the other returns a special
+ * value (either <tt>null</tt> or <tt>false</tt>, depending on the
+ * operation). The latter form of the insert operation is designed
+ * specifically for use with capacity-restricted <tt>Queue</tt>
+ * implementations; in most implementations, insert operations cannot
+ * fail.
+ *
+ * <p>
+ * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <tr>
+ * <td></td>
+ * <td ALIGN=CENTER><em>Throws exception</em></td>
+ * <td ALIGN=CENTER><em>Returns special value</em></td>
+ * </tr>
+ * <tr>
+ * <td><b>Insert</b></td>
+ * <td>{@link #add add(e)}</td>
+ * <td>{@link #offer offer(e)}</td>
+ * </tr>
+ * <tr>
+ * <td><b>Remove</b></td>
+ * <td>{@link #remove remove()}</td>
+ * <td>{@link #poll poll()}</td>
+ * </tr>
+ * <tr>
+ * <td><b>Examine</b></td>
+ * <td>{@link #element element()}</td>
+ * <td>{@link #peek peek()}</td>
+ * </tr>
+ * </table>
+ *
+ * <p>Queues typically, but do not necessarily, order elements in a
+ * FIFO (first-in-first-out) manner. Among the exceptions are
+ * priority queues, which order elements according to a supplied
+ * comparator, or the elements' natural ordering, and LIFO queues (or
+ * stacks) which order the elements LIFO (last-in-first-out).
+ * Whatever the ordering used, the <em>head</em> of the queue is that
+ * element which would be removed by a call to {@link #remove() } or
+ * {@link #poll()}. In a FIFO queue, all new elements are inserted at
+ * the <em> tail</em> of the queue. Other kinds of queues may use
+ * different placement rules. Every <tt>Queue</tt> implementation
+ * must specify its ordering properties.
+ *
+ * <p>The {@link #offer offer} method inserts an element if possible,
+ * otherwise returning <tt>false</tt>. This differs from the {@link
+ * java.util.Collection#add Collection.add} method, which can fail to
+ * add an element only by throwing an unchecked exception. The
+ * <tt>offer</tt> method is designed for use when failure is a normal,
+ * rather than exceptional occurrence, for example, in fixed-capacity
+ * (or "bounded") queues.
+ *
+ * <p>The {@link #remove()} and {@link #poll()} methods remove and
+ * return the head of the queue.
+ * Exactly which element is removed from the queue is a
+ * function of the queue's ordering policy, which differs from
+ * implementation to implementation. The <tt>remove()</tt> and
+ * <tt>poll()</tt> methods differ only in their behavior when the
+ * queue is empty: the <tt>remove()</tt> method throws an exception,
+ * while the <tt>poll()</tt> method returns <tt>null</tt>.
+ *
+ * <p>The {@link #element()} and {@link #peek()} methods return, but do
+ * not remove, the head of the queue.
+ *
+ * <p>The <tt>Queue</tt> interface does not define the <i>blocking queue
+ * methods</i>, which are common in concurrent programming. These methods,
+ * which wait for elements to appear or for space to become available, are
+ * defined in the {@link java.util.concurrent.BlockingQueue} interface, which
+ * extends this interface.
+ *
+ * <p><tt>Queue</tt> implementations generally do not allow insertion
+ * of <tt>null</tt> elements, although some implementations, such as
+ * {@link LinkedList}, do not prohibit insertion of <tt>null</tt>.
+ * Even in the implementations that permit it, <tt>null</tt> should
+ * not be inserted into a <tt>Queue</tt>, as <tt>null</tt> is also
+ * used as a special return value by the <tt>poll</tt> method to
+ * indicate that the queue contains no elements.
+ *
+ * <p><tt>Queue</tt> implementations generally do not define
+ * element-based versions of methods <tt>equals</tt> and
+ * <tt>hashCode</tt> but instead inherit the identity based versions
+ * from class <tt>Object</tt>, because element-based equality is not
+ * always well-defined for queues with the same elements but different
+ * ordering properties.
+ *
+ *
+ * <p>This interface is a member of the
+ * <a href="{@docRoot}/../technotes/guides/collections/index.html">
+ * Java Collections Framework</a>.
+ *
+ * @see java.util.Collection
+ * @see LinkedList
+ * @see PriorityQueue
+ * @see java.util.concurrent.LinkedBlockingQueue
+ * @see java.util.concurrent.BlockingQueue
+ * @see java.util.concurrent.ArrayBlockingQueue
+ * @see java.util.concurrent.LinkedBlockingQueue
+ * @see java.util.concurrent.PriorityBlockingQueue
+ * @since 1.5
+ * @author Doug Lea
+ * @param <E> the type of elements held in this collection
+ */
+public interface Queue/*<E>*/ extends Collection/*<E>*/ {
+ /**
+ * Inserts the specified element into this queue if it is possible to do so
+ * immediately without violating capacity restrictions, returning
+ * <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
+ * if no space is currently available.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> (as specified by {@link Collection#add})
+ * @throws IllegalStateException if the element cannot be added at this
+ * time due to capacity restrictions
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this queue
+ * @throws NullPointerException if the specified element is null and
+ * this queue does not permit null elements
+ * @throws IllegalArgumentException if some property of this element
+ * prevents it from being added to this queue
+ */
+ boolean add(Object/*E*/ e);
+
+ /**
+ * Inserts the specified element into this queue if it is possible to do
+ * so immediately without violating capacity restrictions.
+ * When using a capacity-restricted queue, this method is generally
+ * preferable to {@link #add}, which can fail to insert an element only
+ * by throwing an exception.
+ *
+ * @param e the element to add
+ * @return <tt>true</tt> if the element was added to this queue, else
+ * <tt>false</tt>
+ * @throws ClassCastException if the class of the specified element
+ * prevents it from being added to this queue
+ * @throws NullPointerException if the specified element is null and
+ * this queue does not permit null elements
+ * @throws IllegalArgumentException if some property of this element
+ * prevents it from being added to this queue
+ */
+ boolean offer(Object/*E*/ e);
+
+ /**
+ * Retrieves and removes the head of this queue. This method differs
+ * from {@link #poll poll} only in that it throws an exception if this
+ * queue is empty.
+ *
+ * @return the head of this queue
+ * @throws NoSuchElementException if this queue is empty
+ */
+ Object/*E*/ remove();
+
+ /**
+ * Retrieves and removes the head of this queue,
+ * or returns <tt>null</tt> if this queue is empty.
+ *
+ * @return the head of this queue, or <tt>null</tt> if this queue is empty
+ */
+ Object/*E*/ poll();
+
+ /**
+ * Retrieves, but does not remove, the head of this queue. This method
+ * differs from {@link #peek peek} only in that it throws an exception
+ * if this queue is empty.
+ *
+ * @return the head of this queue
+ * @throws NoSuchElementException if this queue is empty
+ */
+ Object/*E*/ element();
+
+ /**
+ * Retrieves, but does not remove, the head of this queue,
+ * or returns <tt>null</tt> if this queue is empty.
+ *
+ * @return the head of this queue, or <tt>null</tt> if this queue is empty
+ */
+ Object/*E*/ peek();
+}
--- /dev/null
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+/*package java.util.concurrent.locks;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;*/
+
+/**
+ * A reentrant mutual exclusion {@link Lock} with the same basic
+ * behavior and semantics as the implicit monitor lock accessed using
+ * {@code synchronized} methods and statements, but with extended
+ * capabilities.
+ *
+ * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last
+ * successfully locking, but not yet unlocking it. A thread invoking
+ * {@code lock} will return, successfully acquiring the lock, when
+ * the lock is not owned by another thread. The method will return
+ * immediately if the current thread already owns the lock. This can
+ * be checked using methods {@link #isHeldByCurrentThread}, and {@link
+ * #getHoldCount}.
+ *
+ * <p>The constructor for this class accepts an optional
+ * <em>fairness</em> parameter. When set {@code true}, under
+ * contention, locks favor granting access to the longest-waiting
+ * thread. Otherwise this lock does not guarantee any particular
+ * access order. Programs using fair locks accessed by many threads
+ * may display lower overall throughput (i.e., are slower; often much
+ * slower) than those using the default setting, but have smaller
+ * variances in times to obtain locks and guarantee lack of
+ * starvation. Note however, that fairness of locks does not guarantee
+ * fairness of thread scheduling. Thus, one of many threads using a
+ * fair lock may obtain it multiple times in succession while other
+ * active threads are not progressing and not currently holding the
+ * lock.
+ * Also note that the untimed {@link #tryLock() tryLock} method does not
+ * honor the fairness setting. It will succeed if the lock
+ * is available even if other threads are waiting.
+ *
+ * <p>It is recommended practice to <em>always</em> immediately
+ * follow a call to {@code lock} with a {@code try} block, most
+ * typically in a before/after construction such as:
+ *
+ * <pre>
+ * class X {
+ * private final ReentrantLock lock = new ReentrantLock();
+ * // ...
+ *
+ * public void m() {
+ * lock.lock(); // block until condition holds
+ * try {
+ * // ... method body
+ * } finally {
+ * lock.unlock()
+ * }
+ * }
+ * }
+ * </pre>
+ *
+ * <p>In addition to implementing the {@link Lock} interface, this
+ * class defines methods {@code isLocked} and
+ * {@code getLockQueueLength}, as well as some associated
+ * {@code protected} access methods that may be useful for
+ * instrumentation and monitoring.
+ *
+ * <p>Serialization of this class behaves in the same way as built-in
+ * locks: a deserialized lock is in the unlocked state, regardless of
+ * its state when serialized.
+ *
+ * <p>This lock supports a maximum of 2147483647 recursive locks by
+ * the same thread. Attempts to exceed this limit result in
+ * {@link Error} throws from locking methods.
+ *
+ * @since 1.5
+ * @author Doug Lea
+ */
+public class ReentrantLock implements /*Lock, java.io.*/Serializable {
+ private static final long serialVersionUID = 7373984872572414699L;
+ /** Synchronizer providing all implementation mechanics */
+ //private final Sync sync;
+
+ /**
+ * Base of synchronization control for this lock. Subclassed
+ * into fair and nonfair versions below. Uses AQS state to
+ * represent the number of holds on the lock.
+ */
+ /*static abstract class Sync extends AbstractQueuedSynchronizer {
+ private static final long serialVersionUID = -5179523762034025860L;
+
+ /**
+ * Performs {@link Lock#lock}. The main reason for subclassing
+ * is to allow fast path for nonfair version.
+ */
+ /*abstract void lock();
+
+ /**
+ * Performs non-fair tryLock. tryAcquire is
+ * implemented in subclasses, but both need nonfair
+ * try for trylock method.
+ */
+ /*final boolean nonfairTryAcquire(int acquires) {
+ final Thread current = Thread.currentThread();
+ int c = getState();
+ if (c == 0) {
+ if (compareAndSetState(0, acquires)) {
+ setExclusiveOwnerThread(current);
+ return true;
+ }
+ }
+ else if (current == getExclusiveOwnerThread()) {
+ int nextc = c + acquires;
+ if (nextc < 0) // overflow
+ throw new Error("Maximum lock count exceeded");
+ setState(nextc);
+ return true;
+ }
+ return false;
+ }
+
+ protected final boolean tryRelease(int releases) {
+ int c = getState() - releases;
+ if (Thread.currentThread() != getExclusiveOwnerThread())
+ throw new IllegalMonitorStateException();
+ boolean free = false;
+ if (c == 0) {
+ free = true;
+ setExclusiveOwnerThread(null);
+ }
+ setState(c);
+ return free;
+ }
+
+ protected final boolean isHeldExclusively() {
+ // While we must in general read state before owner,
+ // we don't need to do so to check if current thread is owner
+ return getExclusiveOwnerThread() == Thread.currentThread();
+ }
+
+ final ConditionObject newCondition() {
+ return new ConditionObject();
+ }
+
+ // Methods relayed from outer class
+
+ final Thread getOwner() {
+ return getState() == 0 ? null : getExclusiveOwnerThread();
+ }
+
+ final int getHoldCount() {
+ return isHeldExclusively() ? getState() : 0;
+ }
+
+ final boolean isLocked() {
+ return getState() != 0;
+ }
+
+ /**
+ * Reconstitutes this lock instance from a stream.
+ * @param s the stream
+ */
+ /*private void readObject(java.io.ObjectInputStream s)
+ throws java.io.IOException, ClassNotFoundException {
+ s.defaultReadObject();
+ setState(0); // reset to unlocked state
+ }
+ }*/
+
+ /**
+ * Sync object for non-fair locks
+ */
+ /*final static class NonfairSync extends Sync {
+ private static final long serialVersionUID = 7316153563782823691L;
+
+ /**
+ * Performs lock. Try immediate barge, backing up to normal
+ * acquire on failure.
+ */
+ /*final void lock() {
+ if (compareAndSetState(0, 1))
+ setExclusiveOwnerThread(Thread.currentThread());
+ else
+ acquire(1);
+ }
+
+ protected final boolean tryAcquire(int acquires) {
+ return nonfairTryAcquire(acquires);
+ }
+ }*/
+
+ /**
+ * Sync object for fair locks
+ */
+ /*final static class FairSync extends Sync {
+ private static final long serialVersionUID = -3000897897090466540L;
+
+ final void lock() {
+ acquire(1);
+ }
+
+ /**
+ * Fair version of tryAcquire. Don't grant access unless
+ * recursive call or no waiters or is first.
+ */
+ /*protected final boolean tryAcquire(int acquires) {
+ final Thread current = Thread.currentThread();
+ int c = getState();
+ if (c == 0) {
+ if (isFirst(current) &&
+ compareAndSetState(0, acquires)) {
+ setExclusiveOwnerThread(current);
+ return true;
+ }
+ }
+ else if (current == getExclusiveOwnerThread()) {
+ int nextc = c + acquires;
+ if (nextc < 0)
+ throw new Error("Maximum lock count exceeded");
+ setState(nextc);
+ return true;
+ }
+ return false;
+ }
+ }*/
+
+ /**
+ * Creates an instance of {@code ReentrantLock}.
+ * This is equivalent to using {@code ReentrantLock(false)}.
+ */
+ public ReentrantLock() {
+ //sync = new NonfairSync();
+ }
+
+ /**
+ * Creates an instance of {@code ReentrantLock} with the
+ * given fairness policy.
+ *
+ * @param fair {@code true} if this lock should use a fair ordering policy
+ */
+ public ReentrantLock(boolean fair) {
+ //sync = (fair)? new FairSync() : new NonfairSync();
+ }
+
+ /**
+ * Acquires the lock.
+ *
+ * <p>Acquires the lock if it is not held by another thread and returns
+ * immediately, setting the lock hold count to one.
+ *
+ * <p>If the current thread already holds the lock then the hold
+ * count is incremented by one and the method returns immediately.
+ *
+ * <p>If the lock is held by another thread then the
+ * current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until the lock has been acquired,
+ * at which time the lock hold count is set to one.
+ */
+ public void lock() {
+ //sync.lock();
+ System.out.println("Unimplemented ReentrantLock.lock()!");
+ }
+
+ /**
+ * Acquires the lock unless the current thread is
+ * {@linkplain Thread#interrupt interrupted}.
+ *
+ * <p>Acquires the lock if it is not held by another thread and returns
+ * immediately, setting the lock hold count to one.
+ *
+ * <p>If the current thread already holds this lock then the hold count
+ * is incremented by one and the method returns immediately.
+ *
+ * <p>If the lock is held by another thread then the
+ * current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until one of two things happens:
+ *
+ * <ul>
+ *
+ * <li>The lock is acquired by the current thread; or
+ *
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
+ * current thread.
+ *
+ * </ul>
+ *
+ * <p>If the lock is acquired by the current thread then the lock hold
+ * count is set to one.
+ *
+ * <p>If the current thread:
+ *
+ * <ul>
+ *
+ * <li>has its interrupted status set on entry to this method; or
+ *
+ * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
+ * the lock,
+ *
+ * </ul>
+ *
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared.
+ *
+ * <p>In this implementation, as this method is an explicit
+ * interruption point, preference is given to responding to the
+ * interrupt over normal or reentrant acquisition of the lock.
+ *
+ * @throws InterruptedException if the current thread is interrupted
+ */
+ /*public void lockInterruptibly() throws InterruptedException {
+ sync.acquireInterruptibly(1);
+ }*/
+
+ /**
+ * Acquires the lock only if it is not held by another thread at the time
+ * of invocation.
+ *
+ * <p>Acquires the lock if it is not held by another thread and
+ * returns immediately with the value {@code true}, setting the
+ * lock hold count to one. Even when this lock has been set to use a
+ * fair ordering policy, a call to {@code tryLock()} <em>will</em>
+ * immediately acquire the lock if it is available, whether or not
+ * other threads are currently waiting for the lock.
+ * This "barging" behavior can be useful in certain
+ * circumstances, even though it breaks fairness. If you want to honor
+ * the fairness setting for this lock, then use
+ * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
+ * which is almost equivalent (it also detects interruption).
+ *
+ * <p> If the current thread already holds this lock then the hold
+ * count is incremented by one and the method returns {@code true}.
+ *
+ * <p>If the lock is held by another thread then this method will return
+ * immediately with the value {@code false}.
+ *
+ * @return {@code true} if the lock was free and was acquired by the
+ * current thread, or the lock was already held by the current
+ * thread; and {@code false} otherwise
+ */
+ /*public boolean tryLock() {
+ return sync.nonfairTryAcquire(1);
+ }*/
+
+ /**
+ * Acquires the lock if it is not held by another thread within the given
+ * waiting time and the current thread has not been
+ * {@linkplain Thread#interrupt interrupted}.
+ *
+ * <p>Acquires the lock if it is not held by another thread and returns
+ * immediately with the value {@code true}, setting the lock hold count
+ * to one. If this lock has been set to use a fair ordering policy then
+ * an available lock <em>will not</em> be acquired if any other threads
+ * are waiting for the lock. This is in contrast to the {@link #tryLock()}
+ * method. If you want a timed {@code tryLock} that does permit barging on
+ * a fair lock then combine the timed and un-timed forms together:
+ *
+ * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
+ * </pre>
+ *
+ * <p>If the current thread
+ * already holds this lock then the hold count is incremented by one and
+ * the method returns {@code true}.
+ *
+ * <p>If the lock is held by another thread then the
+ * current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until one of three things happens:
+ *
+ * <ul>
+ *
+ * <li>The lock is acquired by the current thread; or
+ *
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts}
+ * the current thread; or
+ *
+ * <li>The specified waiting time elapses
+ *
+ * </ul>
+ *
+ * <p>If the lock is acquired then the value {@code true} is returned and
+ * the lock hold count is set to one.
+ *
+ * <p>If the current thread:
+ *
+ * <ul>
+ *
+ * <li>has its interrupted status set on entry to this method; or
+ *
+ * <li>is {@linkplain Thread#interrupt interrupted} while
+ * acquiring the lock,
+ *
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared.
+ *
+ * <p>If the specified waiting time elapses then the value {@code false}
+ * is returned. If the time is less than or equal to zero, the method
+ * will not wait at all.
+ *
+ * <p>In this implementation, as this method is an explicit
+ * interruption point, preference is given to responding to the
+ * interrupt over normal or reentrant acquisition of the lock, and
+ * over reporting the elapse of the waiting time.
+ *
+ * @param timeout the time to wait for the lock
+ * @param unit the time unit of the timeout argument
+ * @return {@code true} if the lock was free and was acquired by the
+ * current thread, or the lock was already held by the current
+ * thread; and {@code false} if the waiting time elapsed before
+ * the lock could be acquired
+ * @throws InterruptedException if the current thread is interrupted
+ * @throws NullPointerException if the time unit is null
+ *
+ */
+ /*public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
+ return sync.tryAcquireNanos(1, unit.toNanos(timeout));
+ }*/
+
+ /**
+ * Attempts to release this lock.
+ *
+ * <p>If the current thread is the holder of this lock then the hold
+ * count is decremented. If the hold count is now zero then the lock
+ * is released. If the current thread is not the holder of this
+ * lock then {@link IllegalMonitorStateException} is thrown.
+ *
+ * @throws IllegalMonitorStateException if the current thread does not
+ * hold this lock
+ */
+ public void unlock() {
+ //sync.release(1);
+ System.out.println("Unimplemented ReentrantLock.unlock()!");
+ }
+
+ /**
+ * Returns a {@link Condition} instance for use with this
+ * {@link Lock} instance.
+ *
+ * <p>The returned {@link Condition} instance supports the same
+ * usages as do the {@link Object} monitor methods ({@link
+ * Object#wait() wait}, {@link Object#notify notify}, and {@link
+ * Object#notifyAll notifyAll}) when used with the built-in
+ * monitor lock.
+ *
+ * <ul>
+ *
+ * <li>If this lock is not held when any of the {@link Condition}
+ * {@linkplain Condition#await() waiting} or {@linkplain
+ * Condition#signal signalling} methods are called, then an {@link
+ * IllegalMonitorStateException} is thrown.
+ *
+ * <li>When the condition {@linkplain Condition#await() waiting}
+ * methods are called the lock is released and, before they
+ * return, the lock is reacquired and the lock hold count restored
+ * to what it was when the method was called.
+ *
+ * <li>If a thread is {@linkplain Thread#interrupt interrupted}
+ * while waiting then the wait will terminate, an {@link
+ * InterruptedException} will be thrown, and the thread's
+ * interrupted status will be cleared.
+ *
+ * <li> Waiting threads are signalled in FIFO order.
+ *
+ * <li>The ordering of lock reacquisition for threads returning
+ * from waiting methods is the same as for threads initially
+ * acquiring the lock, which is in the default case not specified,
+ * but for <em>fair</em> locks favors those threads that have been
+ * waiting the longest.
+ *
+ * </ul>
+ *
+ * @return the Condition object
+ */
+ public Condition newCondition() {
+ System.out.println("Unimplemented ReentrantLock.newCondition()!");
+ return null;
+ //return sync.newCondition();
+ }
+
+ /**
+ * Queries the number of holds on this lock by the current thread.
+ *
+ * <p>A thread has a hold on a lock for each lock action that is not
+ * matched by an unlock action.
+ *
+ * <p>The hold count information is typically only used for testing and
+ * debugging purposes. For example, if a certain section of code should
+ * not be entered with the lock already held then we can assert that
+ * fact:
+ *
+ * <pre>
+ * class X {
+ * ReentrantLock lock = new ReentrantLock();
+ * // ...
+ * public void m() {
+ * assert lock.getHoldCount() == 0;
+ * lock.lock();
+ * try {
+ * // ... method body
+ * } finally {
+ * lock.unlock();
+ * }
+ * }
+ * }
+ * </pre>
+ *
+ * @return the number of holds on this lock by the current thread,
+ * or zero if this lock is not held by the current thread
+ */
+ /*public int getHoldCount() {
+ return sync.getHoldCount();
+ }*/
+
+ /**
+ * Queries if this lock is held by the current thread.
+ *
+ * <p>Analogous to the {@link Thread#holdsLock} method for built-in
+ * monitor locks, this method is typically used for debugging and
+ * testing. For example, a method that should only be called while
+ * a lock is held can assert that this is the case:
+ *
+ * <pre>
+ * class X {
+ * ReentrantLock lock = new ReentrantLock();
+ * // ...
+ *
+ * public void m() {
+ * assert lock.isHeldByCurrentThread();
+ * // ... method body
+ * }
+ * }
+ * </pre>
+ *
+ * <p>It can also be used to ensure that a reentrant lock is used
+ * in a non-reentrant manner, for example:
+ *
+ * <pre>
+ * class X {
+ * ReentrantLock lock = new ReentrantLock();
+ * // ...
+ *
+ * public void m() {
+ * assert !lock.isHeldByCurrentThread();
+ * lock.lock();
+ * try {
+ * // ... method body
+ * } finally {
+ * lock.unlock();
+ * }
+ * }
+ * }
+ * </pre>
+ *
+ * @return {@code true} if current thread holds this lock and
+ * {@code false} otherwise
+ */
+ /*public boolean isHeldByCurrentThread() {
+ return sync.isHeldExclusively();
+ }*/
+
+ /**
+ * Queries if this lock is held by any thread. This method is
+ * designed for use in monitoring of the system state,
+ * not for synchronization control.
+ *
+ * @return {@code true} if any thread holds this lock and
+ * {@code false} otherwise
+ */
+ /*public boolean isLocked() {
+ return sync.isLocked();
+ }*/
+
+ /**
+ * Returns {@code true} if this lock has fairness set true.
+ *
+ * @return {@code true} if this lock has fairness set true
+ */
+ /*public final boolean isFair() {
+ return sync instanceof FairSync;
+ }*/
+
+ /**
+ * Returns the thread that currently owns this lock, or
+ * {@code null} if not owned. When this method is called by a
+ * thread that is not the owner, the return value reflects a
+ * best-effort approximation of current lock status. For example,
+ * the owner may be momentarily {@code null} even if there are
+ * threads trying to acquire the lock but have not yet done so.
+ * This method is designed to facilitate construction of
+ * subclasses that provide more extensive lock monitoring
+ * facilities.
+ *
+ * @return the owner, or {@code null} if not owned
+ */
+ /*protected Thread getOwner() {
+ return sync.getOwner();
+ }*/
+
+ /**
+ * Queries whether any threads are waiting to acquire this lock. Note that
+ * because cancellations may occur at any time, a {@code true}
+ * return does not guarantee that any other thread will ever
+ * acquire this lock. This method is designed primarily for use in
+ * monitoring of the system state.
+ *
+ * @return {@code true} if there may be other threads waiting to
+ * acquire the lock
+ */
+ /*public final boolean hasQueuedThreads() {
+ return sync.hasQueuedThreads();
+ }*/
+
+
+ /**
+ * Queries whether the given thread is waiting to acquire this
+ * lock. Note that because cancellations may occur at any time, a
+ * {@code true} return does not guarantee that this thread
+ * will ever acquire this lock. This method is designed primarily for use
+ * in monitoring of the system state.
+ *
+ * @param thread the thread
+ * @return {@code true} if the given thread is queued waiting for this lock
+ * @throws NullPointerException if the thread is null
+ */
+ /*public final boolean hasQueuedThread(Thread thread) {
+ return sync.isQueued(thread);
+ }*/
+
+
+ /**
+ * Returns an estimate of the number of threads waiting to
+ * acquire this lock. The value is only an estimate because the number of
+ * threads may change dynamically while this method traverses
+ * internal data structures. This method is designed for use in
+ * monitoring of the system state, not for synchronization
+ * control.
+ *
+ * @return the estimated number of threads waiting for this lock
+ */
+ /*public final int getQueueLength() {
+ return sync.getQueueLength();
+ }*/
+
+ /**
+ * Returns a collection containing threads that may be waiting to
+ * acquire this lock. Because the actual set of threads may change
+ * dynamically while constructing this result, the returned
+ * collection is only a best-effort estimate. The elements of the
+ * returned collection are in no particular order. This method is
+ * designed to facilitate construction of subclasses that provide
+ * more extensive monitoring facilities.
+ *
+ * @return the collection of threads
+ */
+ /*protected Collection<Thread> getQueuedThreads() {
+ return sync.getQueuedThreads();
+ }*/
+
+ /**
+ * Queries whether any threads are waiting on the given condition
+ * associated with this lock. Note that because timeouts and
+ * interrupts may occur at any time, a {@code true} return does
+ * not guarantee that a future {@code signal} will awaken any
+ * threads. This method is designed primarily for use in
+ * monitoring of the system state.
+ *
+ * @param condition the condition
+ * @return {@code true} if there are any waiting threads
+ * @throws IllegalMonitorStateException if this lock is not held
+ * @throws IllegalArgumentException if the given condition is
+ * not associated with this lock
+ * @throws NullPointerException if the condition is null
+ */
+ /*public boolean hasWaiters(Condition condition) {
+ if (condition == null)
+ throw new NullPointerException();
+ if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
+ throw new IllegalArgumentException("not owner");
+ return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
+ }*/
+
+ /**
+ * Returns an estimate of the number of threads waiting on the
+ * given condition associated with this lock. Note that because
+ * timeouts and interrupts may occur at any time, the estimate
+ * serves only as an upper bound on the actual number of waiters.
+ * This method is designed for use in monitoring of the system
+ * state, not for synchronization control.
+ *
+ * @param condition the condition
+ * @return the estimated number of waiting threads
+ * @throws IllegalMonitorStateException if this lock is not held
+ * @throws IllegalArgumentException if the given condition is
+ * not associated with this lock
+ * @throws NullPointerException if the condition is null
+ */
+ /*public int getWaitQueueLength(Condition condition) {
+ if (condition == null)
+ throw new NullPointerException();
+ if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
+ throw new IllegalArgumentException("not owner");
+ return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
+ }*/
+
+ /**
+ * Returns a collection containing those threads that may be
+ * waiting on the given condition associated with this lock.
+ * Because the actual set of threads may change dynamically while
+ * constructing this result, the returned collection is only a
+ * best-effort estimate. The elements of the returned collection
+ * are in no particular order. This method is designed to
+ * facilitate construction of subclasses that provide more
+ * extensive condition monitoring facilities.
+ *
+ * @param condition the condition
+ * @return the collection of threads
+ * @throws IllegalMonitorStateException if this lock is not held
+ * @throws IllegalArgumentException if the given condition is
+ * not associated with this lock
+ * @throws NullPointerException if the condition is null
+ */
+ /*protected Collection<Thread> getWaitingThreads(Condition condition) {
+ if (condition == null)
+ throw new NullPointerException();
+ if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
+ throw new IllegalArgumentException("not owner");
+ return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
+ }*/
+
+ /**
+ * Returns a string identifying this lock, as well as its lock state.
+ * The state, in brackets, includes either the String {@code "Unlocked"}
+ * or the String {@code "Locked by"} followed by the
+ * {@linkplain Thread#getName name} of the owning thread.
+ *
+ * @return a string identifying this lock, as well as its lock state
+ */
+ /*public String toString() {
+ Thread o = sync.getOwner();
+ return super.toString() + ((o == null) ?
+ "[Unlocked]" :
+ "[Locked by thread " + o.getName() + "]");
+ }*/
+}
--- /dev/null
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+/*package java.util.concurrent;
+import java.util.*;
+import java.util.concurrent.locks.*;
+import java.util.concurrent.atomic.*;*/
+
+/**
+ * A counting semaphore. Conceptually, a semaphore maintains a set of
+ * permits. Each {@link #acquire} blocks if necessary until a permit is
+ * available, and then takes it. Each {@link #release} adds a permit,
+ * potentially releasing a blocking acquirer.
+ * However, no actual permit objects are used; the {@code Semaphore} just
+ * keeps a count of the number available and acts accordingly.
+ *
+ * <p>Semaphores are often used to restrict the number of threads than can
+ * access some (physical or logical) resource. For example, here is
+ * a class that uses a semaphore to control access to a pool of items:
+ * <pre>
+ * class Pool {
+ * private static final int MAX_AVAILABLE = 100;
+ * private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
+ *
+ * public Object getItem() throws InterruptedException {
+ * available.acquire();
+ * return getNextAvailableItem();
+ * }
+ *
+ * public void putItem(Object x) {
+ * if (markAsUnused(x))
+ * available.release();
+ * }
+ *
+ * // Not a particularly efficient data structure; just for demo
+ *
+ * protected Object[] items = ... whatever kinds of items being managed
+ * protected boolean[] used = new boolean[MAX_AVAILABLE];
+ *
+ * protected synchronized Object getNextAvailableItem() {
+ * for (int i = 0; i < MAX_AVAILABLE; ++i) {
+ * if (!used[i]) {
+ * used[i] = true;
+ * return items[i];
+ * }
+ * }
+ * return null; // not reached
+ * }
+ *
+ * protected synchronized boolean markAsUnused(Object item) {
+ * for (int i = 0; i < MAX_AVAILABLE; ++i) {
+ * if (item == items[i]) {
+ * if (used[i]) {
+ * used[i] = false;
+ * return true;
+ * } else
+ * return false;
+ * }
+ * }
+ * return false;
+ * }
+ *
+ * }
+ * </pre>
+ *
+ * <p>Before obtaining an item each thread must acquire a permit from
+ * the semaphore, guaranteeing that an item is available for use. When
+ * the thread has finished with the item it is returned back to the
+ * pool and a permit is returned to the semaphore, allowing another
+ * thread to acquire that item. Note that no synchronization lock is
+ * held when {@link #acquire} is called as that would prevent an item
+ * from being returned to the pool. The semaphore encapsulates the
+ * synchronization needed to restrict access to the pool, separately
+ * from any synchronization needed to maintain the consistency of the
+ * pool itself.
+ *
+ * <p>A semaphore initialized to one, and which is used such that it
+ * only has at most one permit available, can serve as a mutual
+ * exclusion lock. This is more commonly known as a <em>binary
+ * semaphore</em>, because it only has two states: one permit
+ * available, or zero permits available. When used in this way, the
+ * binary semaphore has the property (unlike many {@link Lock}
+ * implementations), that the "lock" can be released by a
+ * thread other than the owner (as semaphores have no notion of
+ * ownership). This can be useful in some specialized contexts, such
+ * as deadlock recovery.
+ *
+ * <p> The constructor for this class optionally accepts a
+ * <em>fairness</em> parameter. When set false, this class makes no
+ * guarantees about the order in which threads acquire permits. In
+ * particular, <em>barging</em> is permitted, that is, a thread
+ * invoking {@link #acquire} can be allocated a permit ahead of a
+ * thread that has been waiting - logically the new thread places itself at
+ * the head of the queue of waiting threads. When fairness is set true, the
+ * semaphore guarantees that threads invoking any of the {@link
+ * #acquire() acquire} methods are selected to obtain permits in the order in
+ * which their invocation of those methods was processed
+ * (first-in-first-out; FIFO). Note that FIFO ordering necessarily
+ * applies to specific internal points of execution within these
+ * methods. So, it is possible for one thread to invoke
+ * {@code acquire} before another, but reach the ordering point after
+ * the other, and similarly upon return from the method.
+ * Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not
+ * honor the fairness setting, but will take any permits that are
+ * available.
+ *
+ * <p>Generally, semaphores used to control resource access should be
+ * initialized as fair, to ensure that no thread is starved out from
+ * accessing a resource. When using semaphores for other kinds of
+ * synchronization control, the throughput advantages of non-fair
+ * ordering often outweigh fairness considerations.
+ *
+ * <p>This class also provides convenience methods to {@link
+ * #acquire(int) acquire} and {@link #release(int) release} multiple
+ * permits at a time. Beware of the increased risk of indefinite
+ * postponement when these methods are used without fairness set true.
+ *
+ * <p>Memory consistency effects: Actions in a thread prior to calling
+ * a "release" method such as {@code release()}
+ * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
+ * actions following a successful "acquire" method such as {@code acquire()}
+ * in another thread.
+ *
+ * @since 1.5
+ * @author Doug Lea
+ *
+ */
+
+public class Semaphore implements /*java.io.*/Serializable {
+ private static final long serialVersionUID = -3222578661600680210L;
+ /** All mechanics via AbstractQueuedSynchronizer subclass */
+ //private final Sync sync;
+
+ /**
+ * Synchronization implementation for semaphore. Uses AQS state
+ * to represent permits. Subclassed into fair and nonfair
+ * versions.
+ */
+ /* abstract static class Sync extends AbstractQueuedSynchronizer {
+ private static final long serialVersionUID = 1192457210091910933L;
+
+ Sync(int permits) {
+ setState(permits);
+ }
+
+ final int getPermits() {
+ return getState();
+ }
+
+ final int nonfairTryAcquireShared(int acquires) {
+ for (;;) {
+ int available = getState();
+ int remaining = available - acquires;
+ if (remaining < 0 ||
+ compareAndSetState(available, remaining))
+ return remaining;
+ }
+ }
+
+ protected final boolean tryReleaseShared(int releases) {
+ for (;;) {
+ int p = getState();
+ if (compareAndSetState(p, p + releases))
+ return true;
+ }
+ }
+
+ final void reducePermits(int reductions) {
+ for (;;) {
+ int current = getState();
+ int next = current - reductions;
+ if (compareAndSetState(current, next))
+ return;
+ }
+ }
+
+ final int drainPermits() {
+ for (;;) {
+ int current = getState();
+ if (current == 0 || compareAndSetState(current, 0))
+ return current;
+ }
+ }
+ }*/
+
+ /**
+ * NonFair version
+ */
+ /*final static class NonfairSync extends Sync {
+ private static final long serialVersionUID = -2694183684443567898L;
+
+ NonfairSync(int permits) {
+ super(permits);
+ }
+
+ protected int tryAcquireShared(int acquires) {
+ return nonfairTryAcquireShared(acquires);
+ }
+ }*/
+
+ /**
+ * Fair version
+ */
+ /*final static class FairSync extends Sync {
+ private static final long serialVersionUID = 2014338818796000944L;
+
+ FairSync(int permits) {
+ super(permits);
+ }
+
+ protected int tryAcquireShared(int acquires) {
+ Thread current = Thread.currentThread();
+ for (;;) {
+ Thread first = getFirstQueuedThread();
+ if (first != null && first != current)
+ return -1;
+ int available = getState();
+ int remaining = available - acquires;
+ if (remaining < 0 ||
+ compareAndSetState(available, remaining))
+ return remaining;
+ }
+ }
+ }*/
+
+ /**
+ * Creates a {@code Semaphore} with the given number of
+ * permits and nonfair fairness setting.
+ *
+ * @param permits the initial number of permits available.
+ * This value may be negative, in which case releases
+ * must occur before any acquires will be granted.
+ */
+ public Semaphore(int permits) {
+ //sync = new NonfairSync(permits);
+ }
+
+ /**
+ * Creates a {@code Semaphore} with the given number of
+ * permits and the given fairness setting.
+ *
+ * @param permits the initial number of permits available.
+ * This value may be negative, in which case releases
+ * must occur before any acquires will be granted.
+ * @param fair {@code true} if this semaphore will guarantee
+ * first-in first-out granting of permits under contention,
+ * else {@code false}
+ */
+ public Semaphore(int permits, boolean fair) {
+ //sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
+ }
+
+ /**
+ * Acquires a permit from this semaphore, blocking until one is
+ * available, or the thread is {@linkplain Thread#interrupt interrupted}.
+ *
+ * <p>Acquires a permit, if one is available and returns immediately,
+ * reducing the number of available permits by one.
+ *
+ * <p>If no permit is available then the current thread becomes
+ * disabled for thread scheduling purposes and lies dormant until
+ * one of two things happens:
+ * <ul>
+ * <li>Some other thread invokes the {@link #release} method for this
+ * semaphore and the current thread is next to be assigned a permit; or
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts}
+ * the current thread.
+ * </ul>
+ *
+ * <p>If the current thread:
+ * <ul>
+ * <li>has its interrupted status set on entry to this method; or
+ * <li>is {@linkplain Thread#interrupt interrupted} while waiting
+ * for a permit,
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared.
+ *
+ * @throws InterruptedException if the current thread is interrupted
+ */
+ public void acquire() throws InterruptedException {
+ //sync.acquireSharedInterruptibly(1);
+ System.out.println("Unimplemented Semaphore.acquire()!");
+ }
+
+ /**
+ * Acquires a permit from this semaphore, blocking until one is
+ * available.
+ *
+ * <p>Acquires a permit, if one is available and returns immediately,
+ * reducing the number of available permits by one.
+ *
+ * <p>If no permit is available then the current thread becomes
+ * disabled for thread scheduling purposes and lies dormant until
+ * some other thread invokes the {@link #release} method for this
+ * semaphore and the current thread is next to be assigned a permit.
+ *
+ * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
+ * while waiting for a permit then it will continue to wait, but the
+ * time at which the thread is assigned a permit may change compared to
+ * the time it would have received the permit had no interruption
+ * occurred. When the thread does return from this method its interrupt
+ * status will be set.
+ */
+ /*public void acquireUninterruptibly() {
+ sync.acquireShared(1);
+ }*/
+
+ /**
+ * Acquires a permit from this semaphore, only if one is available at the
+ * time of invocation.
+ *
+ * <p>Acquires a permit, if one is available and returns immediately,
+ * with the value {@code true},
+ * reducing the number of available permits by one.
+ *
+ * <p>If no permit is available then this method will return
+ * immediately with the value {@code false}.
+ *
+ * <p>Even when this semaphore has been set to use a
+ * fair ordering policy, a call to {@code tryAcquire()} <em>will</em>
+ * immediately acquire a permit if one is available, whether or not
+ * other threads are currently waiting.
+ * This "barging" behavior can be useful in certain
+ * circumstances, even though it breaks fairness. If you want to honor
+ * the fairness setting, then use
+ * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
+ * which is almost equivalent (it also detects interruption).
+ *
+ * @return {@code true} if a permit was acquired and {@code false}
+ * otherwise
+ */
+ /*public boolean tryAcquire() {
+ return sync.nonfairTryAcquireShared(1) >= 0;
+ }*/
+
+ /**
+ * Acquires a permit from this semaphore, if one becomes available
+ * within the given waiting time and the current thread has not
+ * been {@linkplain Thread#interrupt interrupted}.
+ *
+ * <p>Acquires a permit, if one is available and returns immediately,
+ * with the value {@code true},
+ * reducing the number of available permits by one.
+ *
+ * <p>If no permit is available then the current thread becomes
+ * disabled for thread scheduling purposes and lies dormant until
+ * one of three things happens:
+ * <ul>
+ * <li>Some other thread invokes the {@link #release} method for this
+ * semaphore and the current thread is next to be assigned a permit; or
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts}
+ * the current thread; or
+ * <li>The specified waiting time elapses.
+ * </ul>
+ *
+ * <p>If a permit is acquired then the value {@code true} is returned.
+ *
+ * <p>If the current thread:
+ * <ul>
+ * <li>has its interrupted status set on entry to this method; or
+ * <li>is {@linkplain Thread#interrupt interrupted} while waiting
+ * to acquire a permit,
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared.
+ *
+ * <p>If the specified waiting time elapses then the value {@code false}
+ * is returned. If the time is less than or equal to zero, the method
+ * will not wait at all.
+ *
+ * @param timeout the maximum time to wait for a permit
+ * @param unit the time unit of the {@code timeout} argument
+ * @return {@code true} if a permit was acquired and {@code false}
+ * if the waiting time elapsed before a permit was acquired
+ * @throws InterruptedException if the current thread is interrupted
+ */
+ /*public boolean tryAcquire(long timeout, TimeUnit unit)
+ throws InterruptedException {
+ return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
+ }*/
+
+ /**
+ * Releases a permit, returning it to the semaphore.
+ *
+ * <p>Releases a permit, increasing the number of available permits by
+ * one. If any threads are trying to acquire a permit, then one is
+ * selected and given the permit that was just released. That thread
+ * is (re)enabled for thread scheduling purposes.
+ *
+ * <p>There is no requirement that a thread that releases a permit must
+ * have acquired that permit by calling {@link #acquire}.
+ * Correct usage of a semaphore is established by programming convention
+ * in the application.
+ */
+ public void release() {
+ //sync.releaseShared(1);
+ System.out.println("Unimplemented Semaphore.release()!");
+ }
+
+ /**
+ * Acquires the given number of permits from this semaphore,
+ * blocking until all are available,
+ * or the thread is {@linkplain Thread#interrupt interrupted}.
+ *
+ * <p>Acquires the given number of permits, if they are available,
+ * and returns immediately, reducing the number of available permits
+ * by the given amount.
+ *
+ * <p>If insufficient permits are available then the current thread becomes
+ * disabled for thread scheduling purposes and lies dormant until
+ * one of two things happens:
+ * <ul>
+ * <li>Some other thread invokes one of the {@link #release() release}
+ * methods for this semaphore, the current thread is next to be assigned
+ * permits and the number of available permits satisfies this request; or
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts}
+ * the current thread.
+ * </ul>
+ *
+ * <p>If the current thread:
+ * <ul>
+ * <li>has its interrupted status set on entry to this method; or
+ * <li>is {@linkplain Thread#interrupt interrupted} while waiting
+ * for a permit,
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared.
+ * Any permits that were to be assigned to this thread are instead
+ * assigned to other threads trying to acquire permits, as if
+ * permits had been made available by a call to {@link #release()}.
+ *
+ * @param permits the number of permits to acquire
+ * @throws InterruptedException if the current thread is interrupted
+ * @throws IllegalArgumentException if {@code permits} is negative
+ */
+ public void acquire(int permits) throws InterruptedException {
+ /*if (permits < 0) throw new IllegalArgumentException();
+ sync.acquireSharedInterruptibly(permits);*/
+ System.out.println("Unimplemented Semaphore.acquire(int)!");
+ }
+
+ /**
+ * Acquires the given number of permits from this semaphore,
+ * blocking until all are available.
+ *
+ * <p>Acquires the given number of permits, if they are available,
+ * and returns immediately, reducing the number of available permits
+ * by the given amount.
+ *
+ * <p>If insufficient permits are available then the current thread becomes
+ * disabled for thread scheduling purposes and lies dormant until
+ * some other thread invokes one of the {@link #release() release}
+ * methods for this semaphore, the current thread is next to be assigned
+ * permits and the number of available permits satisfies this request.
+ *
+ * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
+ * while waiting for permits then it will continue to wait and its
+ * position in the queue is not affected. When the thread does return
+ * from this method its interrupt status will be set.
+ *
+ * @param permits the number of permits to acquire
+ * @throws IllegalArgumentException if {@code permits} is negative
+ *
+ */
+ /*public void acquireUninterruptibly(int permits) {
+ if (permits < 0) throw new IllegalArgumentException();
+ sync.acquireShared(permits);
+ }*/
+
+ /**
+ * Acquires the given number of permits from this semaphore, only
+ * if all are available at the time of invocation.
+ *
+ * <p>Acquires the given number of permits, if they are available, and
+ * returns immediately, with the value {@code true},
+ * reducing the number of available permits by the given amount.
+ *
+ * <p>If insufficient permits are available then this method will return
+ * immediately with the value {@code false} and the number of available
+ * permits is unchanged.
+ *
+ * <p>Even when this semaphore has been set to use a fair ordering
+ * policy, a call to {@code tryAcquire} <em>will</em>
+ * immediately acquire a permit if one is available, whether or
+ * not other threads are currently waiting. This
+ * "barging" behavior can be useful in certain
+ * circumstances, even though it breaks fairness. If you want to
+ * honor the fairness setting, then use {@link #tryAcquire(int,
+ * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
+ * which is almost equivalent (it also detects interruption).
+ *
+ * @param permits the number of permits to acquire
+ * @return {@code true} if the permits were acquired and
+ * {@code false} otherwise
+ * @throws IllegalArgumentException if {@code permits} is negative
+ */
+ /*public boolean tryAcquire(int permits) {
+ if (permits < 0) throw new IllegalArgumentException();
+ return sync.nonfairTryAcquireShared(permits) >= 0;
+ }*/
+
+ /**
+ * Acquires the given number of permits from this semaphore, if all
+ * become available within the given waiting time and the current
+ * thread has not been {@linkplain Thread#interrupt interrupted}.
+ *
+ * <p>Acquires the given number of permits, if they are available and
+ * returns immediately, with the value {@code true},
+ * reducing the number of available permits by the given amount.
+ *
+ * <p>If insufficient permits are available then
+ * the current thread becomes disabled for thread scheduling
+ * purposes and lies dormant until one of three things happens:
+ * <ul>
+ * <li>Some other thread invokes one of the {@link #release() release}
+ * methods for this semaphore, the current thread is next to be assigned
+ * permits and the number of available permits satisfies this request; or
+ * <li>Some other thread {@linkplain Thread#interrupt interrupts}
+ * the current thread; or
+ * <li>The specified waiting time elapses.
+ * </ul>
+ *
+ * <p>If the permits are acquired then the value {@code true} is returned.
+ *
+ * <p>If the current thread:
+ * <ul>
+ * <li>has its interrupted status set on entry to this method; or
+ * <li>is {@linkplain Thread#interrupt interrupted} while waiting
+ * to acquire the permits,
+ * </ul>
+ * then {@link InterruptedException} is thrown and the current thread's
+ * interrupted status is cleared.
+ * Any permits that were to be assigned to this thread, are instead
+ * assigned to other threads trying to acquire permits, as if
+ * the permits had been made available by a call to {@link #release()}.
+ *
+ * <p>If the specified waiting time elapses then the value {@code false}
+ * is returned. If the time is less than or equal to zero, the method
+ * will not wait at all. Any permits that were to be assigned to this
+ * thread, are instead assigned to other threads trying to acquire
+ * permits, as if the permits had been made available by a call to
+ * {@link #release()}.
+ *
+ * @param permits the number of permits to acquire
+ * @param timeout the maximum time to wait for the permits
+ * @param unit the time unit of the {@code timeout} argument
+ * @return {@code true} if all permits were acquired and {@code false}
+ * if the waiting time elapsed before all permits were acquired
+ * @throws InterruptedException if the current thread is interrupted
+ * @throws IllegalArgumentException if {@code permits} is negative
+ */
+ /*public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
+ throws InterruptedException {
+ if (permits < 0) throw new IllegalArgumentException();
+ return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
+ }*/
+
+ /**
+ * Releases the given number of permits, returning them to the semaphore.
+ *
+ * <p>Releases the given number of permits, increasing the number of
+ * available permits by that amount.
+ * If any threads are trying to acquire permits, then one
+ * is selected and given the permits that were just released.
+ * If the number of available permits satisfies that thread's request
+ * then that thread is (re)enabled for thread scheduling purposes;
+ * otherwise the thread will wait until sufficient permits are available.
+ * If there are still permits available
+ * after this thread's request has been satisfied, then those permits
+ * are assigned in turn to other threads trying to acquire permits.
+ *
+ * <p>There is no requirement that a thread that releases a permit must
+ * have acquired that permit by calling {@link Semaphore#acquire acquire}.
+ * Correct usage of a semaphore is established by programming convention
+ * in the application.
+ *
+ * @param permits the number of permits to release
+ * @throws IllegalArgumentException if {@code permits} is negative
+ */
+ public void release(int permits) {
+ /*if (permits < 0) throw new IllegalArgumentException();
+ sync.releaseShared(permits);*/
+ System.out.println("Unimplemented Semaphore.release()!");
+ }
+
+ /**
+ * Returns the current number of permits available in this semaphore.
+ *
+ * <p>This method is typically used for debugging and testing purposes.
+ *
+ * @return the number of permits available in this semaphore
+ */
+ /*public int availablePermits() {
+ return sync.getPermits();
+ }*/
+
+ /**
+ * Acquires and returns all permits that are immediately available.
+ *
+ * @return the number of permits acquired
+ */
+ /*public int drainPermits() {
+ return sync.drainPermits();
+ }*/
+
+ /**
+ * Shrinks the number of available permits by the indicated
+ * reduction. This method can be useful in subclasses that use
+ * semaphores to track resources that become unavailable. This
+ * method differs from {@code acquire} in that it does not block
+ * waiting for permits to become available.
+ *
+ * @param reduction the number of permits to remove
+ * @throws IllegalArgumentException if {@code reduction} is negative
+ */
+ /*protected void reducePermits(int reduction) {
+ if (reduction < 0) throw new IllegalArgumentException();
+ sync.reducePermits(reduction);
+ }*/
+
+ /**
+ * Returns {@code true} if this semaphore has fairness set true.
+ *
+ * @return {@code true} if this semaphore has fairness set true
+ */
+ /*public boolean isFair() {
+ return sync instanceof FairSync;
+ }*/
+
+ /**
+ * Queries whether any threads are waiting to acquire. Note that
+ * because cancellations may occur at any time, a {@code true}
+ * return does not guarantee that any other thread will ever
+ * acquire. This method is designed primarily for use in
+ * monitoring of the system state.
+ *
+ * @return {@code true} if there may be other threads waiting to
+ * acquire the lock
+ */
+ /*public final boolean hasQueuedThreads() {
+ return sync.hasQueuedThreads();
+ }*/
+
+ /**
+ * Returns an estimate of the number of threads waiting to acquire.
+ * The value is only an estimate because the number of threads may
+ * change dynamically while this method traverses internal data
+ * structures. This method is designed for use in monitoring of the
+ * system state, not for synchronization control.
+ *
+ * @return the estimated number of threads waiting for this lock
+ */
+ /*public final int getQueueLength() {
+ return sync.getQueueLength();
+ }*/
+
+ /**
+ * Returns a collection containing threads that may be waiting to acquire.
+ * Because the actual set of threads may change dynamically while
+ * constructing this result, the returned collection is only a best-effort
+ * estimate. The elements of the returned collection are in no particular
+ * order. This method is designed to facilitate construction of
+ * subclasses that provide more extensive monitoring facilities.
+ *
+ * @return the collection of threads
+ */
+ /*protected Collection<Thread> getQueuedThreads() {
+ return sync.getQueuedThreads();
+ }*/
+
+ /**
+ * Returns a string identifying this semaphore, as well as its state.
+ * The state, in brackets, includes the String {@code "Permits ="}
+ * followed by the number of permits.
+ *
+ * @return a string identifying this semaphore, as well as its state
+ */
+ /*public String toString() {
+ return super.toString() + "[Permits = " + sync.getPermits() + "]";
+ }*/
+}
--- /dev/null
+/* Serializable.java -- Interface to indicate a class may be serialized
+ Copyright (C) 1998, 1999, 2001, 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.io;
+
+/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
+ * Status: Believed complete
+ */
+
+/**
+ * This interface has no methods. It simply serves to indicate that
+ * the implementing class may be serialized.
+ *
+ * @author Aaron M. Renn (arenn@urbanophile.com)
+ * @author Warren Levy (warrenl@cygnus.com)
+ */
+public interface Serializable
+{
+} // interface Serializable
--- /dev/null
+/* ThreadLocal -- a variable with a unique value per thread
+ Copyright (C) 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package java.lang;
+
+/**
+ * ThreadLocal objects have a different state associated with every
+ * Thread that accesses them. Every access to the ThreadLocal object
+ * (through the <code>get()</code> and <code>set()</code> methods)
+ * only affects the state of the object as seen by the currently
+ * executing Thread.
+ *
+ * <p>The first time a ThreadLocal object is accessed on a particular
+ * Thread, the state for that Thread's copy of the local variable is set by
+ * executing the method <code>initialValue()</code>.
+ * </p>
+ *
+ * <p>An example how you can use this:
+ * </p>
+ *
+ * <pre>
+ * class Connection
+ * {
+ * private static ThreadLocal owner = new ThreadLocal()
+ * {
+ * public Object initialValue()
+ * {
+ * return("nobody");
+ * }
+ * };
+ * ...
+ * }
+ * </pre>
+ *
+ * <p>Now all instances of connection can see who the owner of the currently
+ * executing Thread is by calling <code>owner.get()</code>. By default any
+ * Thread would be associated with 'nobody'. But the Connection object could
+ * offer a method that changes the owner associated with the Thread on
+ * which the method was called by calling <code>owner.put("somebody")</code>.
+ * (Such an owner changing method should then be guarded by security checks.)
+ * </p>
+ *
+ * <p>When a Thread is garbage collected all references to values of
+ * the ThreadLocal objects associated with that Thread are removed.
+ * </p>
+ *
+ * @author Mark Wielaard (mark@klomp.org)
+ * @author Eric Blake (ebb9@email.byu.edu)
+ * @since 1.2
+ * @status updated to 1.5
+ */
+public class ThreadLocal/*<T>*/
+{
+ /**
+ * Placeholder to distinguish between uninitialized and null set by the
+ * user. Do not expose this to the public. Package visible for use by
+ * InheritableThreadLocal
+ */
+ static final Object sentinel = new Object();
+
+ /**
+ * The base for the computation of the next hash for a thread local.
+ */
+ private static int nextHashBase = 1;
+
+ /**
+ * Allocate a new hash.
+ */
+ private synchronized int computeNextHash()
+ {
+ return nextHashBase++ * 6709;
+ }
+
+ /**
+ * Hash code computed for ThreadLocalMap
+ */
+ final int fastHash;
+
+ /**
+ * Creates a ThreadLocal object without associating any value to it yet.
+ */
+ public ThreadLocal()
+ {
+ fastHash = computeNextHash();
+ }
+
+ /**
+ * Called once per thread on the first invocation of get(), if set() was
+ * not already called. The default implementation returns <code>null</code>.
+ * Often, this method is overridden to create the appropriate initial object
+ * for the current thread's view of the ThreadLocal.
+ *
+ * @return the initial value of the variable in this thread
+ */
+ protected Object/*T*/ initialValue()
+ {
+ return null;
+ }
+
+ /**
+ * Gets the value associated with the ThreadLocal object for the currently
+ * executing Thread. If this is the first time the current thread has called
+ * get(), and it has not already called set(), the value is obtained by
+ * <code>initialValue()</code>.
+ *
+ * @return the value of the variable in this thread
+ */
+ public Object/*T*/ get()
+ {
+ ThreadLocalMap map = Thread.getThreadLocals();
+ // Note that we don't have to synchronize, as only this thread will
+ // ever modify the map.
+ Object/*T*/ value = /*(T)*/ map.get(this);
+ if (value == sentinel)
+ {
+ value = initialValue();
+ map.set(this, value);
+ }
+ return value;
+ }
+
+ /**
+ * Sets the value associated with the ThreadLocal object for the currently
+ * executing Thread. This overrides any existing value associated with the
+ * current Thread and prevents <code>initialValue()</code> from being
+ * called if this is the first access to this ThreadLocal in this Thread.
+ *
+ * @param value the value to set this thread's view of the variable to
+ */
+ public void set(Object/*T*/ value)
+ {
+ ThreadLocalMap map = Thread.getThreadLocals();
+ // Note that we don't have to synchronize, as only this thread will
+ // ever modify the map.
+ map.set(this, value);
+ }
+
+ /**
+ * Removes the value associated with the ThreadLocal object for the
+ * currently executing Thread.
+ * @since 1.5
+ */
+ public void remove()
+ {
+ ThreadLocalMap map = Thread.getThreadLocals();
+ map.remove(this);
+ }
+}
--- /dev/null
+/* ThreadLocalMap -- a weak hash map optimised for ThreadLocal storage
+ Copyright (C) 2000, 2002, 2003, 2004, 2005, 2006, 2007
+ Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package java.lang;
+
+//import java.lang.ref.WeakReference;
+
+/**
+ * ThreadLocalMap is the basic storage for the map of ThreadLocal instance
+ * to a thread's current value.
+ *
+ * Some applications really work out ThreadLocals, leading to this
+ * optimized implementation.
+ */
+final class ThreadLocalMap
+{
+ /**
+ * The log (base 2) of the initial size of the map
+ */
+ private static final int LOG_INITIAL_SIZE = 3;
+
+ /**
+ * The maximum occupancy rate (after which we grow)
+ */
+ private static final float MAX_OCCUPANCY = 0.7f;
+
+ /**
+ * The target occupancy rate.
+ */
+ private static final float TARGET_OCCUPANCY = 0.5f;
+
+ /**
+ * The deleted entry sentinel value.
+ */
+ private static final Entry deletedEntry = new Entry(null);
+
+ /**
+ * Constructor
+ */
+ ThreadLocalMap()
+ {
+ /* Dummy value to ensure fast path can be optimized */
+ entries = new Entry[1];
+ hashMask = 0;
+ count = 0;
+ }
+
+ /**
+ * The map entries
+ */
+ private Entry[] entries;
+
+ /**
+ * Used for start index computation
+ */
+ private int hashMask;
+
+ /**
+ * The number of entries currently in the map
+ */
+ private int count;
+
+ /**
+ * Create or grow the table to the specified size. The size must be a
+ * power of two for the efficient mask/hash computation.
+ *
+ * @param newSize The new table size.
+ */
+ private void newEntryArray(int newSize)
+ {
+ int mask = newSize - 1;
+ Entry[] oldEntries = this.entries;
+ this.entries = new Entry[newSize];
+ this.hashMask = mask;
+
+ /* Copy old entries to new table */
+ count = 0;
+ if (oldEntries != null)
+ {
+ //for(Entry e: oldEntries)
+ for(int j = 0; j < oldEntries.length; j++)
+ {
+ e = oldEntries[j];
+ if (e != null)
+ {
+ ThreadLocal/*<?>*/ key = e.get();
+ if (e != deletedEntry && key != null)
+ {
+ for(int i = key.fastHash & mask;; i = (i + 1) & mask)
+ {
+ if (entries[i] == null)
+ {
+ entries[i] = e;
+ count++;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * We have run out of space in our locals. We use this as the
+ * trigger to attempt to find unused slots as ThreadLocals have
+ * died. If we recover any slots this way then we do not grow.
+ */
+ private void overflow()
+ {
+ /* First 'actual' use */
+ if (entries.length == 1)
+ {
+ newEntryArray(1 << LOG_INITIAL_SIZE);
+ return;
+ }
+
+ /* Attempt to recover unused slots */
+ int deleted = 0;
+ for(int i=0; i < entries.length; i++)
+ {
+ Entry e = entries[i];
+ if (e != null)
+ {
+ if (e == deletedEntry)
+ {
+ deleted++;
+ }
+ else if (e.get() == null)
+ {
+ entries[i] = deletedEntry;
+ deleted++;
+ }
+ }
+ }
+
+ if ((count-deleted) <= (TARGET_OCCUPANCY * entries.length))
+ {
+ /* We currently rehash by simple reallocating into a same-sized table.
+ * An alternative would be to implement a clever hashing algorithm but
+ * as this happens infrequently this seems preferred */
+ newEntryArray(entries.length);
+ return;
+ }
+
+ /* Double the size */
+ newEntryArray(entries.length << 1);
+ }
+
+ /**
+ * This is the class that is used to refer to a thread local weakly.
+ *
+ * As we want to minimize indirections we extend WeakReference.
+ */
+ static final class Entry /*extends WeakReference<ThreadLocal<?>>*/ {
+ /**
+ * The value stored in this slot
+ */
+ Object value;
+ ThreadLocal key;
+
+ /**
+ * Constructor
+ */
+ Entry(ThreadLocal/*<?>*/ threadLocal) {
+ //super(threadLocal);
+ key = threadLocal;
+ }
+
+ ThreadLocal get() {
+ return key;
+ }
+ }
+
+ /**
+ * Gets the value associated with the ThreadLocal object for the currently
+ * executing Thread. If this is the first time the current thread has called
+ * get(), and it has not already called set(), the sentinel value is returned.
+ *
+ * @return the value of the variable in this thread, or sentinel if not present.
+ */
+ public Object get(ThreadLocal/*<?>*/ key)
+ {
+ int mask = this.hashMask;
+ for(int i = key.fastHash & mask;; i = (i + 1) & mask) {
+ Entry e = entries[i];
+ if (e != null) {
+ if (e.get() == key) {
+ return e.value;
+ }
+ } else {
+ return ThreadLocal.sentinel;
+ }
+ }
+ }
+
+ /**
+ * Sets the value associated with the ThreadLocal object for the currently
+ * executing Thread. This overrides any existing value associated with the
+ * current Thread and prevents <code>initialValue()</code> from being
+ * called if this is the first access to this ThreadLocal in this Thread.
+ *
+ * @param value the value to set this thread's view of the variable to
+ */
+ public void set(ThreadLocal/*<?>*/ key, Object value)
+ {
+ /* Overflow ? */
+ if ((count+1) >= (MAX_OCCUPANCY * entries.length))
+ {
+ overflow();
+ }
+
+ /* Set the entry */
+ int mask = this.hashMask;
+ for(int i = key.fastHash & mask;; i = (i + 1) & mask)
+ {
+ Entry e = entries[i];
+ if (e == null || e == deletedEntry)
+ {
+ /* Create entry */
+ if (e == null) count++;
+ entries[i] = e = new Entry(key);
+ e.value = value;
+ return;
+ }
+ else
+ {
+ ThreadLocal/*<?>*/ entryKey = e.get();
+ if (entryKey == null)
+ {
+ entries[i] = deletedEntry;
+ }
+ else if (entryKey == key)
+ {
+ /* Update entry */
+ e.value = value;
+ return;
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes the value associated with the ThreadLocal object for the
+ * currently executing Thread.
+ * @since 1.5
+ */
+ public void remove(ThreadLocal/*<?>*/ key)
+ {
+ int mask = this.hashMask;
+ for(int i = key.fastHash & mask;; i = (i + 1) & mask)
+ {
+ Entry e = entries[i];
+ if (e != null)
+ {
+ ThreadLocal/*<?>*/ entryKey = e.get();
+ if (entryKey != key)
+ {
+ if (entryKey == null) {
+ entries[i] = deletedEntry;
+ }
+ continue;
+ }
+ else
+ {
+ /* Remove from the table */
+ entries[i] = deletedEntry;
+ }
+ }
+ return;
+ }
+ }
+
+ /**
+ * Clear out the map. Done once during thread death.
+ */
+ void clear() {
+ entries = null;
+ }
+
+ /**
+ * Inherit all the InheritableThreadLocal instances from the given parent.
+ *
+ * @param parentMap The map to inherit from.
+ */
+ /*public void inherit(ThreadLocalMap parentMap) {
+ for(Entry e: parentMap.entries)
+ {
+ if (e != null && e != deletedEntry)
+ {
+ ThreadLocal<?> key = e.get();
+ if (key instanceof InheritableThreadLocal)
+ {
+ set(key, ((InheritableThreadLocal)key).childValue(e.value));
+ }
+ }
+ }
+ }*/
+}