AtomicIntegerArraypublic AtomicIntegerArray(int[] array)
| |
AtomicIntegerArraypublic AtomicIntegerArray(int[] array)
|
AtomicIntegerArraypublic AtomicIntegerArray(int[] array)
|
lazySetpublic final void lazySet(int i, int newValue)
|
lazySetpublic final void lazySet(boolean newValue)
|
lazySetpublic final void lazySet(int newValue)
|
addAndGetpublic int addAndGet(T obj, int delta)
| |
addAndGetpublic int addAndGet(T obj, int delta)
|
addAndGetpublic int addAndGet(T obj, int delta)
|
compareAndSetpublic abstract boolean compareAndSet(T obj, int expect, int update)
| |
compareAndSetpublic abstract boolean compareAndSet(T obj, int expect, int update)
|
compareAndSetpublic abstract boolean compareAndSet(T obj, int expect, int update)
|
decrementAndGetpublic int decrementAndGet(T obj)
| |
decrementAndGetpublic int decrementAndGet(T obj)
|
decrementAndGetpublic int decrementAndGet(T obj)
|
getpublic abstract int get(T obj)
| |
getpublic abstract int get(T obj)
|
getpublic abstract int get(T obj)
|
getAndAddpublic int getAndAdd(T obj, int delta)
| |
getAndAddpublic int getAndAdd(T obj, int delta)
|
getAndAddpublic int getAndAdd(T obj, int delta)
|
getAndDecrementpublic int getAndDecrement(T obj)
| |
getAndDecrementpublic int getAndDecrement(T obj)
|
getAndDecrementpublic int getAndDecrement(T obj)
|
getAndIncrementpublic int getAndIncrement(T obj)
| |
getAndIncrementpublic int getAndIncrement(T obj)
|
getAndIncrementpublic int getAndIncrement(T obj)
|
getAndSetpublic int getAndSet(T obj, int newValue)
| |
getAndSetpublic int getAndSet(T obj, int newValue)
|
getAndSetpublic int getAndSet(T obj, int newValue)
|
incrementAndGetpublic int incrementAndGet(T obj)
| |
incrementAndGetpublic int incrementAndGet(T obj)
|
incrementAndGetpublic int incrementAndGet(T obj)
|
lazySetpublic abstract void lazySet(T obj, int newValue)
|
newUpdaterpublic static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)
| |
newUpdaterpublic static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)
|
newUpdaterpublic static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)
|
setpublic abstract void set(T obj, int newValue)
| |
setpublic abstract void set(T obj, int newValue)
|
setpublic abstract void set(T obj, int newValue)
|
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, int expect, int update)
| |
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, int expect, int update)
|
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, int expect, int update)
|
lazySetpublic final void lazySet(long newValue)
|
AtomicLongArraypublic AtomicLongArray(long[] array)
| |
AtomicLongArraypublic AtomicLongArray(long[] array)
|
AtomicLongArraypublic AtomicLongArray(long[] array)
|
lazySetpublic final void lazySet(int i, long newValue)
|
addAndGetpublic long addAndGet(T obj, long delta)
| |
addAndGetpublic long addAndGet(T obj, long delta)
|
addAndGetpublic long addAndGet(T obj, long delta)
|
compareAndSetpublic abstract boolean compareAndSet(T obj, long expect, long update)
| |
compareAndSetpublic abstract boolean compareAndSet(T obj, long expect, long update)
|
compareAndSetpublic abstract boolean compareAndSet(T obj, long expect, long update)
|
decrementAndGetpublic long decrementAndGet(T obj)
| |
decrementAndGetpublic long decrementAndGet(T obj)
|
decrementAndGetpublic long decrementAndGet(T obj)
|
getpublic abstract long get(T obj)
| |
getpublic abstract long get(T obj)
|
getpublic abstract long get(T obj)
|
getAndAddpublic long getAndAdd(T obj, long delta)
| |
getAndAddpublic long getAndAdd(T obj, long delta)
|
getAndAddpublic long getAndAdd(T obj, long delta)
|
getAndDecrementpublic long getAndDecrement(T obj)
| |
getAndDecrementpublic long getAndDecrement(T obj)
|
getAndDecrementpublic long getAndDecrement(T obj)
|
getAndIncrementpublic long getAndIncrement(T obj)
| |
getAndIncrementpublic long getAndIncrement(T obj)
|
getAndIncrementpublic long getAndIncrement(T obj)
|
getAndSetpublic long getAndSet(T obj, long newValue)
| |
getAndSetpublic long getAndSet(T obj, long newValue)
|
getAndSetpublic long getAndSet(T obj, long newValue)
|
incrementAndGetpublic long incrementAndGet(T obj)
| |
incrementAndGetpublic long incrementAndGet(T obj)
|
incrementAndGetpublic long incrementAndGet(T obj)
|
lazySetpublic abstract void lazySet(T obj, long newValue)
|
newUpdaterpublic static <U> AtomicLongFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)
| |
newUpdaterpublic static <U> AtomicLongFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)
|
newUpdaterpublic static <U> AtomicLongFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)
|
setpublic abstract void set(T obj, long newValue)
| |
setpublic abstract void set(T obj, long newValue)
|
setpublic abstract void set(T obj, long newValue)
|
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, long expect, long update)
| |
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, long expect, long update)
|
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, long expect, long update)
|
AtomicReferencepublic AtomicReference(V initialValue)
| |
AtomicReferencepublic AtomicReference(V initialValue)
|
AtomicReferencepublic AtomicReference(V initialValue)
|
compareAndSetpublic final boolean compareAndSet(V expect, V update)
| |
compareAndSetpublic final boolean compareAndSet(V expect, V update)
|
compareAndSetpublic final boolean compareAndSet(V expect, V update)
|
getpublic final V get()
| |
getpublic final V get()
|
getpublic final V get()
|
getAndSetpublic final V getAndSet(V newValue)
| |
getAndSetpublic final V getAndSet(V newValue)
|
getAndSetpublic final V getAndSet(V newValue)
|
lazySetpublic final void lazySet(V newValue)
|
setpublic final void set(V newValue)
| |
setpublic final void set(V newValue)
|
setpublic final void set(V newValue)
|
weakCompareAndSetpublic final boolean weakCompareAndSet(V expect, V update)
| |
weakCompareAndSetpublic final boolean weakCompareAndSet(V expect, V update)
|
weakCompareAndSetpublic final boolean weakCompareAndSet(V expect, V update)
|
AtomicReferenceArraypublic AtomicReferenceArray(E[] array)
| |
AtomicReferenceArraypublic AtomicReferenceArray(E[] array)
|
AtomicReferenceArraypublic AtomicReferenceArray(E[] array)
|
compareAndSetpublic final boolean compareAndSet(int i, E expect, E update)
| |
compareAndSetpublic final boolean compareAndSet(int i, E expect, E update)
|
compareAndSetpublic final boolean compareAndSet(int i, E expect, E update)
|
getpublic final E get(int i)
| |
getpublic final E get(int i)
|
getpublic final E get(int i)
|
getAndSetpublic final E getAndSet(int i, E newValue)
| |
getAndSetpublic final E getAndSet(int i, E newValue)
|
getAndSetpublic final E getAndSet(int i, E newValue)
|
lazySetpublic final void lazySet(int i, E newValue)
|
setpublic final void set(int i, E newValue)
| |
setpublic final void set(int i, E newValue)
|
setpublic final void set(int i, E newValue)
|
weakCompareAndSetpublic final boolean weakCompareAndSet(int i, E expect, E update)
| |
weakCompareAndSetpublic final boolean weakCompareAndSet(int i, E expect, E update)
|
weakCompareAndSetpublic final boolean weakCompareAndSet(int i, E expect, E update)
|
compareAndSetpublic abstract boolean compareAndSet(T obj, V expect, V update)
| |
compareAndSetpublic abstract boolean compareAndSet(T obj, V expect, V update)
|
compareAndSetpublic abstract boolean compareAndSet(T obj, V expect, V update)
|
getpublic abstract V get(T obj)
| |
getpublic abstract V get(T obj)
|
getpublic abstract V get(T obj)
|
getAndSetpublic V getAndSet(T obj, V newValue)
| |
getAndSetpublic V getAndSet(T obj, V newValue)
|
getAndSetpublic V getAndSet(T obj, V newValue)
|
lazySetpublic abstract void lazySet(T obj, V newValue)
|
newUpdaterpublic static <U,W> AtomicReferenceFieldUpdater<U,W> newUpdater(Class<U> tclass, Class<W> vclass, String fieldName)
| |
newUpdaterpublic static <U,W> AtomicReferenceFieldUpdater<U,W> newUpdater(Class<U> tclass, Class<W> vclass, String fieldName)
|
newUpdaterpublic static <U,W> AtomicReferenceFieldUpdater<U,W> newUpdater(Class<U> tclass, Class<W> vclass, String fieldName)
|
setpublic abstract void set(T obj, V newValue)
| |
setpublic abstract void set(T obj, V newValue)
|
setpublic abstract void set(T obj, V newValue)
|
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, V expect, V update)
| |
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, V expect, V update)
|
weakCompareAndSetpublic abstract boolean weakCompareAndSet(T obj, V expect, V update)
|
A synchronizer that may be exclusively owned by a thread. This class provides a basis for creating locks and related synchronizers that may entail a notion of ownership. The AbstractOwnableSynchronizer class itself does not manage or use this information. However, subclasses and tools may use appropriately maintained values to help control and monitor access and provide diagnostics.
|
AbstractOwnableSynchronizerprotected AbstractOwnableSynchronizer()
|
getExclusiveOwnerThreadprotected final Thread getExclusiveOwnerThread()
|
setExclusiveOwnerThreadprotected final void setExclusiveOwnerThread(Thread t)
|
A version of
|
AbstractQueuedLongSynchronizerprotected AbstractQueuedLongSynchronizer()
|
acquirepublic final void acquire(long arg)
|
acquireInterruptiblypublic final void acquireInterruptibly(long arg) throws InterruptedException
|
acquireSharedpublic final void acquireShared(long arg)
|
acquireSharedInterruptiblypublic final void acquireSharedInterruptibly(long arg) throws InterruptedException
|
getExclusiveQueuedThreadspublic final Collection<Thread> getExclusiveQueuedThreads()
|
getFirstQueuedThreadpublic final Thread getFirstQueuedThread()
|
getQueuedThreadspublic final Collection<Thread> getQueuedThreads()
|
getSharedQueuedThreadspublic final Collection<Thread> getSharedQueuedThreads()
|
getStateprotected final long getState()
|
getWaitQueueLengthpublic final int getWaitQueueLength(AbstractQueuedLongSynchronizer.ConditionObject condition)
|
getWaitingThreadspublic final Collection<Thread> getWaitingThreads(AbstractQueuedLongSynchronizer.ConditionObject condition)
|
hasWaiterspublic final boolean hasWaiters(AbstractQueuedLongSynchronizer.ConditionObject condition)
|
isHeldExclusivelyprotected boolean isHeldExclusively()
|
isQueuedpublic final boolean isQueued(Thread thread)
|
ownspublic final boolean owns(AbstractQueuedLongSynchronizer.ConditionObject condition)
|
releasepublic final boolean release(long arg)
|
releaseSharedpublic final boolean releaseShared(long arg)
|
setStateprotected final void setState(long newState)
|
toStringpublic String toString()
|
tryAcquireprotected boolean tryAcquire(long arg)
|
tryAcquireNanospublic final boolean tryAcquireNanos(long arg, long nanosTimeout) throws InterruptedException
|
tryAcquireSharedprotected long tryAcquireShared(long arg)
|
tryAcquireSharedNanospublic final boolean tryAcquireSharedNanos(long arg, long nanosTimeout) throws InterruptedException
|
tryReleaseprotected boolean tryRelease(long arg)
|
tryReleaseSharedprotected boolean tryReleaseShared(long arg)
|
Basic thread blocking primitives for creating locks and other synchronization classes. This class associates with each thread that uses it, a permit (in the sense of the Semaphore class). A call to park will return immediately if the permit is available, consuming it in the process; otherwise it may block. A call to unpark makes the permit available, if it was not already available. (Unlike with Semaphores though, permits do not accumulate. There is at most one.) Methods park and unpark provide efficient means of blocking and unblocking threads that do not encounter the problems that cause the deprecated methods Thread.suspend and Thread.resume to be unusable for such purposes: Races between one thread invoking park and another thread trying to unpark it will preserve liveness, due to the permit. Additionally, park will return if the caller's thread was interrupted, and timeout versions are supported. The park method may also return at any other time, for "no reason", so in general must be invoked within a loop that rechecks conditions upon return. In this sense park serves as an optimization of a "busy wait" that does not waste as much time spinning, but must be paired with an unpark to be effective. The three forms of park each also support a blocker object parameter. This object is recorded while the thread is blocked to permit monitoring and diagnostic tools to identify the reasons that threads are blocked. (Such tools may access blockers using method getBlocker(java.lang.Thread) .) The use of these forms rather than the original forms without this parameter is strongly encouraged. The normal argument to supply as a blocker within a lock implementation is this. These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. Sample Usage. Here is a sketch of a First-in-first-out non-reentrant lock class. class FIFOMutex { private AtomicBoolean locked = new AtomicBoolean(false); private Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>(); public void lock() { boolean wasInterrupted = false; Thread current = Thread.currentThread(); waiters.add(current); // Block while not first in queue or cannot acquire lock while (waiters.peek() != current || !locked.compareAndSet(false, true)) { LockSupport.park(this); if (Thread.interrupted()) // ignore interrupts while waiting wasInterrupted = true; } waiters.remove(); if (wasInterrupted) // reassert interrupt status on exit current.interrupt(); } public void unlock() { locked.set(false); LockSupport.unpark(waiters.peek()); } }
| |
Basic thread blocking primitives for creating locks and other synchronization classes. This class associates with each thread that uses it, a permit
(in the sense of the Methods park and unpark provide efficient means of blocking and unblocking threads that do not encounter the problems that cause the deprecated methods Thread.suspend and Thread.resume to be unusable for such purposes: Races between one thread invoking park and another thread trying to unpark it will preserve liveness, due to the permit. Additionally, park will return if the caller's thread was interrupted, and timeout versions are supported. The park method may also return at any other time, for "no reason", so in general must be invoked within a loop that rechecks conditions upon return. In this sense park serves as an optimization of a "busy wait" that does not waste as much time spinning, but must be paired with an unpark to be effective. These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. Sample Usage. Here is a sketch of a First-in-first-out non-reentrant lock class. class FIFOMutex { private AtomicBoolean locked = new AtomicBoolean(false); private Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>(); public void lock() { boolean wasInterrupted = false; Thread current = Thread.currentThread(); waiters.add(current); // Block while not first in queue or cannot acquire lock while (waiters.peek() != current || !locked.compareAndSet(false, true)) { LockSupport.park(); if (Thread.interrupted()) // ignore interrupts while waiting wasInterrupted = true; } waiters.remove(); if (wasInterrupted) // reassert interrupt status on exit current.interrupt(); } public void unlock() { locked.set(false); LockSupport.unpark(waiters.peek()); } }
|
Basic thread blocking primitives for creating locks and other synchronization classes. This class associates with each thread that uses it, a permit
(in the sense of the Methods park and unpark provide efficient means of blocking and unblocking threads that do not encounter the problems that cause the deprecated methods Thread.suspend and Thread.resume to be unusable for such purposes: Races between one thread invoking park and another thread trying to unpark it will preserve liveness, due to the permit. Additionally, park will return if the caller's thread was interrupted, and timeout versions are supported. The park method may also return at any other time, for "no reason", so in general must be invoked within a loop that rechecks conditions upon return. In this sense park serves as an optimization of a "busy wait" that does not waste as much time spinning, but must be paired with an unpark to be effective. The three forms of park each also support a
blocker object parameter. This object is recorded while
the thread is blocked to permit monitoring and diagnostic tools to
identify the reasons that threads are blocked. (Such tools may
access blockers using method These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. Sample Usage. Here is a sketch of a First-in-first-out non-reentrant lock class. class FIFOMutex { private AtomicBoolean locked = new AtomicBoolean(false); private Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>(); public void lock() { boolean wasInterrupted = false; Thread current = Thread.currentThread(); waiters.add(current); // Block while not first in queue or cannot acquire lock while (waiters.peek() != current || !locked.compareAndSet(false, true)) { LockSupport.park(this); if (Thread.interrupted()) // ignore interrupts while waiting wasInterrupted = true; } waiters.remove(); if (wasInterrupted) // reassert interrupt status on exit current.interrupt(); } public void unlock() { locked.set(false); LockSupport.unpark(waiters.peek()); } }
|
getBlockerpublic static Object getBlocker(Thread t)
|
parkpublic static void park(Object blocker)
|
parkNanospublic static void parkNanos(Object blocker, long nanos)
|
parkUntilpublic static void parkUntil(Object blocker, long deadline)
|
unparkpublic static void unpark(Thread thread)
| |
unparkpublic static void unpark(Thread thread)
|
unparkpublic static void unpark(Thread thread)
|
Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects. A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock . The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired. While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order. With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used: Lock l = ...; l.lock(); try { // access the resource protected by this lock } finally { l.unlock(); }When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary. Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock ( tryLock() ), an attempt to acquire the lock that can be interrupted ( lockInterruptibly() , and an attempt to acquire the lock that can timeout ( tryLock(long, TimeUnit) ). A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such specialized semantics then the implementation must document those semantics. Note that Lock instances are just normal objects and can themselves be used as the target in a synchronized statement. Acquiring the monitor lock of a Lock instance has no specified relationship with invoking any of the lock() methods of that instance. It is recommended that to avoid confusion you never use Lock instances in this way, except within their own implementation. Except where noted, passing a null value for any parameter will result in a NullPointerException being thrown. Memory Synchronization
All
Lock
implementations
must
enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in
The Java Language Specification, Third Edition (17.4 Memory Model)
:
Implementation ConsiderationsThe three forms of lock acquisition (interruptible, non-interruptible, and timed) may differ in their performance characteristics, ordering guarantees, or other implementation qualities. Further, the ability to interrupt the ongoing acquisition of a lock may not be available in a given Lock class. Consequently, an implementation is not required to define exactly the same guarantees or semantics for all three forms of lock acquisition, nor is it required to support interruption of an ongoing lock acquisition. An implementation is required to clearly document the semantics and guarantees provided by each of the locking methods. It must also obey the interruption semantics as defined in this interface, to the extent that interruption of lock acquisition is supported: which is either totally, or only on method entry. 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.
| |
Lock implementations provide more extensive locking
operations than can be obtained using synchronized methods
and statements. They allow more flexible structuring, may have
quite different properties, and may support multiple associated
A lock is a tool for controlling access to a shared resource by
multiple threads. Commonly, a lock provides exclusive access to a
shared resource: only one thread at a time can acquire the lock and
all access to the shared resource requires that the lock be
acquired first. However, some locks may allow concurrent access to
a shared resource, such as the read lock of a The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired. While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order. With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used: Lock l = ...; l.lock(); try { // access the resource protected by this lock } finally { l.unlock(); }When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary. Lock implementations provide additional functionality
over the use of synchronized methods and statements by
providing a non-blocking attempt to acquire a lock ( A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such specialized semantics then the implementation must document those semantics. Note that Lock instances are just normal objects and can
themselves be used as the target in a synchronized statement.
Acquiring the
monitor lock of a Lock instance has no specified relationship
with invoking any of the Except where noted, passing a null value for any
parameter will result in a Memory SynchronizationAll Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock:
Implementation ConsiderationsThe three forms of lock acquisition (interruptible, non-interruptible, and timed) may differ in their performance characteristics, ordering guarantees, or other implementation qualities. Further, the ability to interrupt the ongoing acquisition of a lock may not be available in a given Lock class. Consequently, an implementation is not required to define exactly the same guarantees or semantics for all three forms of lock acquisition, nor is it required to support interruption of an ongoing lock acquisition. An implementation is required to clearly document the semantics and guarantees provided by each of the locking methods. It must also obey the interruption semantics as defined in this interface, to the extent that interruption of lock acquisition is supported: which is either totally, or only on method entry. 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.
|
Lock implementations provide more extensive locking
operations than can be obtained using synchronized methods
and statements. They allow more flexible structuring, may have
quite different properties, and may support multiple associated
A lock is a tool for controlling access to a shared resource by
multiple threads. Commonly, a lock provides exclusive access to a
shared resource: only one thread at a time can acquire the lock and
all access to the shared resource requires that the lock be
acquired first. However, some locks may allow concurrent access to
a shared resource, such as the read lock of a The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired. While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order. With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used: Lock l = ...; l.lock(); try { // access the resource protected by this lock } finally { l.unlock(); }When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary. Lock implementations provide additional functionality
over the use of synchronized methods and statements by
providing a non-blocking attempt to acquire a lock ( A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such specialized semantics then the implementation must document those semantics. Note that Lock instances are just normal objects and can
themselves be used as the target in a synchronized statement.
Acquiring the
monitor lock of a Lock instance has no specified relationship
with invoking any of the Except where noted, passing a null value for any
parameter will result in a Memory SynchronizationAll Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in The Java Language Specification, Third Edition (17.4 Memory Model):
Implementation ConsiderationsThe three forms of lock acquisition (interruptible, non-interruptible, and timed) may differ in their performance characteristics, ordering guarantees, or other implementation qualities. Further, the ability to interrupt the ongoing acquisition of a lock may not be available in a given Lock class. Consequently, an implementation is not required to define exactly the same guarantees or semantics for all three forms of lock acquisition, nor is it required to support interruption of an ongoing lock acquisition. An implementation is required to clearly document the semantics and guarantees provided by each of the locking methods. It must also obey the interruption semantics as defined in this interface, to the extent that interruption of lock acquisition is supported: which is either totally, or only on method entry. 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.
|
Condition implementation for a Method documentation for this class describes mechanics, not behavioral specifications from the point of view of Lock and Condition users. Exported versions of this class will in general need to be accompanied by documentation describing condition semantics that rely on those of the associated AbstractQueuedLongSynchronizer. This class is Serializable, but all fields are transient, so deserialized conditions have no waiters.
|
AbstractQueuedLongSynchronizer.ConditionObjectpublic AbstractQueuedLongSynchronizer.ConditionObject()
|
awaitpublic final void await() throws InterruptedException
|
awaitpublic final boolean await(long time, TimeUnit unit) throws InterruptedException
|
awaitNanospublic final long awaitNanos(long nanosTimeout) throws InterruptedException
|
awaitUninterruptiblypublic final void awaitUninterruptibly()
|
awaitUntilpublic final boolean awaitUntil(Date deadline) throws InterruptedException
|
getWaitQueueLengthprotected final int getWaitQueueLength()
|
getWaitingThreadsprotected final Collection<Thread> getWaitingThreads()
|
hasWaitersprotected final boolean hasWaiters()
|
signalpublic final void signal()
|
signalAllpublic final void signalAll()
|
Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues. This class is designed to be a useful basis for most kinds of synchronizers that rely on a single atomic int value to represent state. Subclasses must define the protected methods that change this state, and which define what that state means in terms of this object being acquired or released. Given these, the other methods in this class carry out all queuing and blocking mechanics. Subclasses can maintain other state fields, but only the atomically updated int value manipulated using methods getState() , setState(int) and compareAndSetState(int, int) is tracked with respect to synchronization. Subclasses should be defined as non-public internal helper classes that are used to implement the synchronization properties of their enclosing class. Class AbstractQueuedSynchronizer does not implement any synchronization interface. Instead it defines methods such as acquireInterruptibly(int) that can be invoked as appropriate by concrete locks and related synchronizers to implement their public methods. This class supports either or both a default exclusive mode and a shared mode. When acquired in exclusive mode, attempted acquires by other threads cannot succeed. Shared mode acquires by multiple threads may (but need not) succeed. This class does not "understand" these differences except in the mechanical sense that when a shared mode acquire succeeds, the next waiting thread (if one exists) must also determine whether it can acquire as well. Threads waiting in the different modes share the same FIFO queue. Usually, implementation subclasses support only one of these modes, but both can come into play for example in a ReadWriteLock . Subclasses that support only exclusive or only shared modes need not define the methods supporting the unused mode. This class defines a nested AbstractQueuedSynchronizer.ConditionObject class that can be used as a Condition implementation by subclasses supporting exclusive mode for which method isHeldExclusively() reports whether synchronization is exclusively held with respect to the current thread, method release(int) invoked with the current getState() value fully releases this object, and acquire(int) , given this saved state value, eventually restores this object to its previous acquired state. No AbstractQueuedSynchronizer method otherwise creates such a condition, so if this constraint cannot be met, do not use it. The behavior of AbstractQueuedSynchronizer.ConditionObject depends of course on the semantics of its synchronizer implementation. This class provides inspection, instrumentation, and monitoring methods for the internal queue, as well as similar methods for condition objects. These can be exported as desired into classes using an AbstractQueuedSynchronizer for their synchronization mechanics. Serialization of this class stores only the underlying atomic integer maintaining state, so deserialized objects have empty thread queues. Typical subclasses requiring serializability will define a readObject method that restores this to a known initial state upon deserialization. UsageTo use this class as the basis of a synchronizer, redefine the following methods, as applicable, by inspecting and/or modifying the synchronization state using getState() , setState(int) and/or compareAndSetState(int, int) : Each of these methods by default throws UnsupportedOperationException . Implementations of these methods must be internally thread-safe, and should in general be short and not block. Defining these methods is the only supported means of using this class. All other methods are declared final because they cannot be independently varied.You may also find the inherited methods from AbstractOwnableSynchronizer useful to keep track of the thread owning an exclusive synchronizer. You are encouraged to use them -- this enables monitoring and diagnostic tools to assist users in determining which threads hold locks. Even though this class is based on an internal FIFO queue, it does not automatically enforce FIFO acquisition policies. The core of exclusive synchronization takes the form: Acquire: while (!tryAcquire(arg)) { enqueue thread if it is not already queued; possibly block current thread; } Release: if (tryRelease(arg)) unblock the first queued thread;(Shared mode is similar but may involve cascading signals.) Because checks in acquire are invoked before enqueuing, a newly acquiring thread may barge ahead of others that are blocked and queued. However, you can, if desired, define tryAcquire and/or tryAcquireShared to disable barging by internally invoking one or more of the inspection methods. In particular, a strict FIFO lock can define tryAcquire to immediately return false if getFirstQueuedThread() does not return the current thread. A normally preferable non-strict fair version can immediately return false only if hasQueuedThreads() returns true and getFirstQueuedThread is not the current thread; or equivalently, that getFirstQueuedThread is both non-null and not the current thread. Further variations are possible. Throughput and scalability are generally highest for the default barging (also known as greedy , renouncement , and convoy-avoidance ) strategy. While this is not guaranteed to be fair or starvation-free, earlier queued threads are allowed to recontend before later queued threads, and each recontention has an unbiased chance to succeed against incoming threads. Also, while acquires do not "spin" in the usual sense, they may perform multiple invocations of tryAcquire interspersed with other computations before blocking. This gives most of the benefits of spins when exclusive synchronization is only briefly held, without most of the liabilities when it isn't. If so desired, you can augment this by preceding calls to acquire methods with "fast-path" checks, possibly prechecking hasContended() and/or hasQueuedThreads() to only do so if the synchronizer is likely not to be contended. This class provides an efficient and scalable basis for synchronization in part by specializing its range of use to synchronizers that can rely on int state, acquire, and release parameters, and an internal FIFO wait queue. When this does not suffice, you can build synchronizers from a lower level using atomic classes, your own custom Queue classes, and LockSupport blocking support. Usage ExamplesHere is a non-reentrant mutual exclusion lock class that uses the value zero to represent the unlocked state, and one to represent the locked state. While a non-reentrant lock does not strictly require recording of the current owner thread, this class does so anyway to make usage easier to monitor. It also supports conditions and exposes one of the instrumentation methods: class Mutex implements Lock, java.io.Serializable { // Our internal helper class private static class Sync extends AbstractQueuedSynchronizer { // Report whether in locked state protected boolean isHeldExclusively() { return getState() == 1; } // Acquire the lock if state is zero public boolean tryAcquire(int acquires) { assert acquires == 1; // Otherwise unused if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; Here is a latch class that is like a CountDownLatch except that it only requires a single signal to fire. Because a latch is non-exclusive, it uses the shared acquire and release methods. class BooleanLatch { private static class Sync extends AbstractQueuedSynchronizer { boolean isSignalled() { return getState() != 0; } protected int tryAcquireShared(int ignore) { return isSignalled()? 1 : -1; } protected boolean tryReleaseShared(int ignore) { setState(1); return true; } } private final Sync sync = new Sync(); public boolean isSignalled() { return sync.isSignalled(); } public void signal() { sync.releaseShared(1); } public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } }
| |
Provides a framework for implementing blocking locks and related
synchronizers (semaphores, events, etc) that rely on
first-in-first-out (FIFO) wait queues. This class is designed to
be a useful basis for most kinds of synchronizers that rely on a
single atomic int value to represent state. Subclasses
must define the protected methods that change this state, and which
define what that state means in terms of this object being acquired
or released. Given these, the other methods in this class carry
out all queuing and blocking mechanics. Subclasses can maintain
other state fields, but only the atomically updated int
value manipulated using methods Subclasses should be defined as non-public internal helper
classes that are used to implement the synchronization properties
of their enclosing class. Class
AbstractQueuedSynchronizer does not implement any
synchronization interface. Instead it defines methods such as
This class supports either or both a default exclusive
mode and a shared mode. When acquired in exclusive mode,
attempted acquires by other threads cannot succeed. Shared mode
acquires by multiple threads may (but need not) succeed. This class
does not "understand" these differences except in the
mechanical sense that when a shared mode acquire succeeds, the next
waiting thread (if one exists) must also determine whether it can
acquire as well. Threads waiting in the different modes share the
same FIFO queue. Usually, implementation subclasses support only
one of these modes, but both can come into play for example in a
This class defines a nested This class provides inspection, instrumentation, and monitoring methods for the internal queue, as well as similar methods for condition objects. These can be exported as desired into classes using an AbstractQueuedSynchronizer for their synchronization mechanics. Serialization of this class stores only the underlying atomic integer maintaining state, so deserialized objects have empty thread queues. Typical subclasses requiring serializability will define a readObject method that restores this to a known initial state upon deserialization. Usage To use this class as the basis of a synchronizer, redefine the
following methods, as applicable, by inspecting and/or modifying
the synchronization state using UnsupportedOperationException . Implementations of these methods
must be internally thread-safe, and should in general be short and
not block. Defining these methods is the only supported
means of using this class. All other methods are declared
final because they cannot be independently varied.
Even though this class is based on an internal FIFO queue, it does not automatically enforce FIFO acquisition policies. The core of exclusive synchronization takes the form: Acquire: while (!tryAcquire(arg)) { enqueue thread if it is not already queued; possibly block current thread; } Release: if (tryRelease(arg)) unblock the first queued thread;(Shared mode is similar but may involve cascading signals.) Because checks in acquire are invoked before enqueuing, a newly
acquiring thread may barge ahead of others that are
blocked and queued. However, you can, if desired, define
tryAcquire and/or tryAcquireShared to disable
barging by internally invoking one or more of the inspection
methods. In particular, a strict FIFO lock can define
tryAcquire to immediately return false if Throughput and scalability are generally highest for the
default barging (also known as greedy,
renouncement, and convoy-avoidance) strategy.
While this is not guaranteed to be fair or starvation-free, earlier
queued threads are allowed to recontend before later queued
threads, and each recontention has an unbiased chance to succeed
against incoming threads. Also, while acquires do not
"spin" in the usual sense, they may perform multiple
invocations of tryAcquire interspersed with other
computations before blocking. This gives most of the benefits of
spins when exclusive synchronization is only briefly held, without
most of the liabilities when it isn't. If so desired, you can
augment this by preceding calls to acquire methods with
"fast-path" checks, possibly prechecking This class provides an efficient and scalable basis for
synchronization in part by specializing its range of use to
synchronizers that can rely on int state, acquire, and
release parameters, and an internal FIFO wait queue. When this does
not suffice, you can build synchronizers from a lower level using
Usage ExamplesHere is a non-reentrant mutual exclusion lock class that uses the value zero to represent the unlocked state, and one to represent the locked state. It also supports conditions and exposes one of the instrumentation methods: class Mutex implements Lock, java.io.Serializable { // Our internal helper class private static class Sync extends AbstractQueuedSynchronizer { // Report whether in locked state protected boolean isHeldExclusively() { return getState() == 1; } // Acquire the lock if state is zero public boolean tryAcquire(int acquires) { assert acquires == 1; // Otherwise unused return compareAndSetState(0, 1); } // Release the lock by setting state to zero protected boolean tryRelease(int releases) { assert releases == 1; // Otherwise unused if (getState() == 0) throw new IllegalMonitorStateException(); setState(0); return true; } // Provide a Condition Condition newCondition() { return new ConditionObject(); } // Deserialize properly private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } } // The sync object does all the hard work. We just forward to it. private final Sync sync = new Sync(); public void lock() { sync.acquire(1); } public boolean tryLock() { return sync.tryAcquire(1); } public void unlock() { sync.release(1); } public Condition newCondition() { return sync.newCondition(); } public boolean isLocked() { return sync.isHeldExclusively(); } public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } } Here is a latch class that is like a class BooleanLatch { private static class Sync extends AbstractQueuedSynchronizer { boolean isSignalled() { return getState() != 0; } protected int tryAcquireShared(int ignore) { return isSignalled()? 1 : -1; } protected boolean tryReleaseShared(int ignore) { setState(1); return true; } } private final Sync sync = new Sync(); public boolean isSignalled() { return sync.isSignalled(); } public void signal() { sync.releaseShared(1); } public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } }
|
Provides a framework for implementing blocking locks and related
synchronizers (semaphores, events, etc) that rely on
first-in-first-out (FIFO) wait queues. This class is designed to
be a useful basis for most kinds of synchronizers that rely on a
single atomic int value to represent state. Subclasses
must define the protected methods that change this state, and which
define what that state means in terms of this object being acquired
or released. Given these, the other methods in this class carry
out all queuing and blocking mechanics. Subclasses can maintain
other state fields, but only the atomically updated int
value manipulated using methods Subclasses should be defined as non-public internal helper
classes that are used to implement the synchronization properties
of their enclosing class. Class
AbstractQueuedSynchronizer does not implement any
synchronization interface. Instead it defines methods such as
This class supports either or both a default exclusive
mode and a shared mode. When acquired in exclusive mode,
attempted acquires by other threads cannot succeed. Shared mode
acquires by multiple threads may (but need not) succeed. This class
does not "understand" these differences except in the
mechanical sense that when a shared mode acquire succeeds, the next
waiting thread (if one exists) must also determine whether it can
acquire as well. Threads waiting in the different modes share the
same FIFO queue. Usually, implementation subclasses support only
one of these modes, but both can come into play for example in a
This class defines a nested This class provides inspection, instrumentation, and monitoring methods for the internal queue, as well as similar methods for condition objects. These can be exported as desired into classes using an AbstractQueuedSynchronizer for their synchronization mechanics. Serialization of this class stores only the underlying atomic integer maintaining state, so deserialized objects have empty thread queues. Typical subclasses requiring serializability will define a readObject method that restores this to a known initial state upon deserialization. Usage To use this class as the basis of a synchronizer, redefine the
following methods, as applicable, by inspecting and/or modifying
the synchronization state using UnsupportedOperationException . Implementations of these methods
must be internally thread-safe, and should in general be short and
not block. Defining these methods is the only supported
means of using this class. All other methods are declared
final because they cannot be independently varied.
You may also find the inherited methods from Even though this class is based on an internal FIFO queue, it does not automatically enforce FIFO acquisition policies. The core of exclusive synchronization takes the form: Acquire: while (!tryAcquire(arg)) { enqueue thread if it is not already queued; possibly block current thread; } Release: if (tryRelease(arg)) unblock the first queued thread;(Shared mode is similar but may involve cascading signals.) Because checks in acquire are invoked before enqueuing, a newly
acquiring thread may barge ahead of others that are
blocked and queued. However, you can, if desired, define
tryAcquire and/or tryAcquireShared to disable
barging by internally invoking one or more of the inspection
methods. In particular, a strict FIFO lock can define
tryAcquire to immediately return false if Throughput and scalability are generally highest for the
default barging (also known as greedy,
renouncement, and convoy-avoidance) strategy.
While this is not guaranteed to be fair or starvation-free, earlier
queued threads are allowed to recontend before later queued
threads, and each recontention has an unbiased chance to succeed
against incoming threads. Also, while acquires do not
"spin" in the usual sense, they may perform multiple
invocations of tryAcquire interspersed with other
computations before blocking. This gives most of the benefits of
spins when exclusive synchronization is only briefly held, without
most of the liabilities when it isn't. If so desired, you can
augment this by preceding calls to acquire methods with
"fast-path" checks, possibly prechecking This class provides an efficient and scalable basis for
synchronization in part by specializing its range of use to
synchronizers that can rely on int state, acquire, and
release parameters, and an internal FIFO wait queue. When this does
not suffice, you can build synchronizers from a lower level using
Usage ExamplesHere is a non-reentrant mutual exclusion lock class that uses the value zero to represent the unlocked state, and one to represent the locked state. While a non-reentrant lock does not strictly require recording of the current owner thread, this class does so anyway to make usage easier to monitor. It also supports conditions and exposes one of the instrumentation methods: class Mutex implements Lock, java.io.Serializable { // Our internal helper class private static class Sync extends AbstractQueuedSynchronizer { // Report whether in locked state protected boolean isHeldExclusively() { return getState() == 1; } // Acquire the lock if state is zero public boolean tryAcquire(int acquires) { assert acquires == 1; // Otherwise unused if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } // Release the lock by setting state to zero protected boolean tryRelease(int releases) { assert releases == 1; // Otherwise unused if (getState() == 0) throw new IllegalMonitorStateException(); setExclusiveOwnerThread(null); setState(0); return true; } // Provide a Condition Condition newCondition() { return new ConditionObject(); } // Deserialize properly private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } } // The sync object does all the hard work. We just forward to it. private final Sync sync = new Sync(); public void lock() { sync.acquire(1); } public boolean tryLock() { return sync.tryAcquire(1); } public void unlock() { sync.release(1); } public Condition newCondition() { return sync.newCondition(); } public boolean isLocked() { return sync.isHeldExclusively(); } public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } } Here is a latch class that is like a class BooleanLatch { private static class Sync extends AbstractQueuedSynchronizer { boolean isSignalled() { return getState() != 0; } protected int tryAcquireShared(int ignore) { return isSignalled()? 1 : -1; } protected boolean tryReleaseShared(int ignore) { setState(1); return true; } } private final Sync sync = new Sync(); public boolean isSignalled() { return sync.isSignalled(); } public void signal() { sync.releaseShared(1); } public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } }
|
tryAcquireSharedprotected int tryAcquireShared(int arg)
| |
tryAcquireSharedprotected int tryAcquireShared(int arg)
|
tryAcquireSharedprotected int tryAcquireShared(int arg)
|
tryReleaseSharedprotected boolean tryReleaseShared(int arg)
| |
tryReleaseSharedprotected boolean tryReleaseShared(int arg)
|
tryReleaseSharedprotected boolean tryReleaseShared(int arg)
|
An implementation of ReadWriteLock supporting similar semantics to ReentrantLock . This class has the following properties:
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. Sample usages . Here is a code sketch showing how to exploit reentrancy to perform lock downgrading after updating a cache (exception handling is elided for simplicity): class CachedData { Object data; volatile boolean cacheValid; ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); void processCachedData() { rwl.readLock().lock(); if (!cacheValid) { // Must release readReentrantReadWriteLocks can be used to improve concurrency in some uses of some kinds of Collections. This is typically worthwhile only when the collections are expected to be large, accessed by more reader threads than writer threads, and entail operations with overhead that outweighs synchronization overhead. For example, here is a class using a TreeMap that is expected to be large and concurrently accessed. class RWDictionary { private final Map<String, Data> m = new TreeMap<String, Data>(); private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); public Data get(String key) { r.lock(); try { return m.get(key); } finally { r.unlock(); } } public String[] allKeys() { r.lock(); try { return m.keySet().toArray(); } finally { r.unlock(); } } public Data put(String key, Data value) { w.lock(); try { return m.put(key, value); } finally { w.unlock(); } } public void clear() { w.lock(); try { m.clear(); } finally { w.unlock(); } } } Implementation Notes
This lock supports a maximum of 65535 recursive write locks and 65535 read locks. Attempts to exceed these limits result in
Error
throws from locking methods.
| |
An implementation of This class has the following properties:
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. Sample usages. Here is a code sketch showing how to exploit reentrancy to perform lock downgrading after updating a cache (exception handling is elided for simplicity): class CachedData { Object data; volatile boolean cacheValid; ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); void processCachedData() { rwl.readLock().lock(); if (!cacheValid) { // upgrade lock manually rwl.readLock().unlock(); // must unlock first to obtain writelock rwl.writeLock().lock(); if (!cacheValid) { // recheck data = ... cacheValid = true; } // downgrade lock rwl.readLock().lock(); // reacquire read without giving up write lock rwl.writeLock().unlock(); // unlock write, still hold read } use(data); rwl.readLock().unlock(); } }ReentrantReadWriteLocks can be used to improve concurrency in some uses of some kinds of Collections. This is typically worthwhile only when the collections are expected to be large, accessed by more reader threads than writer threads, and entail operations with overhead that outweighs synchronization overhead. For example, here is a class using a TreeMap that is expected to be large and concurrently accessed. class RWDictionary { private final Map<String, Data> m = new TreeMap<String, Data>(); private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); public Data get(String key) { r.lock(); try { return m.get(key); } finally { r.unlock(); } } public String[] allKeys() { r.lock(); try { return m.keySet().toArray(); } finally { r.unlock(); } } public Data put(String key, Data value) { w.lock(); try { return m.put(key, value); } finally { w.unlock(); } } public void clear() { w.lock(); try { m.clear(); } finally { w.unlock(); } } } Implementation NotesA reentrant write lock intrinsically defines an owner and can only be released by the thread that acquired it. In contrast, in this implementation, the read lock has no concept of ownership, and there is no requirement that the thread releasing a read lock is the same as the one that acquired it. However, this property is not guaranteed to hold in future implementations of this class. This lock supports a maximum of 65536 recursive write locks
and 65536 read locks. Attempts to exceed these limits result in
|
An implementation of This class has the following properties:
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. Sample usages. Here is a code sketch showing how to exploit reentrancy to perform lock downgrading after updating a cache (exception handling is elided for simplicity): class CachedData { Object data; volatile boolean cacheValid; ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); void processCachedData() { rwl.readLock().lock(); if (!cacheValid) { // Must release read lock before acquiring write lock rwl.readLock().unlock(); rwl.writeLock().lock(); // Recheck state because another thread might have acquired // write lock and changed state before we did. if (!cacheValid) { data = ... cacheValid = true; } // Downgrade by acquiring read lock before releasing write lock rwl.readLock().lock(); rwl.writeLock().unlock(); // Unlock write, still hold read } use(data); rwl.readLock().unlock(); } }ReentrantReadWriteLocks can be used to improve concurrency in some uses of some kinds of Collections. This is typically worthwhile only when the collections are expected to be large, accessed by more reader threads than writer threads, and entail operations with overhead that outweighs synchronization overhead. For example, here is a class using a TreeMap that is expected to be large and concurrently accessed. class RWDictionary { private final Map<String, Data> m = new TreeMap<String, Data>(); private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); public Data get(String key) { r.lock(); try { return m.get(key); } finally { r.unlock(); } } public String[] allKeys() { r.lock(); try { return m.keySet().toArray(); } finally { r.unlock(); } } public Data put(String key, Data value) { w.lock(); try { return m.put(key, value); } finally { w.unlock(); } } public void clear() { w.lock(); try { m.clear(); } finally { w.unlock(); } } } Implementation Notes This lock supports a maximum of 65535 recursive write locks
and 65535 read locks. Attempts to exceed these limits result in
|
getOwnerprotected Thread getOwner()
| |
getOwnerprotected Thread getOwner()
|
getOwnerprotected Thread getOwner()
|
A ReadWriteLock maintains a pair of associated locks , one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive. All ReadWriteLock implementations must guarantee that the memory synchronization effects of writeLock operations (as specified in the Lock interface) also hold with respect to the associated readLock. That is, a thread successfully acquiring the read lock will see all updates made upon previous release of the write lock. A read-write lock allows for a greater level of concurrency in accessing shared data than that permitted by a mutual exclusion lock. It exploits the fact that while only a single thread at a time (a writer thread) can modify the shared data, in many cases any number of threads can concurrently read the data (hence reader threads). In theory, the increase in concurrency permitted by the use of a read-write lock will lead to performance improvements over the use of a mutual exclusion lock. In practice this increase in concurrency will only be fully realized on a multi-processor, and then only if the access patterns for the shared data are suitable. Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is read compared to being modified, the duration of the read and write operations, and the contention for the data - that is, the number of threads that will try to read or write the data at the same time. For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched (such as a directory of some kind) is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Further, if the read operations are too short the overhead of the read-write lock implementation (which is inherently more complex than a mutual exclusion lock) can dominate the execution cost, particularly as many read-write lock implementations still serialize all threads through a small section of code. Ultimately, only profiling and measurement will establish whether the use of a read-write lock is suitable for your application. Although the basic operation of a read-write lock is straight-forward, there are many policy decisions that an implementation must make, which may affect the effectiveness of the read-write lock in a given application. Examples of these policies include:
| |
A ReadWriteLock maintains a pair of associated A read-write lock allows for a greater level of concurrency in accessing shared data than that permitted by a mutual exclusion lock. It exploits the fact that while only a single thread at a time (a writer thread) can modify the shared data, in many cases any number of threads can concurrently read the data (hence reader threads). In theory, the increase in concurrency permitted by the use of a read-write lock will lead to performance improvements over the use of a mutual exclusion lock. In practice this increase in concurrency will only be fully realized on a multi-processor, and then only if the access patterns for the shared data are suitable. Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is read compared to being modified, the duration of the read and write operations, and the contention for the data - that is, the number of threads that will try to read or write the data at the same time. For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched (such as a directory of some kind) is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Further, if the read operations are too short the overhead of the read-write lock implementation (which is inherently more complex than a mutual exclusion lock) can dominate the execution cost, particularly as many read-write lock implementations still serialize all threads through a small section of code. Ultimately, only profiling and measurement will establish whether the use of a read-write lock is suitable for your application. Although the basic operation of a read-write lock is straight-forward, there are many policy decisions that an implementation must make, which may affect the effectiveness of the read-write lock in a given application. Examples of these policies include:
|
A ReadWriteLock maintains a pair of associated All ReadWriteLock implementations must guarantee that
the memory synchronization effects of writeLock operations
(as specified in the A read-write lock allows for a greater level of concurrency in accessing shared data than that permitted by a mutual exclusion lock. It exploits the fact that while only a single thread at a time (a writer thread) can modify the shared data, in many cases any number of threads can concurrently read the data (hence reader threads). In theory, the increase in concurrency permitted by the use of a read-write lock will lead to performance improvements over the use of a mutual exclusion lock. In practice this increase in concurrency will only be fully realized on a multi-processor, and then only if the access patterns for the shared data are suitable. Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is read compared to being modified, the duration of the read and write operations, and the contention for the data - that is, the number of threads that will try to read or write the data at the same time. For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched (such as a directory of some kind) is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Further, if the read operations are too short the overhead of the read-write lock implementation (which is inherently more complex than a mutual exclusion lock) can dominate the execution cost, particularly as many read-write lock implementations still serialize all threads through a small section of code. Ultimately, only profiling and measurement will establish whether the use of a read-write lock is suitable for your application. Although the basic operation of a read-write lock is straight-forward, there are many policy decisions that an implementation must make, which may affect the effectiveness of the read-write lock in a given application. Examples of these policies include:
|
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking 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 isHeldByCurrentThread() , and getHoldCount() . The constructor for this class accepts an optional fairness parameter. When set 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 tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting. It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as: class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body } finally { lock.unlock() } } } In addition to implementing the Lock interface, this class defines methods isLocked and getLockQueueLength , as well as some associated protected access methods that may be useful for instrumentation and monitoring. 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.
This lock supports a maximum of 2147483647
| |
A reentrant mutual exclusion A ReentrantLock is owned by the thread last
successfully locking, but not yet unlocking it. A thread invoking
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 The constructor for this class accepts an optional
fairness parameter. When set 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 It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as: class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body } finally { lock.unlock() } } } In addition to implementing the 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. This lock supports a maximum of 2147483648 recursive locks by the same thread.
|
A reentrant mutual exclusion A ReentrantLock is owned by the thread last
successfully locking, but not yet unlocking it. A thread invoking
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 The constructor for this class accepts an optional
fairness parameter. When set 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 It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as: class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body } finally { lock.unlock() } } } In addition to implementing the 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. This lock supports a maximum of 2147483647 recursive locks by
the same thread. Attempts to exceed this limit result in
|
getOwnerprotected Thread getOwner()
| |
getOwnerprotected Thread getOwner()
|
getOwnerprotected Thread getOwner()
|
cancelboolean cancel(boolean mayInterruptIfRunning)
| |
cancelboolean cancel(boolean mayInterruptIfRunning)
|
cancelboolean cancel(boolean mayInterruptIfRunning)
|
Provides default implementations Extension example . Here is a sketch of a class that customizes ThreadPoolExecutor to use a CustomTask class instead of the default FutureTask : public class CustomThreadPoolExecutor extends ThreadPoolExecutor { static class CustomTask<V> implements RunnableFuture<V> {...} protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) { return new CustomTask<V>(c); } protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) { return new CustomTask<V>(r, v); } // ... add constructors, etc. }
| |
Provides default implementation of
|
Provides default implementations of Extension example. Here is a sketch of a class
that customizes public class CustomThreadPoolExecutor extends ThreadPoolExecutor { static class CustomTask<V> implements RunnableFuture<V> {...} protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) { return new CustomTask<V>(c); } protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) { return new CustomTask<V>(r, v); } // ... add constructors, etc. }
|
invokeAllpublic <T> List<Future<T>> invokeAll(Collection<? extends Callable
| |
invokeAllpublic <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks) throws InterruptedException
|
invokeAllpublic <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException
|
invokeAllpublic <T> List<Future<T>> invokeAll(Collection<? extends Callable
| |
invokeAllpublic <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException
|
invokeAllpublic <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException
|
invokeAnypublic <T> T invokeAny(Collection<? extends Callable
| |
invokeAnypublic <T> T invokeAny(Collection<Callable<T>> tasks) throws InterruptedException, ExecutionException
|
invokeAnypublic <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException
|
invokeAnypublic <T> T invokeAny(Collection<? extends Callable
| |
invokeAnypublic <T> T invokeAny(Collection<Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
|
invokeAnypublic <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
|
newTaskForprotected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value)
|
newTaskForprotected <T> RunnableFuture<T> newTaskFor(Callable<T> callable)
|
submitpublic Future<?> submit(Runnable task)
| |
submitpublic Future<?> submit(Runnable task)
|
submitpublic Future<?> submit(Runnable task)
|
submitpublic <T> Future<T> submit(Runnable task, T result)
| |
submitpublic <T> Future<T> submit(Runnable task, T result)
|
submitpublic <T> Future<T> submit(Runnable task, T result)
|
submitpublic <T> Future<T> submit(Callable<T> task)
| |
submitpublic <T> Future<T> submit(Callable<T> task)
|
submitpublic <T> Future<T> submit(Callable<T> task)
|
A bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.
This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be increased. Attempts to put
an element into a full queue will result in the This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. This class is a member of the Java Collections Framework.
| |
A bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be increased. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will similarly block. This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation. This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
A bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be increased. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block. This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation. This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
ArrayBlockingQueuepublic ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)
| |
ArrayBlockingQueuepublic ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)
|
ArrayBlockingQueuepublic ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)
|
addpublic boolean add(E e)
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
drainTopublic int drainTo(Collection<? super E> c)
| |
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
| |
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
offerpublic boolean offer(E e)
| |
offerpublic boolean offer(E o)
|
offerpublic boolean offer(E e)
|
offerpublic boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
| |
offerpublic boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException
|
offerpublic boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
|
peekpublic E peek() | |
peekpublic E peek() |
peekpublic E peek() |
pollpublic E poll() | |
pollpublic E poll() |
pollpublic E poll() |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
| |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
putpublic void put(E e) throws InterruptedException
| |
putpublic void put(E o) throws InterruptedException
|
putpublic void put(E e) throws InterruptedException
|
remainingCapacitypublic int remainingCapacity()
| |
remainingCapacitypublic int remainingCapacity()
|
remainingCapacitypublic int remainingCapacity()
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
takepublic E take() throws InterruptedException
| |
takepublic E take() throws InterruptedException
|
takepublic E take() throws InterruptedException
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
A BlockingDeque methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. These methods are summarized in the following table:
Like any A BlockingDeque implementation may be used directly as a FIFO BlockingQueue. The methods inherited from the BlockingQueue interface are precisely equivalent to BlockingDeque methods as indicated in the following table:
This interface is a member of the Java Collections Framework.
|
addboolean add(E e)
|
addFirstvoid addFirst(E e)
|
addLastvoid addLast(E e)
|
containsboolean contains(Object o)
|
elementE element()
|
iteratorIterator<E> iterator()
|
offerboolean offer(E e)
|
offerboolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
|
offerFirstboolean offerFirst(E e)
|
offerFirstboolean offerFirst(E e, long timeout, TimeUnit unit) throws InterruptedException
|
offerLastboolean offerLast(E e)
|
offerLastboolean offerLast(E e, long timeout, TimeUnit unit) throws InterruptedException
|
peekE peek()
|
pollE poll()
|
pollE poll(long timeout, TimeUnit unit) throws InterruptedException
|
pollFirstE pollFirst(long timeout, TimeUnit unit) throws InterruptedException
|
pollLastE pollLast(long timeout, TimeUnit unit) throws InterruptedException
|
pushvoid push(E e)
|
putvoid put(E e) throws InterruptedException
|
putFirstvoid putFirst(E e) throws InterruptedException
|
putLastvoid putLast(E e) throws InterruptedException
|
removeE remove()
|
removeboolean remove(Object o)
|
removeFirstOccurrenceboolean removeFirstOccurrence(Object o)
|
removeLastOccurrenceboolean removeLastOccurrence(Object o)
|
sizeint size() |
takeE take() throws InterruptedException
|
takeFirstE takeFirst() throws InterruptedException
|
takeLastE takeLast() throws InterruptedException
|
A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false , depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. These methods are summarized in the following table:
A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add , put or offer a null . A null is used as a sentinel value to indicate failure of poll operations. A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE . BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the Collection interface. So, for example, it is possible to remove an arbitrary element from a queue using remove(x) . However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled. BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll , containsAll , retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c . A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers. Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { queue.put(produce()); } } catch (InterruptedException ex) { ... handle ...} } Object produce() { ... } } class Consumer implements Runnable { private final BlockingQueue queue; Consumer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { consume(queue.take()); } } catch (InterruptedException ex) { ... handle ...} } void consume(Object x) { ... } } class Setup { void main() { BlockingQueue q = new SomeQueueImplementation(); Producer p = new Producer(q); Consumer c1 = new Consumer(q); Consumer c2 = new Consumer(q); new Thread(p).start(); new Thread(c1).start(); new Thread(c2).start(); } } This interface is a member of the Java Collections Framework.
| |||||||||||||||||||||
A A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations. A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE. BlockingQueue implementations are designed to be used
primarily for producer-consumer queues, but additionally support
the BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c. A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers. Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while(true) { queue.put(produce()); } } catch (InterruptedException ex) { ... handle ...} } Object produce() { ... } } class Consumer implements Runnable { private final BlockingQueue queue; Consumer(BlockingQueue q) { queue = q; } public void run() { try { while(true) { consume(queue.take()); } } catch (InterruptedException ex) { ... handle ...} } void consume(Object x) { ... } } class Setup { void main() { BlockingQueue q = new SomeQueueImplementation(); Producer p = new Producer(q); Consumer c1 = new Consumer(q); Consumer c2 = new Consumer(q); new Thread(p).start(); new Thread(c1).start(); new Thread(c2).start(); } } This interface is a member of the Java Collections Framework.
|
A BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. These methods are summarized in the following table:
A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations. A BlockingQueue may be capacity bounded. At any given time it may have a remainingCapacity beyond which no additional elements can be put without blocking. A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of Integer.MAX_VALUE. BlockingQueue implementations are designed to be used
primarily for producer-consumer queues, but additionally support
the BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c. A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers. Usage example, based on a typical producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { queue.put(produce()); } } catch (InterruptedException ex) { ... handle ...} } Object produce() { ... } } class Consumer implements Runnable { private final BlockingQueue queue; Consumer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { consume(queue.take()); } } catch (InterruptedException ex) { ... handle ...} } void consume(Object x) { ... } } class Setup { void main() { BlockingQueue q = new SomeQueueImplementation(); Producer p = new Producer(q); Consumer c1 = new Consumer(q); Consumer c2 = new Consumer(q); new Thread(p).start(); new Thread(c1).start(); new Thread(c2).start(); } } This interface is a member of the Java Collections Framework.
|
addboolean add(E e)
| |
addboolean add(E o)
|
addboolean add(E e)
|
containsboolean contains(Object o)
|
drainToint drainTo(Collection<? super E> c)
| |
drainToint drainTo(Collection<? super E> c)
|
drainToint drainTo(Collection<? super E> c)
|
drainToint drainTo(Collection<? super E> c, int maxElements)
| |
drainToint drainTo(Collection<? super E> c, int maxElements)
|
drainToint drainTo(Collection<? super E> c, int maxElements)
|
offerboolean offer(E e)
| |
offerboolean offer(E o)
|
offerboolean offer(E e)
|
offerboolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
| |
offerboolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException
|
offerboolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
|
pollE poll(long timeout, TimeUnit unit) throws InterruptedException
| |
pollE poll(long timeout, TimeUnit unit) throws InterruptedException
|
pollE poll(long timeout, TimeUnit unit) throws InterruptedException
|
putvoid put(E e) throws InterruptedException
| |
putvoid put(E o) throws InterruptedException
|
putvoid put(E e) throws InterruptedException
|
removeboolean remove(Object o)
|
takeE take() throws InterruptedException
| |
takeE take() throws InterruptedException
|
takeE take() throws InterruptedException
|
submitFuture<V> submit(Runnable task, V result)
| |
submitFuture<V> submit(Runnable task, V result)
|
submitFuture<V> submit(Runnable task, V result)
|
submitFuture<V> submit(Callable<V> task)
| |
submitFuture<V> submit(Callable<V> task)
|
submitFuture<V> submit(Callable<V> task)
|
Static methods that operate on or return instances of collection and synchronizer classes and interfaces defined in this package.
|
Concurrentpublic Concurrent() |
asLifoBlockingQueuepublic static <T> BlockingQueue<T> asLifoBlockingQueue(BlockingDeque<T> deque)
|
ConcurrentHashMappublic ConcurrentHashMap(int initialCapacity)
| |
ConcurrentHashMappublic ConcurrentHashMap(int initialCapacity)
|
ConcurrentHashMappublic ConcurrentHashMap(int initialCapacity)
|
ConcurrentHashMappublic ConcurrentHashMap(int initialCapacity, float loadFactor)
|
ConcurrentHashMappublic ConcurrentHashMap(Map<? extends K,? extends V> m)
| |
ConcurrentHashMappublic ConcurrentHashMap(Map<? extends K,? extends V> t)
|
ConcurrentHashMappublic ConcurrentHashMap(Map<? extends K,? extends V> m)
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
| |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
getpublic V get(Object key)
| |
getpublic V get(Object key)
|
getpublic V get(Object key)
|
isEmptypublic boolean isEmpty()
| |
isEmptypublic boolean isEmpty()
|
isEmptypublic boolean isEmpty() |
keySetpublic Set<K> keySet()
| |
keySetpublic Set<K> keySet()
|
keySetpublic Set<K> keySet()
|
putpublic V put(K key, V value)
| |
putpublic V put(K key, V value)
|
putpublic V put(K key, V value)
|
removepublic V remove(Object key)
| |
removepublic V remove(Object key)
|
removepublic V remove(Object key)
|
removepublic boolean remove(Object key, Object value)
| |
removepublic boolean remove(Object key, Object value)
|
removepublic boolean remove(Object key, Object value)
|
replacepublic V replace(K key, V value)
| |
replacepublic V replace(K key, V value)
|
replacepublic V replace(K key, V value)
|
replacepublic boolean replace(K key, V oldValue, V newValue)
| |
replacepublic boolean replace(K key, V oldValue, V newValue)
|
replacepublic boolean replace(K key, V oldValue, V newValue)
|
sizepublic int size()
| |
sizepublic int size()
|
sizepublic int size() |
valuespublic Collection<V> values()
| |
valuespublic Collection<V> values()
|
valuespublic Collection<V> values()
|
ConcurrentLinkedQueuepublic ConcurrentLinkedQueue(Collection<? extends E> c)
| |
ConcurrentLinkedQueuepublic ConcurrentLinkedQueue(Collection<? extends E> c)
|
ConcurrentLinkedQueuepublic ConcurrentLinkedQueue(Collection<? extends E> c)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
isEmptypublic boolean isEmpty()
| |
isEmptypublic boolean isEmpty()
|
isEmptypublic boolean isEmpty()
|
offerpublic boolean offer(E e)
| |
offerpublic boolean offer(E o)
|
offerpublic boolean offer(E e)
|
peekpublic E peek() | |
peekpublic E peek() |
peekpublic E peek() |
pollpublic E poll() | |
pollpublic E poll() |
pollpublic E poll() |
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
putIfAbsentV putIfAbsent(K key, V value)
| |
putIfAbsentV putIfAbsent(K key, V value)
|
putIfAbsentV putIfAbsent(K key, V value)
|
removeboolean remove(Object key, Object value)
| |
removeboolean remove(Object key, Object value)
|
removeboolean remove(Object key, Object value)
|
replaceV replace(K key, V value)
| |
replaceV replace(K key, V value)
|
replaceV replace(K key, V value)
|
replaceboolean replace(K key, V oldValue, V newValue)
| |
replaceboolean replace(K key, V oldValue, V newValue)
|
replaceboolean replace(K key, V oldValue, V newValue)
|
An optionally-bounded blocking deque based on linked nodes. The optional capacity bound constructor argument serves as a
way to prevent excessive expansion. The capacity, if unspecified,
is equal to Most operations run in constant time (ignoring time spent
blocking). Exceptions include This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
LinkedBlockingDequepublic LinkedBlockingDeque()
|
LinkedBlockingDequepublic LinkedBlockingDeque(int capacity)
|
LinkedBlockingDequepublic LinkedBlockingDeque(Collection<? extends E> c)
|
addpublic boolean add(E e)
|
addFirstpublic void addFirst(E e)
|
addLastpublic void addLast(E e)
|
clearpublic void clear()
|
containspublic boolean contains(Object o)
|
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
elementpublic E element()
|
getFirstpublic E getFirst()
|
getLastpublic E getLast()
|
iteratorpublic Iterator<E> iterator()
|
offerpublic boolean offer(E e)
|
offerpublic boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
|
offerFirstpublic boolean offerFirst(E e)
|
offerFirstpublic boolean offerFirst(E e, long timeout, TimeUnit unit) throws InterruptedException
|
offerLastpublic boolean offerLast(E e)
|
offerLastpublic boolean offerLast(E e, long timeout, TimeUnit unit) throws InterruptedException
|
peekpublic E peek()
|
peekFirstpublic E peekFirst() |
peekLastpublic E peekLast() |
pollpublic E poll()
|
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
pollFirstpublic E pollFirst() |
pollFirstpublic E pollFirst(long timeout, TimeUnit unit) throws InterruptedException
|
pollLastpublic E pollLast() |
pollLastpublic E pollLast(long timeout, TimeUnit unit) throws InterruptedException
|
poppublic E pop()
|
pushpublic void push(E e)
|
putpublic void put(E e) throws InterruptedException
|
putFirstpublic void putFirst(E e) throws InterruptedException
|
putLastpublic void putLast(E e) throws InterruptedException
|
remainingCapacitypublic int remainingCapacity()
|
removepublic E remove()
|
removepublic boolean remove(Object o)
|
removeFirstpublic E removeFirst()
|
removeFirstOccurrencepublic boolean removeFirstOccurrence(Object o)
|
removeLastpublic E removeLast()
|
removeLastOccurrencepublic boolean removeLastOccurrence(Object o)
|
sizepublic int size()
|
takepublic E take() throws InterruptedException
|
takeFirstpublic E takeFirst() throws InterruptedException
|
takeLastpublic E takeLast() throws InterruptedException
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
|
toStringpublic String toString()
|
A This interface is a member of the Java Collections Framework.
|
headMapConcurrentNavigableMap<K,V> headMap(K toKey)
|
navigableHeadMapConcurrentNavigableMap<K,V> navigableHeadMap(K toKey)
|
navigableSubMapConcurrentNavigableMap<K,V> navigableSubMap(K fromKey, K toKey)
|
navigableTailMapConcurrentNavigableMap<K,V> navigableTailMap(K fromKey)
|
subMapConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey)
|
tailMapConcurrentNavigableMap<K,V> tailMap(K fromKey)
|
A scalable concurrent This class implements a concurrent variant of SkipLists providing
expected average log(n) time cost for the
containsKey, get, put and
remove operations and their variants. Insertion, removal,
update, and access operations safely execute concurrently by
multiple threads. Iterators are weakly consistent, returning
elements reflecting the state of the map at some point at or since
the creation of the iterator. They do not throw All Map.Entry pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. (Note however that it is possible to change mappings in the associated map using put, putIfAbsent, or replace, depending on exactly which effect you need.) Beware that, unlike in most collections, the size method is not a constant-time operation. Because of the asynchronous nature of these maps, determining the current number of elements requires a traversal of the elements. Additionally, the bulk operations putAll, equals, and clear are not guaranteed to be performed atomically. For example, an iterator operating concurrently with a putAll operation might view only some of the added elements. This class and its views and iterators implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
ConcurrentSkipListMappublic ConcurrentSkipListMap()
|
ConcurrentSkipListMappublic ConcurrentSkipListMap(Comparator<? super K> comparator)
|
ConcurrentSkipListMappublic ConcurrentSkipListMap(Map<? extends K,? extends V> m)
|
ConcurrentSkipListMappublic ConcurrentSkipListMap(SortedMap<K,? extends V> m)
|
ceilingEntrypublic Map.Entry<K,V> ceilingEntry(K key)
|
ceilingKeypublic K ceilingKey(K key)
|
clearpublic void clear() |
clonepublic ConcurrentSkipListMap<K,V> clone()
|
comparatorpublic Comparator<? super K> comparator()
|
containsKeypublic boolean containsKey(Object key)
|
containsValuepublic boolean containsValue(Object value)
|
descendingEntrySetpublic Set<Map.Entry<K,V>> descendingEntrySet()
|
descendingKeySetpublic Set<K> descendingKeySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
equalspublic boolean equals(Object o)
|
firstEntrypublic Map.Entry<K,V> firstEntry()
|
firstKeypublic K firstKey() |
floorEntrypublic Map.Entry<K,V> floorEntry(K key)
|
floorKeypublic K floorKey(K key)
|
getpublic V get(Object key)
|
headMappublic ConcurrentNavigableMap<K,V> headMap(K toKey)
|
higherEntrypublic Map.Entry<K,V> higherEntry(K key)
|
higherKeypublic K higherKey(K key)
|
isEmptypublic boolean isEmpty() |
keySetpublic Set<K> keySet()
|
lastEntrypublic Map.Entry<K,V> lastEntry()
|
lastKeypublic K lastKey() |
lowerEntrypublic Map.Entry<K,V> lowerEntry(K key)
|
lowerKeypublic K lowerKey(K key)
|
navigableHeadMappublic ConcurrentNavigableMap<K,V> navigableHeadMap(K toKey)
|
navigableSubMappublic ConcurrentNavigableMap<K,V> navigableSubMap(K fromKey, K toKey)
|
navigableTailMappublic ConcurrentNavigableMap<K,V> navigableTailMap(K fromKey)
|
pollFirstEntrypublic Map.Entry<K,V> pollFirstEntry()
|
pollLastEntrypublic Map.Entry<K,V> pollLastEntry()
|
putpublic V put(K key, V value)
|
putIfAbsentpublic V putIfAbsent(K key, V value)
|
removepublic V remove(Object key)
|
removepublic boolean remove(Object key, Object value)
|
replacepublic V replace(K key, V value)
|
replacepublic boolean replace(K key, V oldValue, V newValue)
|
subMappublic ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey)
|
tailMappublic ConcurrentNavigableMap<K,V> tailMap(K fromKey)
|
valuespublic Collection<V> values()
|
A scalable concurrent This implementation provides expected average log(n) time
cost for the contains, add, and remove
operations and their variants. Insertion, removal, and access
operations safely execute concurrently by multiple threads.
Iterators are weakly consistent, returning elements
reflecting the state of the set at some point at or since the
creation of the iterator. They do not throw Beware that, unlike in most collections, the size method is not a constant-time operation. Because of the asynchronous nature of these sets, determining the current number of elements requires a traversal of the elements. Additionally, the bulk operations addAll, removeAll, retainAll, and containsAll are not guaranteed to be performed atomically. For example, an iterator operating concurrently with an addAll operation might view only some of the added elements. This class and its iterators implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
ConcurrentSkipListSetpublic ConcurrentSkipListSet()
|
ConcurrentSkipListSetpublic ConcurrentSkipListSet(Collection<? extends E> c)
|
ConcurrentSkipListSetpublic ConcurrentSkipListSet(Comparator<? super E> comparator)
|
ConcurrentSkipListSetpublic ConcurrentSkipListSet(SortedSet<E> s)
|
addpublic boolean add(E e)
|
ceilingpublic E ceiling(E e)
|
clearpublic void clear()
|
clonepublic ConcurrentSkipListSet<E> clone() |
comparatorpublic Comparator<? super E> comparator()
|
containspublic boolean contains(Object o)
|
descendingIteratorpublic Iterator<E> descendingIterator()
|
equalspublic boolean equals(Object o)
|
firstpublic E first()
|
floorpublic E floor(E e)
|
headSetpublic SortedSet<E> headSet(E toElement)
|
higherpublic E higher(E e)
|
isEmptypublic boolean isEmpty()
|
iteratorpublic Iterator<E> iterator()
|
lastpublic E last()
|
lowerpublic E lower(E e)
|
navigableHeadSetpublic NavigableSet<E> navigableHeadSet(E toElement)
|
navigableSubSetpublic NavigableSet<E> navigableSubSet(E fromElement, E toElement)
|
navigableTailSetpublic NavigableSet<E> navigableTailSet(E fromElement)
|
pollFirstpublic E pollFirst()
|
pollLastpublic E pollLast()
|
removepublic boolean remove(Object o)
|
removeAllpublic boolean removeAll(Collection<?> c)
|
sizepublic int size()
|
subSetpublic SortedSet<E> subSet(E fromElement, E toElement)
|
tailSetpublic SortedSet<E> tailSet(E fromElement)
|
A thread-safe variant of ArrayList in which all mutative operations ( add , set , and so on) are implemented by making a fresh copy of the underlying array.
This is ordinarily too costly, but may be
more
efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don't want to synchronize traversals, yet need to preclude interference among concurrent threads. The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw
ConcurrentModificationException
. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves ( All elements are permitted, including null. This class is a member of the Java Collections Framework.
| |
A thread-safe variant of This is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don't want to synchronize traversals, yet need to preclude interference among concurrent threads. The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException. This class is a member of the Java Collections Framework.
|
A thread-safe variant of This is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don't want to synchronize traversals, yet need to preclude interference among concurrent threads. The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException. All elements are permitted, including null. This class is a member of the Java Collections Framework.
|
CopyOnWriteArrayListpublic CopyOnWriteArrayList(E[] toCopyIn)
| |
CopyOnWriteArrayListpublic CopyOnWriteArrayList(E[] toCopyIn)
|
CopyOnWriteArrayListpublic CopyOnWriteArrayList(E[] toCopyIn)
|
CopyOnWriteArrayListpublic CopyOnWriteArrayList(Collection<? extends E> c)
| |
CopyOnWriteArrayListpublic CopyOnWriteArrayList(Collection<? extends E> c)
|
CopyOnWriteArrayListpublic CopyOnWriteArrayList(Collection<? extends E> c)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E element) |
addpublic boolean add(E e)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
| |
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
| |
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllAbsentpublic int addAllAbsent(Collection<? extends E> c)
| |
addAllAbsentpublic int addAllAbsent(Collection<? extends E> c)
|
addAllAbsentpublic int addAllAbsent(Collection<? extends E> c)
|
addIfAbsentpublic boolean addIfAbsent(E e)
| |
addIfAbsentpublic boolean addIfAbsent(E element)
|
addIfAbsentpublic boolean addIfAbsent(E e)
|
clearpublic void clear() | |
clearpublic void clear() |
clearpublic void clear() |
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object elem) |
containspublic boolean contains(Object o)
|
containsAllpublic boolean containsAll(Collection<?> c)
| |
containsAllpublic boolean containsAll(Collection<?> c)
|
containsAllpublic boolean containsAll(Collection<?> c)
|
equalspublic boolean equals(Object o)
| |
equalspublic boolean equals(Object o)
|
equalspublic boolean equals(Object o)
|
hashCodepublic int hashCode()
| |
hashCodepublic int hashCode()
|
hashCodepublic int hashCode()
|
indexOfpublic int indexOf(Object o)
| |
indexOfpublic int indexOf(Object elem)
|
indexOfpublic int indexOf(Object o)
|
indexOfpublic int indexOf(E e, int index)
| |
indexOfpublic int indexOf(E elem, int index)
|
indexOfpublic int indexOf(E e, int index)
|
isEmptypublic boolean isEmpty() | |
isEmptypublic boolean isEmpty() |
isEmptypublic boolean isEmpty() |
iteratorpublic Iterator<E> iterator()
| |
iteratorpublic Iterator<E> iterator()
|
iteratorpublic Iterator<E> iterator()
|
lastIndexOfpublic int lastIndexOf(Object o)
| |
lastIndexOfpublic int lastIndexOf(Object elem)
|
lastIndexOfpublic int lastIndexOf(Object o)
|
lastIndexOfpublic int lastIndexOf(E e, int index)
| |
lastIndexOfpublic int lastIndexOf(E elem, int index)
|
lastIndexOfpublic int lastIndexOf(E e, int index)
|
listIteratorpublic ListIterator<E> listIterator()
| |
listIteratorpublic ListIterator<E> listIterator()
|
listIteratorpublic ListIterator<E> listIterator()
|
listIteratorpublic ListIterator<E> listIterator(int index)
| |
listIteratorpublic ListIterator<E> listIterator(int index)
|
listIteratorpublic ListIterator<E> listIterator(int index)
|
removepublic E remove(int index)
| |
removepublic E remove(int index)
|
removepublic E remove(int index)
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
removeAllpublic boolean removeAll(Collection<?> c)
| |
removeAllpublic boolean removeAll(Collection<?> c)
|
removeAllpublic boolean removeAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
| |
retainAllpublic boolean retainAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
|
setpublic E set(int index, E element)
| |
setpublic E set(int index, E element)
|
setpublic E set(int index, E element)
|
subListpublic List<E> subList(int fromIndex, int toIndex)
| |
subListpublic List<E> subList(int fromIndex, int toIndex)
|
subListpublic List<E> subList(int fromIndex, int toIndex)
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
toStringpublic String toString() | |
toStringpublic String toString() |
toStringpublic String toString() |
A Set that uses an internal CopyOnWriteArrayList for all of its operations. Thus, it shares the same basic properties:
Sample Usage. The following code sketch uses a copy-on-write set to maintain a set of Handler objects that perform some action upon state updates. class Handler { void handle(); ... } class X { private final CopyOnWriteArraySet<Handler> handlers = new CopyOnWriteArraySet<Handler>(); public void addHandler(Handler h) { handlers.add(h); } private long internalState; private synchronized void changeState() { internalState = ...; } public void update() { changeState(); for (Handler handler : handlers) handler.handle(); } } This class is a member of the Java Collections Framework.
| |
A
Sample Usage. The following code sketch uses a copy-on-write set to maintain a set of Handler objects that perform some action upon state updates. class Handler { void handle(); ... } class X { private final CopyOnWriteArraySet<Handler> handlers = new CopyOnWriteArraySet<Handler>(); public void addHandler(Handler h) { handlers.add(h); } private long internalState; private synchronized void changeState() { internalState = ...; } public void update() { changeState(); for (Handler handler : handlers) handler.handle(); } } This class is a member of the Java Collections Framework.
|
A
Sample Usage. The following code sketch uses a copy-on-write set to maintain a set of Handler objects that perform some action upon state updates. class Handler { void handle(); ... } class X { private final CopyOnWriteArraySet<Handler> handlers = new CopyOnWriteArraySet<Handler>(); public void addHandler(Handler h) { handlers.add(h); } private long internalState; private synchronized void changeState() { internalState = ...; } public void update() { changeState(); for (Handler handler : handlers) handler.handle(); } } This class is a member of the Java Collections Framework.
|
CopyOnWriteArraySetpublic CopyOnWriteArraySet(Collection<? extends E> c)
| |
CopyOnWriteArraySetpublic CopyOnWriteArraySet(Collection<? extends E> c)
|
CopyOnWriteArraySetpublic CopyOnWriteArraySet(Collection<? extends E> c)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
addAllpublic boolean addAll(Collection<? extends E> c)
| |
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
containsAllpublic boolean containsAll(Collection<?> c)
| |
containsAllpublic boolean containsAll(Collection<?> c)
|
containsAllpublic boolean containsAll(Collection<?> c)
|
isEmptypublic boolean isEmpty()
| |
isEmptypublic boolean isEmpty()
|
isEmptypublic boolean isEmpty()
|
iteratorpublic Iterator<E> iterator()
| |
iteratorpublic Iterator<E> iterator()
|
iteratorpublic Iterator<E> iterator()
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
removeAllpublic boolean removeAll(Collection<?> c)
| |
removeAllpublic boolean removeAll(Collection<?> c)
|
removeAllpublic boolean removeAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
| |
retainAllpublic boolean retainAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
|
sizepublic int size()
| |
sizepublic int size()
|
sizepublic int size()
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released. A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue. Sample usage: Here is an example of using a barrier in a parallel decomposition design: class Solver { final int N; final float[][] data; final CyclicBarrier barrier; class Worker implements Runnable { int myRow; Worker(int row) { myRow = row; } public void run() { while (!done()) { processRow(myRow); try { barrier.await(); } catch (InterruptedException ex) { return; } catch (BrokenBarrierException ex) { return; } } } } public Solver(float[][] matrix) { data = matrix; N = matrix.length; barrier = new CyclicBarrier(N, new Runnable() { public void run() { mergeRows(...); } }); for (int i = 0; i < N; ++i) new Thread(new Worker(i)).start(); waitUntilDone(); } }Here, each worker thread processes a row of the matrix then waits at the barrier until all rows have been processed. When all rows are processed the supplied Runnable barrier action is executed and merges the rows. If the merger determines that a solution has been found then done() will return true and each worker will terminate. If the barrier action does not rely on the parties being suspended when it is executed, then any of the threads in the party could execute that action when it is released. To facilitate this, each invocation of await() returns the arrival index of that thread at the barrier. You can then choose which thread should execute the barrier action, for example: if (barrier.await() == 0) { // log the completion of this iteration }
The
CyclicBarrier
uses an
| |
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released. A CyclicBarrier supports an optional Sample usage: Here is an example of using a barrier in a parallel decomposition design: class Solver { final int N; final float[][] data; final CyclicBarrier barrier; class Worker implements Runnable { int myRow; Worker(int row) { myRow = row; } public void run() { while (!done()) { processRow(myRow); try { barrier.await(); } catch (InterruptedException ex) { return; } catch (BrokenBarrierException ex) { return; } } } } public Solver(float[][] matrix) { data = matrix; N = matrix.length; barrier = new CyclicBarrier(N, new Runnable() { public void run() { mergeRows(...); } }); for (int i = 0; i < N; ++i) new Thread(new Worker(i)).start(); waitUntilDone(); } }Here, each worker thread processes a row of the matrix then waits at the barrier until all rows have been processed. When all rows are processed the supplied Runnable barrier action is executed and merges the
rows. If the merger
determines that a solution has been found then done() will return
true and each worker will terminate.
If the barrier action does not rely on the parties being suspended when
it is executed, then any of the threads in the party could execute that
action when it is released. To facilitate this, each invocation of
if (barrier.await() == 0) { // log the completion of this iteration } The CyclicBarrier uses a fast-fail all-or-none breakage
model for failed synchronization attempts: If a thread leaves a
barrier point prematurely because of interruption, failure, or
timeout, all other threads, even those that have not yet resumed
from a previous
|
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released. A CyclicBarrier supports an optional Sample usage: Here is an example of using a barrier in a parallel decomposition design: class Solver { final int N; final float[][] data; final CyclicBarrier barrier; class Worker implements Runnable { int myRow; Worker(int row) { myRow = row; } public void run() { while (!done()) { processRow(myRow); try { barrier.await(); } catch (InterruptedException ex) { return; } catch (BrokenBarrierException ex) { return; } } } } public Solver(float[][] matrix) { data = matrix; N = matrix.length; barrier = new CyclicBarrier(N, new Runnable() { public void run() { mergeRows(...); } }); for (int i = 0; i < N; ++i) new Thread(new Worker(i)).start(); waitUntilDone(); } }Here, each worker thread processes a row of the matrix then waits at the barrier until all rows have been processed. When all rows are processed the supplied Runnable barrier action is executed and merges the
rows. If the merger
determines that a solution has been found then done() will return
true and each worker will terminate.
If the barrier action does not rely on the parties being suspended when
it is executed, then any of the threads in the party could execute that
action when it is released. To facilitate this, each invocation of
if (barrier.await() == 0) { // log the completion of this iteration } The CyclicBarrier uses an all-or-none breakage model
for failed synchronization attempts: If a thread leaves a barrier
point prematurely because of interruption, failure, or timeout, all
other threads waiting at that barrier point will also leave
abnormally via
|
CyclicBarrierpublic CyclicBarrier(int parties)
| |
CyclicBarrierpublic CyclicBarrier(int parties)
|
CyclicBarrierpublic CyclicBarrier(int parties)
|
awaitpublic int await() throws InterruptedException, BrokenBarrierException
| |
awaitpublic int await() throws InterruptedException, BrokenBarrierException
|
awaitpublic int await() throws InterruptedException, BrokenBarrierException
|
awaitpublic int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException
| |
awaitpublic int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException
|
awaitpublic int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException
|
An unbounded
blocking queue
of
Delayed
elements, in which an element can only be taken when its delay has expired. The
head
of the queue is that
Delayed
element whose delay expired furthest in the past. If no delay has expired there is no head and
poll
will return
null
. Expiration occurs when an element's
getDelay(TimeUnit.NANOSECONDS)
method returns a value less than or equal to zero. Even though unexpired elements cannot be removed using This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. This class is a member of the Java Collections Framework.
| |
An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. The head of the queue is that Delayed element whose delay expired furthest in the past. If no delay has expired there is no head and poll will return null. Expiration occurs when an element's getDelay(TimeUnit.NANOSECONDS) method returns a value less than or equal to zero. This queue does not permit null elements. This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. The head of the queue is that Delayed element whose delay expired furthest in the past. If no delay has expired there is no head and poll will return null. Expiration occurs when an element's getDelay(TimeUnit.NANOSECONDS) method returns a value less than or equal to zero. Even though unexpired elements cannot be removed using take or poll, they are otherwise treated as normal elements. For example, the size method returns the count of both expired and unexpired elements. This queue does not permit null elements. This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
DelayQueuepublic DelayQueue(Collection<? extends E> c)
| |
DelayQueuepublic DelayQueue(Collection<? extends E> c)
|
DelayQueuepublic DelayQueue(Collection<? extends E> c)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
drainTopublic int drainTo(Collection<? super E> c)
| |
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
| |
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
iteratorpublic Iterator<E> iterator()
| |
iteratorpublic Iterator<E> iterator()
|
iteratorpublic Iterator<E> iterator()
|
peekpublic E peek()
| |
peekpublic E peek() |
peekpublic E peek()
|
pollpublic E poll() | |
pollpublic E poll() |
pollpublic E poll() |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
| |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
putpublic void put(E e)
| |
putpublic void put(E o)
|
putpublic void put(E e)
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
sizepublic int size()
| |
sizepublic int size()
|
sizepublic int size()
|
takepublic E take() throws InterruptedException
| |
takepublic E take() throws InterruptedException
|
takepublic E take() throws InterruptedException
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] array)
|
toArraypublic <T> T[] toArray(T[] a)
|
Exchangerpublic Exchanger()
| |
Exchangerpublic Exchanger()
|
Exchangerpublic Exchanger()
|
An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use: Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); ...However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread: class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } }More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task. class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); } }Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor. class SerialExecutor implements Executor { final Queue<Runnable> tasks = new ArrayDeque<Runnable>();The Executor implementations provided in this package implement ExecutorService , which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.
| |
An object that executes submitted Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); ...However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread: class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } }More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task. class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); } }Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor. class SerialExecutor implements Executor { final Queue<Runnable> tasks = new LinkedBlockingQueue<Runnable>(); final Executor executor; Runnable active; SerialExecutor(Executor executor) { this.executor = executor; } public synchronized void execute(final Runnable r) { tasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (active == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } }The Executor implementations provided in this package implement ExecutorService , which is a more extensive
interface. The ThreadPoolExecutor class provides an
extensible thread pool implementation. The Executors class
provides convenient factory methods for these Executors.
|
An object that executes submitted Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); ...However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread: class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } }More typically, tasks are executed in some thread other than the caller's thread. The executor below spawns a new thread for each task. class ThreadPerTaskExecutor implements Executor { public void execute(Runnable r) { new Thread(r).start(); } }Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor. class SerialExecutor implements Executor { final Queue<Runnable> tasks = new ArrayDeque<Runnable>(); final Executor executor; Runnable active; SerialExecutor(Executor executor) { this.executor = executor; } public synchronized void execute(final Runnable r) { tasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (active == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } }The Executor implementations provided in this package implement ExecutorService , which is a more extensive
interface. The ThreadPoolExecutor class provides an
extensible thread pool implementation. The Executors class
provides convenient factory methods for these Executors.
|
invokeAll<T> List<Future<T>> invokeAll(Collection<? extends Callable
| |
invokeAll<T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks) throws InterruptedException
|
invokeAll<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException
|
invokeAll<T> List<Future<T>> invokeAll(Collection<? extends Callable
| |
invokeAll<T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException
|
invokeAll<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException
|
invokeAny<T> T invokeAny(Collection<? extends Callable
| |
invokeAny<T> T invokeAny(Collection<Callable<T>> tasks) throws InterruptedException, ExecutionException
|
invokeAny<T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException
|
invokeAny<T> T invokeAny(Collection<? extends Callable
| |
invokeAny<T> T invokeAny(Collection<Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
|
invokeAny<T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
|
shutdownNowList<Runnable> shutdownNow()
| |
shutdownNowList<Runnable> shutdownNow()
|
shutdownNowList<Runnable> shutdownNow()
|
submitFuture<?> submit(Runnable task)
| |
submitFuture<?> submit(Runnable task)
|
submitFuture<?> submit(Runnable task)
|
submit<T> Future<T> submit(Runnable task, T result)
| |
submit<T> Future<T> submit(Runnable task, T result)
|
submit<T> Future<T> submit(Runnable task, T result)
|
submit<T> Future<T> submit(Callable<T> task)
| |
submit<T> Future<T> submit(Callable<T> task)
|
submit<T> Future<T> submit(Callable<T> task)
|
callablepublic static Callable<Object> callable(PrivilegedAction<?> action)
| |
callablepublic static Callable<Object> callable(PrivilegedAction action)
|
callablepublic static Callable<Object> callable(PrivilegedAction<?> action)
|
callablepublic static Callable<Object> callable(PrivilegedExceptionAction<?> action)
| |
callablepublic static Callable<Object> callable(PrivilegedExceptionAction action)
|
callablepublic static Callable<Object> callable(PrivilegedExceptionAction<?> action)
|
defaultThreadFactorypublic static ThreadFactory defaultThreadFactory()
| |
defaultThreadFactorypublic static ThreadFactory defaultThreadFactory()
|
defaultThreadFactorypublic static ThreadFactory defaultThreadFactory()
|
newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads)
| |
newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads)
|
newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads)
|
newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
| |
newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
|
newFixedThreadPoolpublic static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
|
A cancellable asynchronous computation. This class provides a base implementation of Future , with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get method will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled. A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable , a FutureTask can be submitted to an Executor for execution. In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.
| |
A cancellable asynchronous computation. This class provides a base
implementation of A FutureTask can be used to wrap a In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.
|
A cancellable asynchronous computation. This class provides a base
implementation of A FutureTask can be used to wrap a In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.
|
cancelpublic boolean cancel(boolean mayInterruptIfRunning)
| |
cancelpublic boolean cancel(boolean mayInterruptIfRunning)
|
cancelpublic boolean cancel(boolean mayInterruptIfRunning)
|
getpublic V get() throws InterruptedException, ExecutionException
| |
getpublic V get() throws InterruptedException, ExecutionException
|
getpublic V get() throws InterruptedException, ExecutionException
|
getpublic V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
| |
getpublic V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
|
getpublic V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
|
runpublic void run()
| |
runpublic void run()
|
runpublic void run()
|
setprotected void set(V v)
| |
setprotected void set(V v)
|
setprotected void set(V v)
|
setExceptionprotected void setException(Throwable t)
| |
setExceptionprotected void setException(Throwable t)
|
setExceptionprotected void setException(Throwable t)
|
A
|
runvoid run()
|
LinkedBlockingQueuepublic LinkedBlockingQueue(Collection<? extends E> c)
| |
LinkedBlockingQueuepublic LinkedBlockingQueue(Collection<? extends E> c)
|
LinkedBlockingQueuepublic LinkedBlockingQueue(Collection<? extends E> c)
|
drainTopublic int drainTo(Collection<? super E> c)
| |
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
| |
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
offerpublic boolean offer(E e)
| |
offerpublic boolean offer(E o)
|
offerpublic boolean offer(E e)
|
peekpublic E peek() | |
peekpublic E peek() |
peekpublic E peek() |
pollpublic E poll() | |
pollpublic E poll() |
pollpublic E poll() |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
| |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
putpublic void put(E e) throws InterruptedException
| |
putpublic void put(E o) throws InterruptedException
|
putpublic void put(E e) throws InterruptedException
|
remainingCapacitypublic int remainingCapacity()
| |
remainingCapacitypublic int remainingCapacity()
|
remainingCapacitypublic int remainingCapacity()
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
takepublic E take() throws InterruptedException
| |
takepublic E take() throws InterruptedException
|
takepublic E take() throws InterruptedException
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
An unbounded
blocking queue
that uses the same ordering rules as class
PriorityQueue
and supplies blocking retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource exhaustion (causing
OutOfMemoryError
). This class does not permit
null
elements. A priority queue relying on
natural ordering
This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityBlockingQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()) . Also, method drainTo can be used to remove some or all elements in priority order and place them in another collection. Operations on this class make no guarantees about the ordering of elements with equal priority. If you need to enforce an ordering, you can define custom classes or comparators that use a secondary key to break ties in primary priority values. For example, here is a class that applies first-in-first-out tie-breaking to comparable elements. To use it, you would insert a new FIFOEntry(anEntry) instead of a plain entry object. class FIFOEntry<E extends Comparable<? super E>> implements Comparable<FIFOEntry<E>> { final static AtomicLong seq = new AtomicLong(); final long seqNum; final E entry; public FIFOEntry(E entry) { seqNum = seq.getAndIncrement(); this.entry = entry; } public E getEntry() { return entry; } public int compareTo(FIFOEntry<E> other) { int res = entry.compareTo(other.entry); if (res == 0 && other.entry != this.entry) res = (seqNum < other.seqNum ? -1 : 1); return res; } } This class is a member of the Java Collections Framework.
| |
An unbounded blocking queue that uses
the same ordering rules as class This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
An unbounded blocking queue that uses
the same ordering rules as class This class and its iterator implement all of the
optional methods of the Operations on this class make no guarantees about the ordering of elements with equal priority. If you need to enforce an ordering, you can define custom classes or comparators that use a secondary key to break ties in primary priority values. For example, here is a class that applies first-in-first-out tie-breaking to comparable elements. To use it, you would insert a new FIFOEntry(anEntry) instead of a plain entry object. class FIFOEntry<E extends Comparable<? super E>> implements Comparable<FIFOEntry<E>> { final static AtomicLong seq = new AtomicLong(); final long seqNum; final E entry; public FIFOEntry(E entry) { seqNum = seq.getAndIncrement(); this.entry = entry; } public E getEntry() { return entry; } public int compareTo(FIFOEntry<E> other) { int res = entry.compareTo(other.entry); if (res == 0 && other.entry != this.entry) res = (seqNum < other.seqNum ? -1 : 1); return res; } } This class is a member of the Java Collections Framework.
|
PriorityBlockingQueuepublic PriorityBlockingQueue()
| |
PriorityBlockingQueuepublic PriorityBlockingQueue()
|
PriorityBlockingQueuepublic PriorityBlockingQueue()
|
PriorityBlockingQueuepublic PriorityBlockingQueue(int initialCapacity)
| |
PriorityBlockingQueuepublic PriorityBlockingQueue(int initialCapacity)
|
PriorityBlockingQueuepublic PriorityBlockingQueue(int initialCapacity)
|
PriorityBlockingQueuepublic PriorityBlockingQueue(Collection<? extends E> c)
| |
PriorityBlockingQueuepublic PriorityBlockingQueue(Collection<? extends E> c)
|
PriorityBlockingQueuepublic PriorityBlockingQueue(Collection<? extends E> c)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
comparatorpublic Comparator<? super E> comparator()
| |
comparatorpublic Comparator<? super E> comparator()
|
comparatorpublic Comparator<? super E> comparator()
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
drainTopublic int drainTo(Collection<? super E> c)
| |
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
| |
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
offerpublic boolean offer(E e)
| |
offerpublic boolean offer(E o)
|
offerpublic boolean offer(E e)
|
peekpublic E peek() | |
peekpublic E peek() |
peekpublic E peek() |
pollpublic E poll() | |
pollpublic E poll() |
pollpublic E poll() |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
| |
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
pollpublic E poll(long timeout, TimeUnit unit) throws InterruptedException
|
putpublic void put(E e)
| |
putpublic void put(E o)
|
putpublic void put(E e)
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
sizepublic int size()
| |
sizepublic int size()
|
sizepublic int size()
|
takepublic E take() throws InterruptedException
| |
takepublic E take() throws InterruptedException
|
takepublic E take() throws InterruptedException
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
A
|
scheduleScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
| |
scheduleScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
|
scheduleScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
|
scheduleAtFixedRateScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
| |
scheduleAtFixedRateScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
|
scheduleAtFixedRateScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
|
scheduleWithFixedDelayScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
| |
scheduleWithFixedDelayScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
|
scheduleWithFixedDelayScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
|
A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required. Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission. While this class inherits from ThreadPoolExecutor , a few of the inherited tuning methods are not useful for it. In particular, because it acts as a fixed-sized pool using corePoolSize threads and an unbounded queue, adjustments to maximumPoolSize have no useful effect. This class supports protected extension method decorateTask (one version each for Runnable and Callable ) that can be used to customize the concrete task types used to execute commands. By default, a ScheduledThreadPoolExecutor uses a task type extending FutureTask . However, this may be modified or replaced using subclasses of the form: public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor { static class CustomTask<V> implements RunnableScheduledFuture<V> { ... } protected <V> RunnableScheduledFuture<V> decorateTask( Runnable r, RunnableScheduledFuture<V> task) { return new CustomTask<V>(r, task); } protected <V> RunnableScheduledFuture<V> decorateTask( Callable<V> c, RunnableScheduledFuture<V> task) { return new CustomTask<V>(c, task); } // ... add constructors, etc. }
| |
A Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission. While this class inherits from
|
A Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission. While this class inherits from This class supports protected extension method
decorateTask (one version each for Runnable and
Callable) that can be used to customize the concrete task
types used to execute commands. By default,
a ScheduledThreadPoolExecutor uses
a task type extending public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor { static class CustomTask<V> implements RunnableScheduledFuture<V> { ... } protected <V> RunnableScheduledFuture<V> decorateTask( Runnable r, RunnableScheduledFuture<V> task) { return new CustomTask<V>(r, task); } protected <V> RunnableScheduledFuture<V> decorateTask( Callable<V> c, RunnableScheduledFuture<V> task) { return new CustomTask<V>(c, task); } // ... add constructors, etc. }
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize)
| |
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize)
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize)
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler)
| |
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler)
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler)
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory)
| |
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory)
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory)
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler)
| |
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler)
|
ScheduledThreadPoolExecutorpublic ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler)
|
decorateTaskprotected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task)
|
decorateTaskprotected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task)
|
executepublic void execute(Runnable command)
| |
executepublic void execute(Runnable command)
|
executepublic void execute(Runnable command)
|
getContinueExistingPeriodicTasksAfterShutdownPolicypublic boolean getContinueExistingPeriodicTasksAfterShutdownPolicy()
| |
getContinueExistingPeriodicTasksAfterShutdownPolicypublic boolean getContinueExistingPeriodicTasksAfterShutdownPolicy()
|
getContinueExistingPeriodicTasksAfterShutdownPolicypublic boolean getContinueExistingPeriodicTasksAfterShutdownPolicy()
|
getExecuteExistingDelayedTasksAfterShutdownPolicypublic boolean getExecuteExistingDelayedTasksAfterShutdownPolicy()
| |
getExecuteExistingDelayedTasksAfterShutdownPolicypublic boolean getExecuteExistingDelayedTasksAfterShutdownPolicy()
|
getExecuteExistingDelayedTasksAfterShutdownPolicypublic boolean getExecuteExistingDelayedTasksAfterShutdownPolicy()
|
schedulepublic ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
| |
schedulepublic ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
|
schedulepublic ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
|
scheduleAtFixedRatepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
| |
scheduleAtFixedRatepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
|
scheduleAtFixedRatepublic ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
|
scheduleWithFixedDelaypublic ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
| |
scheduleWithFixedDelaypublic ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
|
scheduleWithFixedDelaypublic ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
|
setContinueExistingPeriodicTasksAfterShutdownPolicypublic void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)
| |
setContinueExistingPeriodicTasksAfterShutdownPolicypublic void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)
|
setContinueExistingPeriodicTasksAfterShutdownPolicypublic void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value)
|
setExecuteExistingDelayedTasksAfterShutdownPolicypublic void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)
| |
setExecuteExistingDelayedTasksAfterShutdownPolicypublic void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)
|
setExecuteExistingDelayedTasksAfterShutdownPolicypublic void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value)
|
shutdownNowpublic List<Runnable> shutdownNow()
| |
shutdownNowpublic List<Runnable> shutdownNow()
|
shutdownNowpublic List<Runnable> shutdownNow()
|
submitpublic Future<?> submit(Runnable task)
| |
submitpublic Future<?> submit(Runnable task)
|
submitpublic Future<?> submit(Runnable task)
|
submitpublic <T> Future<T> submit(Runnable task, T result)
| |
submitpublic <T> Future<T> submit(Runnable task, T result)
|
submitpublic <T> Future<T> submit(Runnable task, T result)
|
submitpublic <T> Future<T> submit(Callable<T> task)
| |
submitpublic <T> Future<T> submit(Callable<T> task)
|
submitpublic <T> Future<T> submit(Callable<T> task)
|
A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly. 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: 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; } } 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 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. 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 binary semaphore , 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 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. The constructor for this class optionally accepts a fairness parameter. When set false, this class makes no guarantees about the order in which threads acquire permits. In particular, barging is permitted, that is, a thread invoking 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 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 acquire before another, but reach the ordering point after the other, and similarly upon return from the method. Also note that the untimed tryAcquire methods do not honor the fairness setting, but will take any permits that are available. 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. This class also provides convenience methods to acquire and release multiple permits at a time. Beware of the increased risk of indefinite postponement when these methods are used without fairness set true.
| |
A counting semaphore. Conceptually, a semaphore maintains a set of
permits. Each 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: class Pool { private static final 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; } } 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 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 binary
semaphore, 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 The constructor for this class optionally accepts a
fairness parameter. When set false, this class makes no
guarantees about the order in which threads acquire permits. In
particular, barging is permitted, that is, a thread
invoking 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. This class also provides convenience methods to
|
A counting semaphore. Conceptually, a semaphore maintains a set of
permits. Each 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: 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; } } 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 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 binary
semaphore, 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 The constructor for this class optionally accepts a
fairness parameter. When set false, this class makes no
guarantees about the order in which threads acquire permits. In
particular, barging is permitted, that is, a thread
invoking 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. This class also provides convenience methods to
|
A
blocking queue
in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot Synchronous queues are similar to rendezvous channels used in CSP and Ada. They are well suited for handoff designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task.
This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to
true
grants threads access in FIFO order. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. This class is a member of the Java Collections Framework.
| |
A blocking queue in which each put must wait for a take, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to take it; you cannot add an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate. The head of the queue is the element that the first queued thread is trying to add to the queue; if there are no queued threads then no element is being added and the head is null. For purposes of other Collection methods (for example contains), a SynchronousQueue acts as an empty collection. This queue does not permit null elements. Synchronous queues are similar to rendezvous channels used in CSP and Ada. They are well suited for handoff designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task. This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation. This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is only present when you try to remove it; you cannot insert an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate. The head of the queue is the element that the first queued inserting thread is trying to add to the queue; if there is no such queued thread then no element is available for removal and poll() will return null. For purposes of other Collection methods (for example contains), a SynchronousQueue acts as an empty collection. This queue does not permit null elements. Synchronous queues are similar to rendezvous channels used in CSP and Ada. They are well suited for handoff designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task. This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
drainTopublic int drainTo(Collection<? super E> c)
| |
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
| |
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
drainTopublic int drainTo(Collection<? super E> c, int maxElements)
|
offerpublic boolean offer(E e)
| |
offerpublic boolean offer(E o)
|
offerpublic boolean offer(E e)
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks. To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient Executors factory methods Executors.newCachedThreadPool() (unbounded thread pool, with automatic thread reclamation), Executors.newFixedThreadPool(int) (fixed size thread pool) and Executors.newSingleThreadExecutor() (single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:
Extension example . Most extensions of this class override one or more of the protected hook methods. For example, here is a subclass that adds a simple pause/resume feature: class PausableThreadPoolExecutor extends ThreadPoolExecutor { private boolean isPaused; private ReentrantLock pauseLock = new ReentrantLock(); private Condition unpaused = pauseLock.newCondition(); public PausableThreadPoolExecutor(...) { super(...); } protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); pauseLock.lock(); try { while (isPaused) unpaused.await(); } catch (InterruptedException ie) { t.interrupt(); } finally { pauseLock.unlock(); } } public void pause() { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } } public void resume() { pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } }
| |
An Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks. To be useful across a wide range of contexts, this class
provides many adjustable parameters and extensibility
hooks. However, programmers are urged to use the more convenient
Extension example. Most extensions of this class override one or more of the protected hook methods. For example, here is a subclass that adds a simple pause/resume feature: class PausableThreadPoolExecutor extends ThreadPoolExecutor { private boolean isPaused; private ReentrantLock pauseLock = new ReentrantLock(); private Condition unpaused = pauseLock.newCondition(); public PausableThreadPoolExecutor(...) { super(...); } protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); pauseLock.lock(); try { while (isPaused) unpaused.await(); } catch(InterruptedException ie) { t.interrupt(); } finally { pauseLock.unlock(); } } public void pause() { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } } public void resume() { pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } }
|
An Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks. To be useful across a wide range of contexts, this class
provides many adjustable parameters and extensibility
hooks. However, programmers are urged to use the more convenient
Extension example. Most extensions of this class override one or more of the protected hook methods. For example, here is a subclass that adds a simple pause/resume feature: class PausableThreadPoolExecutor extends ThreadPoolExecutor { private boolean isPaused; private ReentrantLock pauseLock = new ReentrantLock(); private Condition unpaused = pauseLock.newCondition(); public PausableThreadPoolExecutor(...) { super(...); } protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); pauseLock.lock(); try { while (isPaused) unpaused.await(); } catch (InterruptedException ie) { t.interrupt(); } finally { pauseLock.unlock(); } } public void pause() { pauseLock.lock(); try { isPaused = true; } finally { pauseLock.unlock(); } } public void resume() { pauseLock.lock(); try { isPaused = false; unpaused.signalAll(); } finally { pauseLock.unlock(); } } }
|
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
| |
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
|
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
|
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
| |
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
|
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)
|
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
| |
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
|
ThreadPoolExecutorpublic ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
|
afterExecuteprotected void afterExecute(Runnable r, Throwable t)
| |
afterExecuteprotected void afterExecute(Runnable r, Throwable t)
|
afterExecuteprotected void afterExecute(Runnable r, Throwable t)
|
allowCoreThreadTimeOutpublic void allowCoreThreadTimeOut(boolean value)
|
beforeExecuteprotected void beforeExecute(Thread t, Runnable r)
| |
beforeExecuteprotected void beforeExecute(Thread t, Runnable r)
|
beforeExecuteprotected void beforeExecute(Thread t, Runnable r)
|
setKeepAliveTimepublic void setKeepAliveTime(long time, TimeUnit unit)
| |
setKeepAliveTimepublic void setKeepAliveTime(long time, TimeUnit unit)
|
setKeepAliveTimepublic void setKeepAliveTime(long time, TimeUnit unit)
|
shutdownNowpublic List<Runnable> shutdownNow()
| |
shutdownNowpublic List<Runnable> shutdownNow()
|
shutdownNowpublic List<Runnable> shutdownNow()
|
A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours. A TimeUnit is mainly used to inform time-based methods how a given timing parameter should be interpreted. For example, the following code will timeout in 50 milliseconds if the lock is not available: Lock lock = ...; if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...while this code will timeout in 50 seconds: Lock lock = ...; if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...Note however, that there is no guarantee that a particular timeout implementation will be able to notice the passage of time at the same granularity as the given TimeUnit .
| |
A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A TimeUnit is mainly used to inform time-based methods
how a given timing parameter should be interpreted. For example,
the following code will timeout in 50 milliseconds if the Lock lock = ...; if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...while this code will timeout in 50 seconds: Lock lock = ...; if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...Note however, that there is no guarantee that a particular timeout implementation will be able to notice the passage of time at the same granularity as the given TimeUnit.
|
A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours. A TimeUnit is mainly used to inform time-based methods
how a given timing parameter should be interpreted. For example,
the following code will timeout in 50 milliseconds if the Lock lock = ...; if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...while this code will timeout in 50 seconds: Lock lock = ...; if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...Note however, that there is no guarantee that a particular timeout implementation will be able to notice the passage of time at the same granularity as the given TimeUnit.
|
convertpublic long convert(long sourceDuration,
| |
convertpublic long convert(long duration, TimeUnit unit)
|
convertpublic long convert(long sourceDuration, TimeUnit sourceUnit)
|
sleeppublic void sleep(long timeout) throws InterruptedException
| |
sleeppublic void sleep(long timeout) throws InterruptedException
|
sleeppublic void sleep(long timeout) throws InterruptedException
|
timedJoinpublic void timedJoin(Thread thread, long timeout) throws InterruptedException
| |
timedJoinpublic void timedJoin(Thread thread, long timeout) throws InterruptedException
|
timedJoinpublic void timedJoin(Thread thread, long timeout) throws InterruptedException
|
timedWaitpublic void timedWait(Object obj, long timeout) throws InterruptedException
| |
timedWaitpublic void timedWait(Object obj, long timeout) throws InterruptedException
|
timedWaitpublic void timedWait(Object obj, long timeout) throws InterruptedException
|
toDayspublic long toDays(long duration)
|
toHourspublic long toHours(long duration)
|
toMinutespublic long toMinutes(long duration)
|
toSecondspublic long toSeconds(long duration)
| |
toSecondspublic long toSeconds(long duration)
|
toSecondspublic long toSeconds(long duration)
|
An Entry maintaining a key and a value. The value may be changed using the setValue method. This class facilitates the process of building custom map implementations. For example, it may be convenient to return arrays of SimpleEntry instances in method Map.entrySet().toArray.
|
AbstractMap.SimpleEntrypublic AbstractMap.SimpleEntry(K key, V value)
|
AbstractMap.SimpleEntrypublic AbstractMap.SimpleEntry(Map.Entry<? extends K,? extends V> entry)
|
equalspublic boolean equals(Object o)
|
getKeypublic K getKey() |
getValuepublic V getValue() |
hashCodepublic int hashCode()
|
setValuepublic V setValue(V value) |
toStringpublic String toString()
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
addAllpublic boolean addAll(Collection<? extends E> c)
| |
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
containsAllpublic boolean containsAll(Collection<?> c)
| |
containsAllpublic boolean containsAll(Collection<?> c)
|
containsAllpublic boolean containsAll(Collection<?> c)
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
removeAllpublic boolean removeAll(Collection<?> c)
| |
removeAllpublic boolean removeAll(Collection<?> c)
|
removeAllpublic boolean removeAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
| |
retainAllpublic boolean retainAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
|
sizepublic abstract int size()
| |
sizepublic abstract int size()
|
sizepublic abstract int size()
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class. To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods. To implement a modifiable list, the programmer must additionally override the set(int index, Object element) method (which otherwise throws an UnsupportedOperationException . If the list is variable-size the programmer must additionally override the add(int index, Object element) and remove(int index) methods. The programmer should generally provide a void (no argument) and collection constructor, as per the recommendation in the Collection interface specification.
Unlike the other abstract collection implementations, the programmer does
not
have to provide an iterator implementation; the iterator and list iterator are implemented by this class, on top of the "random access" methods:
get(int index)
,
set(int index, E The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. This class is a member of the Java Collections Framework.
| |
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class. To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods. To implement a modifiable list, the programmer must additionally override the set(int index, Object element) method (which otherwise throws an UnsupportedOperationException. If the list is variable-size the programmer must additionally override the add(int index, Object element) and remove(int index) methods. The programmer should generally provide a void (no argument) and collection constructor, as per the recommendation in the Collection interface specification. Unlike the other abstract collection implementations, the programmer does not have to provide an iterator implementation; the iterator and list iterator are implemented by this class, on top the "random access" methods: get(int index), set(int index, Object element), set(int index, Object element), add(int index, Object element) and remove(int index). The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. This class is a member of the Java Collections Framework.
|
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class. To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int index) and size() methods. To implement a modifiable list, the programmer must additionally override the set(int index, Object element) method (which otherwise throws an UnsupportedOperationException. If the list is variable-size the programmer must additionally override the add(int index, Object element) and remove(int index) methods. The programmer should generally provide a void (no argument) and collection constructor, as per the recommendation in the Collection interface specification. Unlike the other abstract collection implementations, the programmer does not have to provide an iterator implementation; the iterator and list iterator are implemented by this class, on top of the "random access" methods: get(int index), set(int index, E element), add(int index, E element) and remove(int index). The documentation for each non-abstract methods in this class describes its implementation in detail. Each of these methods may be overridden if the collection being implemented admits a more efficient implementation. This class is a member of the Java Collections Framework.
|
addpublic void add(int index, E element)
| |
addpublic void add(int index, E element)
|
addpublic void add(int index, E element)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
| |
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
hashCodepublic int hashCode()
| |
hashCodepublic int hashCode()
|
hashCodepublic int hashCode()
|
indexOfpublic int indexOf(Object o)
| |
indexOfpublic int indexOf(Object o)
|
indexOfpublic int indexOf(Object o)
|
lastIndexOfpublic int lastIndexOf(Object o)
| |
lastIndexOfpublic int lastIndexOf(Object o)
|
lastIndexOfpublic int lastIndexOf(Object o)
|
listIteratorpublic ListIterator<E> listIterator()
| |
listIteratorpublic ListIterator<E> listIterator()
|
listIteratorpublic ListIterator<E> listIterator()
|
listIteratorpublic ListIterator<E> listIterator(int index)
| |
listIteratorpublic ListIterator<E> listIterator(int index)
|
listIteratorpublic ListIterator<E> listIterator(int index)
|
removepublic E remove(int index)
| |
removepublic E remove(int index)
|
removepublic E remove(int index)
|
setpublic E set(int index, E element)
| |
setpublic E set(int index, E element)
|
setpublic E set(int index, E element)
|
subListpublic List<E> subList(int fromIndex, int toIndex)
| |
subListpublic List<E> subList(int fromIndex, int toIndex)
|
subListpublic List<E> subList(int fromIndex, int toIndex)
|
Resizable-array implementation of the Most ArrayDeque operations run in amortized constant time.
Exceptions include The iterators returned by this class's iterator method are
fail-fast: If the deque is modified at any time after the iterator
is created, in any way except through the iterator's own remove
method, the iterator will generally throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class and its iterator implement all of the
optional methods of the This class is a member of the Java Collections Framework.
|
ArrayDequepublic ArrayDeque()
|
ArrayDequepublic ArrayDeque(Collection<? extends E> c)
|
addpublic boolean add(E e)
|
addFirstpublic void addFirst(E e)
|
addLastpublic void addLast(E e)
|
clearpublic void clear()
|
clonepublic ArrayDeque<E> clone() |
containspublic boolean contains(Object o)
|
elementpublic E element()
|
getFirstpublic E getFirst()
|
getLastpublic E getLast()
|
isEmptypublic boolean isEmpty()
|
iteratorpublic Iterator<E> iterator() |
offerpublic boolean offer(E e)
|
offerFirstpublic boolean offerFirst(E e)
|
offerLastpublic boolean offerLast(E e)
|
peekpublic E peek()
|
peekFirstpublic E peekFirst() |
peekLastpublic E peekLast() |
pollpublic E poll()
|
pollFirstpublic E pollFirst() |
pollLastpublic E pollLast() |
poppublic E pop()
|
pushpublic void push(E e)
|
removepublic E remove()
|
removepublic boolean remove(Object o)
|
removeFirstpublic E removeFirst()
|
removeFirstOccurrencepublic boolean removeFirstOccurrence(Object o)
|
removeLastpublic E removeLast()
|
removeLastOccurrencepublic boolean removeLastOccurrence(Object o)
|
sizepublic int size()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
|
An Entry maintaining an immutable key and value. This class does not support method setValue. This class may be convenient in methods that return thread-safe snapshots of key-value mappings.
|
AbstractMap.SimpleImmutableEntrypublic AbstractMap.SimpleImmutableEntry(K key, V value)
|
AbstractMap.SimpleImmutableEntrypublic AbstractMap.SimpleImmutableEntry(Map.Entry<? extends K,? extends V> entry)
|
equalspublic boolean equals(Object o)
|
getKeypublic K getKey() |
getValuepublic V getValue() |
hashCodepublic int hashCode()
|
setValuepublic V setValue(V value)
|
toStringpublic String toString()
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
containsKeypublic boolean containsKey(Object key)
| |
containsKeypublic boolean containsKey(Object key)
|
containsKeypublic boolean containsKey(Object key)
|
containsValuepublic boolean containsValue(Object value)
| |
containsValuepublic boolean containsValue(Object value)
|
containsValuepublic boolean containsValue(Object value)
|
entrySetpublic abstract Set<Map.Entry<K,V>> entrySet()
| |
entrySetpublic abstract Set<Map.Entry<K,V>> entrySet()
|
entrySetpublic abstract Set<Map.Entry<K,V>> entrySet()
|
equalspublic boolean equals(Object o)
| |
equalspublic boolean equals(Object o)
|
equalspublic boolean equals(Object o)
|
getpublic V get(Object key)
| |
getpublic V get(Object key)
|
getpublic V get(Object key)
|
hashCodepublic int hashCode()
| |
hashCodepublic int hashCode()
|
hashCodepublic int hashCode()
|
keySetpublic Set<K> keySet()
| |
keySetpublic Set<K> keySet()
|
keySetpublic Set<K> keySet()
|
putpublic V put(K key, V value)
| |
putpublic V put(K key, V value)
|
putpublic V put(K key, V value)
|
putAllpublic void putAll(Map<? extends K,? extends V> m)
| |
putAllpublic void putAll(Map<? extends K,? extends V> t)
|
putAllpublic void putAll(Map<? extends K,? extends V> m)
|
removepublic V remove(Object key)
| |
removepublic V remove(Object key)
|
removepublic V remove(Object key)
|
valuespublic Collection<V> values()
| |
valuespublic Collection<V> values()
|
valuespublic Collection<V> values()
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
addAllpublic boolean addAll(Collection<? extends E> c)
| |
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
elementpublic E element()
| |
elementpublic E element()
|
elementpublic E element()
|
removepublic E remove()
| |
removepublic E remove()
|
removepublic E remove()
|
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list). For random access data (such as an array), AbstractList should be used in preference to this class.
This class is the opposite of the
AbstractList
class in the sense that it implements the "random access" methods (
get(int index)
,
set(int index, E To implement a list the programmer needs only to extend this class and provide implementations for the listIterator and size methods. For an unmodifiable list, the programmer need only implement the list iterator's hasNext , next , hasPrevious , previous and index methods. For a modifiable list the programmer should additionally implement the list iterator's set method. For a variable-size list the programmer should additionally implement the list iterator's remove and add methods. The programmer should generally provide a void (no argument) and collection constructor, as per the recommendation in the Collection interface specification. This class is a member of the Java Collections Framework.
| |
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list). For random access data (such as an array), AbstractList should be used in preference to this class. This class is the opposite of the AbstractList class in the sense that it implements the "random access" methods (get(int index), set(int index, Object element), set(int index, Object element), add(int index, Object element) and remove(int index)) on top of the list's list iterator, instead of the other way around. To implement a list the programmer needs only to extend this class and provide implementations for the listIterator and size methods. For an unmodifiable list, the programmer need only implement the list iterator's hasNext, next, hasPrevious, previous and index methods. For a modifiable list the programmer should additionally implement the list iterator's set method. For a variable-size list the programmer should additionally implement the list iterator's remove and add methods. The programmer should generally provide a void (no argument) and collection constructor, as per the recommendation in the Collection interface specification. This class is a member of the Java Collections Framework.
|
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list). For random access data (such as an array), AbstractList should be used in preference to this class. This class is the opposite of the AbstractList class in the sense that it implements the "random access" methods (get(int index), set(int index, E element), add(int index, E element) and remove(int index)) on top of the list's list iterator, instead of the other way around. To implement a list the programmer needs only to extend this class and provide implementations for the listIterator and size methods. For an unmodifiable list, the programmer need only implement the list iterator's hasNext, next, hasPrevious, previous and index methods. For a modifiable list the programmer should additionally implement the list iterator's set method. For a variable-size list the programmer should additionally implement the list iterator's remove and add methods. The programmer should generally provide a void (no argument) and collection constructor, as per the recommendation in the Collection interface specification. This class is a member of the Java Collections Framework.
|
addpublic void add(int index, E element)
| |
addpublic void add(int index, E element)
|
addpublic void add(int index, E element)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
| |
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
listIteratorpublic abstract ListIterator<E> listIterator(int index)
| |
listIteratorpublic abstract ListIterator<E> listIterator(int index)
|
listIteratorpublic abstract ListIterator<E> listIterator(int index)
|
removepublic E remove(int index)
| |
removepublic E remove(int index)
|
removepublic E remove(int index)
|
setpublic E set(int index, E element)
| |
setpublic E set(int index, E element)
|
setpublic E set(int index, E element)
|
hashCodepublic int hashCode()
| |
hashCodepublic int hashCode()
|
hashCodepublic int hashCode()
|
removeAllpublic boolean removeAll(Collection<?> c)
| |
removeAllpublic boolean removeAll(Collection<?> c)
|
removeAllpublic boolean removeAll(Collection<?> c)
|
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.) The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time , that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation. Each ArrayList instance has a capacity . The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized.
If multiple threads access an
ArrayList
instance concurrently, and at least one of the threads modifies the list structurally, it
must
be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the
Collections.synchronizedList
List list = Collections.synchronizedList(new ArrayList(...));
The iterators returned by this class's
iterator
and
listIterator
methods are
fail-fast
: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove
or add
methods, the iterator will throw a
ConcurrentModificationException
. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.) The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList(...)); The iterators returned by this class's iterator and listIterator methods are fail-fast: if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.) The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. Note that this implementation is not synchronized.
If multiple threads access an ArrayList instance concurrently,
and at least one of the threads modifies the list structurally, it
must be synchronized externally. (A structural modification is
any operation that adds or deletes one or more elements, or explicitly
resizes the backing array; merely setting the value of an element is not
a structural modification.) This is typically accomplished by
synchronizing on some object that naturally encapsulates the list.
If no such object exists, the list should be "wrapped" using the
List list = Collections.synchronizedList(new ArrayList(...)); The iterators returned by this class's iterator and
listIterator methods are fail-fast: if the list is
structurally modified at any time after the iterator is created, in any way
except through the iterator's own remove or add methods,
the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
| |
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
| |
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object elem)
|
containspublic boolean contains(Object o)
|
indexOfpublic int indexOf(Object o)
| |
indexOfpublic int indexOf(Object elem)
|
indexOfpublic int indexOf(Object o)
|
isEmptypublic boolean isEmpty()
| |
isEmptypublic boolean isEmpty()
|
isEmptypublic boolean isEmpty()
|
lastIndexOfpublic int lastIndexOf(Object o)
| |
lastIndexOfpublic int lastIndexOf(Object elem)
|
lastIndexOfpublic int lastIndexOf(Object o)
|
removepublic E remove(int index)
| |
removepublic E remove(int index)
|
removepublic E remove(int index)
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
removeRangeprotected void removeRange(int fromIndex, int toIndex)
| |
removeRangeprotected void removeRange(int fromIndex, int toIndex)
|
removeRangeprotected void removeRange(int fromIndex, int toIndex)
|
setpublic E set(int index, E element)
| |
setpublic E set(int index, E element)
|
setpublic E set(int index, E element)
|
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
binarySearchpublic static int binarySearch(byte[] a, byte key)
| |
binarySearchpublic static int binarySearch(byte[] a, byte key)
|
binarySearchpublic static int binarySearch(byte[] a, byte key)
|
binarySearchpublic static int binarySearch(char[] a, char key)
| |
binarySearchpublic static int binarySearch(char[] a, char key)
|
binarySearchpublic static int binarySearch(char[] a, char key)
|
binarySearchpublic static int binarySearch(double[] a, double key)
| |
binarySearchpublic static int binarySearch(double[] a, double key)
|
binarySearchpublic static int binarySearch(double[] a, double key)
|
binarySearchpublic static int binarySearch(float[] a, float key)
| |
binarySearchpublic static int binarySearch(float[] a, float key)
|
binarySearchpublic static int binarySearch(float[] a, float key)
|
binarySearchpublic static int binarySearch(int[] a, int key)
| |
binarySearchpublic static int binarySearch(int[] a, int key)
|
binarySearchpublic static int binarySearch(int[] a, int key)
|
binarySearchpublic static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
| |
binarySearchpublic static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
|
binarySearchpublic static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
|
binarySearchpublic static int binarySearch(Object[] a, Object key)
| |
binarySearchpublic static int binarySearch(Object[] a, Object key)
|
binarySearchpublic static int binarySearch(Object[] a, Object key)
|
binarySearchpublic static int binarySearch(long[] a, long key)
| |
binarySearchpublic static int binarySearch(long[] a, long key)
|
binarySearchpublic static int binarySearch(long[] a, long key)
|
binarySearchpublic static int binarySearch(short[] a, short key)
| |
binarySearchpublic static int binarySearch(short[] a, short key)
|
binarySearchpublic static int binarySearch(short[] a, short key)
|
copyOfpublic static boolean[] copyOf(boolean[] original, int newLength)
|
copyOfpublic static byte[] copyOf(byte[] original, int newLength)
|
copyOfpublic static char[] copyOf(char[] original, int newLength)
|
copyOfpublic static double[] copyOf(double[] original, int newLength)
|
copyOfpublic static float[] copyOf(float[] original, int newLength)
|
copyOfpublic static int[] copyOf(int[] original, int newLength)
|
copyOfpublic static <T> T[] copyOf(T[] original, int newLength)
|
copyOfpublic static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
|
copyOfpublic static long[] copyOf(long[] original, int newLength)
|
copyOfpublic static short[] copyOf(short[] original, int newLength)
|
copyOfRangepublic static boolean[] copyOfRange(boolean[] original, int from, int to)
|
copyOfRangepublic static byte[] copyOfRange(byte[] original, int from, int to)
|
copyOfRangepublic static char[] copyOfRange(char[] original, int from, int to)
|
copyOfRangepublic static double[] copyOfRange(double[] original, int from, int to)
|
copyOfRangepublic static float[] copyOfRange(float[] original, int from, int to)
|
copyOfRangepublic static int[] copyOfRange(int[] original, int from, int to)
|
copyOfRangepublic static <T> T[] copyOfRange(T[] original, int from, int to)
|
copyOfRangepublic static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
|
copyOfRangepublic static long[] copyOfRange(long[] original, int from, int to)
|
copyOfRangepublic static short[] copyOfRange(short[] original, int from, int to)
|
deepEqualspublic static boolean deepEquals(Object[] a1, Object[] a2)
| |
deepEqualspublic static boolean deepEquals(Object[] a1, Object[] a2)
|
deepEqualspublic static boolean deepEquals(Object[] a1, Object[] a2)
|
andNotpublic void andNot(BitSet set)
| |
andNotpublic void andNot(BitSet set)
|
andNotpublic void andNot(BitSet set)
|
clonepublic Object clone()
| |
clonepublic Object clone()
|
clonepublic Object clone() |
hashCodepublic int hashCode()
| |
hashCodepublic int hashCode()
|
hashCodepublic int hashCode()
|
asLifoQueuepublic static <T> Queue<T> asLifoQueue(Deque<T> deque) |
synchronizedSortedMappublic static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
| |
synchronizedSortedMappublic static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
|
synchronizedSortedMappublic static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
|
synchronizedSortedSetpublic static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
| |
synchronizedSortedSetpublic static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
|
synchronizedSortedSetpublic static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
|
addboolean add(E e)
| |
addboolean add(E o)
|
addboolean add(E e)
|
addAllboolean addAll(Collection<? extends E> c)
| |
addAllboolean addAll(Collection<? extends E> c)
|
addAllboolean addAll(Collection<? extends E> c)
|
clearvoid clear()
| |
clearvoid clear()
|
clearvoid clear()
|
containsAllboolean containsAll(Collection<?> c)
| |
containsAllboolean containsAll(Collection<?> c)
|
containsAllboolean containsAll(Collection<?> c)
|
equalsboolean equals(Object o)
| |
equalsboolean equals(Object o)
|
equalsboolean equals(Object o)
|
removeboolean remove(Object o)
| |
removeboolean remove(Object o)
|
removeboolean remove(Object o)
|
removeAllboolean removeAll(Collection<?> c)
| |
removeAllboolean removeAll(Collection<?> c)
|
removeAllboolean removeAll(Collection<?> c)
|
retainAllboolean retainAll(Collection<?> c)
| |
retainAllboolean retainAll(Collection<?> c)
|
retainAllboolean retainAll(Collection<?> c)
|
toArray<T> T[] toArray(T[] a)
| |
toArray<T> T[] toArray(T[] a)
|
toArray<T> T[] toArray(T[] a)
|
A comparison function, which imposes a
total ordering
on some collection of objects. Comparators can be passed to a sort method (such as
Collections.sort
or
Arrays.sort
The ordering imposed by a comparator
c
on a set of elements
S
is said to be
consistent with equals
if and only if
c.compare(e1, e2)==0 Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S . If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals .
For example, if one adds two keys
a
and
b
such that
(a.equals(b)
Note: It is generally a good idea for comparators to also implement
java.io.Serializable
, as they may be used as ordering methods in serializable data structures (like
TreeSet
,
TreeMap
). In order for the data structure to serialize successfully, the comparator (if provided) must implement
For the mathematically inclined, the
relation
that defines the
imposed ordering {(x, y) such that c.compare(x, y)The quotient for this total order is: {(x, y) such that c.compare(x, y)It follows immediately from the contract for compare that the quotient is an equivalence relation on S , and that the imposed {(x, y) such that x.equals(y)}. This interface is a member of the Java Collections Framework.
| |
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap). The ordering imposed by a Comparator c on a set of elements S is said to be consistent with equals if and only if (compare((Object)e1, (Object)e2)==0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 in S. Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit Comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals. For example, if one adds two keys a and b such that (a.equals((Object)b) && c.compare((Object)a, (Object)b) != 0) to a sorted set with comparator c, the second add operation will return false (and the size of the sorted set will not increase) because a and b are equivalent from the sorted set's perspective. Note: It is generally a good idea for comparators to implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable. For the mathematically inclined, the relation that defines the total order that a given comparator c imposes on a given set of objects S is: {(x, y) such that c.compare((Object)x, (Object)y) <= 0}.The quotient for this total order is: {(x, y) such that c.compare((Object)x, (Object)y) == 0}.It follows immediately from the contract for compare that the quotient is an equivalence relation on S, and that the natural ordering is a total order on S. When we say that the ordering imposed by c on S is consistent with equals, we mean that the quotient for the natural ordering is the equivalence relation defined by the objects' equals(Object) method(s): {(x, y) such that x.equals((Object)y)}. This interface is a member of the Java Collections Framework.
|
A comparison function, which imposes a total ordering on some
collection of objects. Comparators can be passed to a sort method (such
as The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S. Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals. For example, if one adds two keys a and b such that (a.equals(b) && c.compare(a, b) != 0) to a sorted set with comparator c, the second add operation will return false (and the size of the sorted set will not increase) because a and b are equivalent from the sorted set's perspective.
Note: It is generally a good idea for comparators to also implement
java.io.Serializable, as they may be used as ordering methods in
serializable data structures (like For the mathematically inclined, the relation that defines the imposed ordering that a given comparator c imposes on a given set of objects S is: {(x, y) such that c.compare(x, y) <= 0}.The quotient for this total order is: {(x, y) such that c.compare(x, y) == 0}.It follows immediately from the contract for compare that the quotient is an equivalence relation on S, and that the imposed ordering is a total order on S. When we say that the ordering imposed by c on S is consistent with equals, we mean that the quotient for the ordering is the equivalence relation defined by the objects' equals(Object) method(s):{(x, y) such that x.equals(y)}. This interface is a member of the Java Collections Framework.
|
compareint compare(T o1, T o2)
| |
compareint compare(T o1, T o2)
|
compareint compare(T o1, T o2)
|
equalsboolean equals(Object obj)
| |
equalsboolean equals(Object obj)
|
equalsboolean equals(Object obj)
|
A linear collection that supports element insertion and removal at both ends. The name deque is short for "double ended queue" and is usually pronounced "deck". Most Deque 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. 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 null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Deque implementations; in most implementations, insert operations cannot fail. The twelve methods described above are summarized in the following table:
This interface extends the
Deques can also be used as LIFO (Last-In-First-Out) stacks. This
interface should be used in preference to the legacy
Note that the This interface provides two methods to remove interior
elements, Unlike the While Deque implementations are not strictly required to prohibit the insertion of null elements, they are strongly encouraged to do so. Users of any Deque implementations that do allow null elements are strongly encouraged not to take advantage of the ability to insert nulls. This is so because null is used as a special return value by various methods to indicated that the deque is empty. Deque implementations generally do not define element-based versions of the equals and hashCode methods, but instead inherit the identity-based versions from class Object. This interface is a member of the Java Collections Framework.
|
addboolean add(E e)
|
addFirstvoid addFirst(E e)
|
addLastvoid addLast(E e)
|
containsboolean contains(Object o)
|
elementE element()
|
getFirstE getFirst()
|
getLastE getLast()
|
iteratorIterator<E> iterator()
|
offerboolean offer(E e)
|
offerFirstboolean offerFirst(E e)
|
offerLastboolean offerLast(E e)
|
peekE peek()
|
peekFirstE peekFirst()
|
peekLastE peekLast()
|
pollE poll()
|
pollFirstE pollFirst()
|
pollLastE pollLast()
|
popE pop()
|
pushvoid push(E e)
|
removeE remove()
|
removeboolean remove(Object o)
|
removeFirstE removeFirst()
|
removeFirstOccurrenceboolean removeFirstOccurrence(Object o)
|
removeLastE removeLast()
|
removeLastOccurrenceboolean removeLastOccurrence(Object o)
|
sizeint size()
|
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient. Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared). This is reflected in the iterators returned by the collections views ( keySet() , entrySet() , and values() ). Iterators returned by the collection views are weakly consistent : they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress. Null keys are not permitted. Attempts to insert a null key will throw NullPointerException . Attempts to test for the presence of a null key or to remove one will, however, function properly. Null values are permitted.
Like most collection implementations
EnumMap
is not synchronized. If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the enum map. If no such object exists, the map should be "wrapped" using the
Collections.synchronizedMap(java.util.Map Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...)); Implementation note: All basic operations execute in constant time. They are likely (though not guaranteed) to be faster than their HashMap counterparts. This class is a member of the Java Collections Framework.
| |
A specialized Enum maps are maintained in the natural order of their keys
(the order in which the enum constants are declared). This is reflected
in the iterators returned by the collections views ( Iterators returned by the collection views are weakly consistent:
they will never throw Null keys are not permitted. Attempts to insert a null key will
throw Like most collection implementations EnumMap is not
synchronized. If multiple threads access an enum map concurrently, and at
least one of the threads modifies the map, it should be synchronized
externally. This is typically accomplished by synchronizing on some
object that naturally encapsulates the enum map. If no such object exists,
the map should be "wrapped" using the Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap(...)); Implementation note: All basic operations execute in constant time.
They are likely (though not guaranteed) to be faster than their
This class is a member of the Java Collections Framework.
|
A specialized Enum maps are maintained in the natural order of their keys
(the order in which the enum constants are declared). This is reflected
in the iterators returned by the collections views ( Iterators returned by the collection views are weakly consistent:
they will never throw Null keys are not permitted. Attempts to insert a null key will
throw Like most collection implementations EnumMap is not
synchronized. If multiple threads access an enum map concurrently, and at
least one of the threads modifies the map, it should be synchronized
externally. This is typically accomplished by synchronizing on some
object that naturally encapsulates the enum map. If no such object exists,
the map should be "wrapped" using the Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...)); Implementation note: All basic operations execute in constant time.
They are likely (though not guaranteed) to be faster than their
This class is a member of the Java Collections Framework.
|
An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.
For example, to print all elements of a Vector<E>
for (Enumeration<E> e = v.elements(); e.hasMoreElements();) System.out.println(e.nextElement()); Methods are provided to enumerate through the elements of a vector, the keys of a hashtable, and the values in a hashtable. Enumerations are also used to specify the input streams to a SequenceInputStream . NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.
| |
An object that implements the Enumeration interface generates a
series of elements, one at a time. Successive calls to the
For example, to print all elements of a vector v: for (Enumeration e = v.elements() ; e.hasMoreElements() ;) { System.out.println(e.nextElement());
Methods are provided to enumerate through the elements of a
vector, the keys of a hashtable, and the values in a hashtable.
Enumerations are also used to specify the input streams to a
NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.
|
An object that implements the Enumeration interface generates a
series of elements, one at a time. Successive calls to the
For example, to print all elements of a Vector<E> v: for (Enumeration<E> e = v.elements(); e.hasMoreElements();) System.out.println(e.nextElement());
Methods are provided to enumerate through the elements of a
vector, the keys of a hashtable, and the values in a hashtable.
Enumerations are also used to specify the input streams to a
NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.
|
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap , two keys k1 and k2 are considered equal if and only if (k1==k2) . (In normal Map implementations (like HashMap ) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)) .) This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required. A typical use of this class is topology-preserving object graph transformations , such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects . For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged. This class provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This class provides constant-time performance for the basic operations ( get and put ), assuming the system identity hash function ( System.identityHashCode(Object) ) disperses elements properly among the buckets. This class has one tuning parameter (which affects performance but not semantics): expected maximum size . This parameter is the maximum number of key-value mappings that the map is expected to hold. Internally, this parameter is used to determine the number of buckets initially comprising the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified. If the size of the map (the number of key-value mappings) sufficiently exceeds the expected maximum size, the number of buckets is increased Increasing the number of buckets ("rehashing") may be fairly expensive, so it pays to create identity hash maps with a sufficiently large expected maximum size. On the other hand, iteration over collection views requires time proportional to the number of buckets in the hash table, so it pays not to set the expected maximum size too high if you are especially concerned with iteration performance or memory usage.
Note that this implementation is not synchronized.
If multiple threads access an identity hash Map m = Collections.synchronizedMap(new IdentityHashMap(...));
The iterators returned by the iterator
method of the collections returned by all of this class's "collection view methods" are
fail-fast
: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own
remove
method, the iterator will throw a
ConcurrentModificationException
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: fail-fast iterators should be used only to detect bugs. Implementation note: This is a simple linear-probe hash table, as described for example in texts by Sedgewick and Knuth. The array alternates holding keys and values. (This has better locality for large tables than does using separate arrays.) For many JRE implementations and operation mixes, this class will yield better performance than HashMap (which uses chaining rather than linear-probing). This class is a member of the Java Collections Framework.
| |
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).) This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required. A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged. This class provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This class provides constant-time performance for the basic
operations (get and put), assuming the system
identity hash function ( This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold. Internally, this parameter is used to determine the number of buckets initially comprising the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified. If the size of the map (the number of key-value mappings) sufficiently exceeds the expected maximum size, the number of buckets is increased Increasing the number of buckets ("rehashing") may be fairly expensive, so it pays to create identity hash maps with a sufficiently large expected maximum size. On the other hand, iteration over collection views requires time proportional to the number of buckets in the hash table, so it pays not to set the expected maximum size too high if you are especially concerned with iteration performance or memory usage. Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map: Map m = Collections.synchronizedMap(new HashMap(...)); The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. 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. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: fail-fast iterators should be used only to detect bugs. Implementation note: This is a simple linear-probe hash table,
as described for example in texts by Sedgewick and Knuth. The array
alternates holding keys and values. (This has better locality for large
tables than does using separate arrays.) For many JRE implementations
and operation mixes, this class will yield better performance than
This class is a member of the Java Collections Framework.
|
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).) This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required. A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged. This class provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This class provides constant-time performance for the basic
operations (get and put), assuming the system
identity hash function ( This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold. Internally, this parameter is used to determine the number of buckets initially comprising the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified. If the size of the map (the number of key-value mappings) sufficiently exceeds the expected maximum size, the number of buckets is increased Increasing the number of buckets ("rehashing") may be fairly expensive, so it pays to create identity hash maps with a sufficiently large expected maximum size. On the other hand, iteration over collection views requires time proportional to the number of buckets in the hash table, so it pays not to set the expected maximum size too high if you are especially concerned with iteration performance or memory usage. Note that this implementation is not synchronized.
If multiple threads access an identity hash map concurrently, and at
least one of the threads modifies the map structurally, it must
be synchronized externally. (A structural modification is any operation
that adds or deletes one or more mappings; merely changing the value
associated with a key that an instance already contains is not a
structural modification.) This is typically accomplished by
synchronizing on some object that naturally encapsulates the map.
If no such object exists, the map should be "wrapped" using the
Map m = Collections.synchronizedMap(new IdentityHashMap(...)); The iterators returned by the iterator method of the
collections returned by all of this class's "collection view
methods" are fail-fast: if the map is structurally modified
at any time after the iterator is created, in any way except
through the iterator's own remove method, the iterator
will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: fail-fast iterators should be used only to detect bugs. Implementation note: This is a simple linear-probe hash table,
as described for example in texts by Sedgewick and Knuth. The array
alternates holding keys and values. (This has better locality for large
tables than does using separate arrays.) For many JRE implementations
and operation mixes, this class will yield better performance than
This class is a member of the Java Collections Framework.
|
clearpublic void clear() | |
clearpublic void clear() |
clearpublic void clear() |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
| |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
equalspublic boolean equals(Object o)
| |
equalspublic boolean equals(Object o)
|
equalspublic boolean equals(Object o)
|
getpublic V get(Object key)
| |
getpublic V get(Object key)
|
getpublic V get(Object key)
|
hashCodepublic int hashCode()
| |
hashCodepublic int hashCode()
|
hashCodepublic int hashCode()
|
removepublic V remove(Object key)
| |
removepublic V remove(Object key)
|
removepublic V remove(Object key)
|
valuespublic Collection<V> values()
| |
valuespublic Collection<V> values()
|
valuespublic Collection<V> values()
|
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable , except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations ( get and put ), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
An instance of
HashMap
has two parameters that affect its performance:
initial capacity
and
load factor
. The
capacity
is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The
load factor
is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put ). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.
Note that this implementation is not synchronized.
If multiple threads access a hash Map m = Collections.synchronizedMap(new HashMap(...));
The iterators returned by all of this class's "collection view methods" are
fail-fast
: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own
remove
method, the iterator will throw a
ConcurrentModificationException
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is roughly doubled by calling the rehash method. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map: Map m = Collections.synchronizedMap(new HashMap(...)); The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. 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. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that this implementation is not synchronized.
If multiple threads access a hash map concurrently, and at least one of
the threads modifies the map structurally, it must be
synchronized externally. (A structural modification is any operation
that adds or deletes one or more mappings; merely changing the value
associated with a key that an instance already contains is not a
structural modification.) This is typically accomplished by
synchronizing on some object that naturally encapsulates the map.
If no such object exists, the map should be "wrapped" using the
Map m = Collections.synchronizedMap(new HashMap(...)); The iterators returned by all of this class's "collection view methods"
are fail-fast: if the map is structurally modified at any time after
the iterator is created, in any way except through the iterator's own
remove method, the iterator will throw a
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
clearpublic void clear() | |
clearpublic void clear() |
clearpublic void clear() |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
| |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
getpublic V get(Object key)
| |
getpublic V get(Object key)
|
getpublic V get(Object key)
|
keySetpublic Set<K> keySet()
| |
keySetpublic Set<K> keySet()
|
keySetpublic Set<K> keySet()
|
putpublic V put(K key, V value)
| |
putpublic V put(K key, V value)
|
putpublic V put(K key, V value)
|
valuespublic Collection<V> values()
| |
valuespublic Collection<V> values()
|
valuespublic Collection<V> values()
|
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations ( add , remove , contains and size ), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
Note that this implementation is not synchronized.
If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it
must
be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the
Collections.synchronizedSet
Set s = Collections.synchronizedSet(new HashSet(...));
The iterators returned by this class's
iterator
method are
fail-fast
: if the set is modified at any time after the iterator is created, in any way except through the iterator's own
remove
method, the Iterator throws a
ConcurrentModificationException
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. Note that this implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the HashSet instance: Set s = Collections.synchronizedSet(new HashSet(...)); The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. Note that this implementation is not synchronized.
If multiple threads access a hash set concurrently, and at least one of
the threads modifies the set, it must be synchronized externally.
This is typically accomplished by synchronizing on some object that
naturally encapsulates the set.
If no such object exists, the set should be "wrapped" using the
Set s = Collections.synchronizedSet(new HashSet(...)); The iterators returned by this class's iterator method are
fail-fast: if the set is modified at any time after the iterator is
created, in any way except through the iterator's own remove
method, the Iterator throws a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
HashSetpublic HashSet(int initialCapacity)
| |
HashSetpublic HashSet(int initialCapacity)
|
HashSetpublic HashSet(int initialCapacity)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
This class implements a hashtable, which maps keys to values. Any non- null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor . The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open : in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent. Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put ). The initial capacity controls a tradeoff between wasted space and the need for rehash operations, which are time-consuming. No rehash operations will ever occur if the initial capacity is greater than the maximum number of entries the Hashtable will contain divided by its load factor. However, setting the initial capacity too high can waste space. If many entries are to be made into a Hashtable , creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table. This example creates a hashtable of numbers. It uses the names of the numbers as keys:
Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); To retrieve a number, use the following code:
Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); } As of the Java 2 platform v1.2, this class has been retrofitted to implement Map, so that it becomes a part of Java's collection framework. Unlike the new collection implementations, Hashtable is synchronized.
The iterators returned by the iterator
method Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
This class implements a hashtable, which maps keys to values. Any
non-
To successfully store and retrieve objects from a hashtable, the
objects used as keys must implement the
An instance of Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).
The initial capacity controls a tradeoff between wasted space and the
need for
If many entries are to be made into a This example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); To retrieve a number, use the following code: Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); } As of the Java 2 platform v1.2, this class has been retrofitted to implement Map, so that it becomes a part of Java's collection framework. Unlike the new collection implementations, Hashtable is synchronized. The Iterators returned by the iterator and listIterator methods of the Collections returned by all of Hashtable's "collection view methods" are fail-fast: if the Hashtable is structurally modified at any time after the Iterator is created, in any way except through the Iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Hashtable's keys and values methods are not fail-fast. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
This class implements a hashtable, which maps keys to values. Any
non-
To successfully store and retrieve objects from a hashtable, the
objects used as keys must implement the
An instance of Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).
The initial capacity controls a tradeoff between wasted space and the
need for
If many entries are to be made into a This example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); To retrieve a number, use the following code: Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); } As of the Java 2 platform v1.2, this class has been retrofitted to implement Map, so that it becomes a part of Java's collection framework. Unlike the new collection implementations, Hashtable is synchronized. The iterators returned by the iterator method of the collections
returned by all of this class's "collection view methods" are
fail-fast: if the Hashtable is structurally modified at any time
after the iterator is created, in any way except through the iterator's own
remove method, the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
Hashtablepublic Hashtable(int initialCapacity)
| |
Hashtablepublic Hashtable(int initialCapacity)
|
Hashtablepublic Hashtable(int initialCapacity)
|
Hashtablepublic Hashtable(Map<? extends K,? extends V> t)
| |
Hashtablepublic Hashtable(Map<? extends K,? extends V> t)
|
Hashtablepublic Hashtable(Map<? extends K,? extends V> t)
|
containspublic boolean contains(Object value)
| |
containspublic boolean contains(Object value)
|
containspublic boolean contains(Object value)
|
containsValuepublic boolean containsValue(Object value)
| |
containsValuepublic boolean containsValue(Object value)
|
containsValuepublic boolean containsValue(Object value)
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
| |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
keySetpublic Set<K> keySet()
| |
keySetpublic Set<K> keySet()
|
keySetpublic Set<K> keySet()
|
valuespublic Collection<V> values()
| |
valuespublic Collection<V> values()
|
valuespublic Collection<V> values()
|
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map ( insertion-order ). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.) This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable ), without incurring the increased cost associated with TreeMap . It can be used to produce a copy of a map that has the same order as the original, regardless of the original map's implementation: void foo(Map m) { Map copy = new LinkedHashMap(m); ... }This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.) A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently ( access-order ). This kind of map is well-suited to building LRU caches. Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes). The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map's entry set iterator. No other methods generate entry accesses. In particular, operations on collection-views do not affect the order of iteration of the backing map. The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map. This class provides all of the optional Map operations, and permits null elements. Like HashMap , it provides constant-time performance for the basic operations ( add , contains and remove ), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap , due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity . A linked hash map has two parameters that affect its performance: initial capacity and load factor . They are defined precisely as for HashMap . Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap , as iteration times for this class are unaffected by capacity.
Note that this implementation is not synchronized.
If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it
must
be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the
Collections.synchronizedMap
Map m = Collections.synchronizedMap(new LinkedHashMap(...));A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification. )
The iterators returned by the
iterator
method Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.) This implementation spares its clients from the unspecified, generally
chaotic ordering provided by void foo(Map m) { Map copy = new LinkedHashMap(m); ... }This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.) A special The This class provides all of the optional Map operations, and permits null elements. Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity. A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity. Note that this implementation is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMapmethod. This is best done at creation time, to prevent accidental unsynchronized access: Map m = Collections.synchronizedMap(new LinkedHashMap(...));A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification.) The iterators returned by the iterator methods of the collections returned by all of this class's collection view methods are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.) This implementation spares its clients from the unspecified, generally
chaotic ordering provided by void foo(Map m) { Map copy = new LinkedHashMap(m); ... }This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.) A special The This class provides all of the optional Map operations, and permits null elements. Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity. A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity. Note that this implementation is not synchronized.
If multiple threads access a linked hash map concurrently, and at least
one of the threads modifies the map structurally, it must be
synchronized externally. This is typically accomplished by
synchronizing on some object that naturally encapsulates the map.
If no such object exists, the map should be "wrapped" using the
Map m = Collections.synchronizedMap(new LinkedHashMap(...));A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification.) The iterators returned by the iterator method of the collections
returned by all of this class's collection view methods are
fail-fast: if the map is structurally modified at any time after
the iterator is created, in any way except through the iterator's own
remove method, the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
clearpublic void clear() | |
clearpublic void clear() |
clearpublic void clear() |
getpublic V get(Object key)
| |
getpublic V get(Object key)
|
getpublic V get(Object key)
|
removeEldestEntryprotected boolean removeEldestEntry(Map.Entry<K,V> eldest)
| |
removeEldestEntryprotected boolean removeEldestEntry(Map.Entry<K,V> eldest)
|
removeEldestEntryprotected boolean removeEldestEntry(Map.Entry<K,V> eldest)
|
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set ( insertion-order ). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.) This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet , without incurring the increased cost associated with TreeSet . It can be used to produce a copy of a set that has the same order as the original, regardless of the original set's implementation: void foo(Set s)This technique is particularly useful if a module takes a set on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.) This class provides all of the optional Set operations, and permits null elements. Like HashSet , it provides constant-time performance for the basic operations ( add , contains and remove ), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet , due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity . A linked hash set has two parameters that affect its performance: initial capacity and load factor . They are defined precisely as for HashSet . Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet , as iteration times for this class are unaffected by capacity.
Note that this implementation is not synchronized.
If multiple threads access a linked hash set concurrently, and at least one of the threads modifies the set, it
must
be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the
Collections.synchronizedSet
Set s = Collections.synchronizedSet(new LinkedHashSet(...));
The iterators returned by this class's
iterator
method are
fail-fast
: if the set is modified at any time after the iterator is created, in any way except through the iterator's own Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.) This implementation spares its clients from the unspecified, generally
chaotic ordering provided by void foo(Set m) { Set copy = new LinkedHashSet(m); ... }This technique is particularly useful if a module takes a set on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.) This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity. A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity. Note that this implementation is not synchronized. If multiple threads access a linked hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSetmethod. This is best done at creation time, to prevent accidental unsynchronized access: Set s = Collections.synchronizedSet(new LinkedHashSet(...)); The iterators returned by the this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.) This implementation spares its clients from the unspecified, generally
chaotic ordering provided by void foo(Set s) { Set copy = new LinkedHashSet(s); ... }This technique is particularly useful if a module takes a set on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.) This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity. A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity. Note that this implementation is not synchronized.
If multiple threads access a linked hash set concurrently, and at least
one of the threads modifies the set, it must be synchronized
externally. This is typically accomplished by synchronizing on some
object that naturally encapsulates the set.
If no such object exists, the set should be "wrapped" using the
Set s = Collections.synchronizedSet(new LinkedHashSet(...)); The iterators returned by this class's iterator method are
fail-fast: if the set is modified at any time after the iterator
is created, in any way except through the iterator's own remove
method, the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
Linked list implementation of the
List
interface. Implements all optional list operations, and permits all elements (including
null
). In addition to implementing the
List
interface, the
LinkedList
class provides uniformly named methods to
get
,
remove
and
insert
an element at the beginning and end of the list. These operations allow linked lists to be used as a stack,
queue
,
The class implements the
Deque All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Note that this implementation is not synchronized.
If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it
must
be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the
Collections.synchronizedList
List list = Collections.synchronizedList(new LinkedList(...));
The iterators returned by this class's
iterator
and
listIterator
methods are
fail-fast
: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own
remove
or
add
methods, the iterator will throw a
ConcurrentModificationException
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue (deque). The class implements the Queue interface, providing first-in-first-out queue operations for add, poll, etc. Other stack and deque operations could be easily recast in terms of the standard list operations. They're included here primarily for convenience, though they may run slightly faster than the equivalent List operations. All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index. Note that this implementation is not synchronized. If multiple threads access a list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list: List list = Collections.synchronizedList(new LinkedList(...)); The iterators returned by the this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue. The class implements the Deque interface, providing first-in-first-out queue operations for add, poll, along with other stack and deque operations. All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Note that this implementation is not synchronized.
If multiple threads access a linked list concurrently, and at least
one of the threads modifies the list structurally, it must be
synchronized externally. (A structural modification is any operation
that adds or deletes one or more elements; merely setting the value of
an element is not a structural modification.) This is typically
accomplished by synchronizing on some object that naturally
encapsulates the list.
If no such object exists, the list should be "wrapped" using the
List list = Collections.synchronizedList(new LinkedList(...)); The iterators returned by this class's iterator and
listIterator methods are fail-fast: if the list is
structurally modified at any time after the iterator is created, in
any way except through the Iterator's own remove or
add methods, the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
| |
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(int index, Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
| |
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
|
addFirstpublic void addFirst(E e) | |
addFirstpublic void addFirst(E o)
|
addFirstpublic void addFirst(E e) |
addLastpublic void addLast(E e)
| |
addLastpublic void addLast(E o)
|
addLastpublic void addLast(E e) |
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
elementpublic E element() | |
elementpublic E element()
|
elementpublic E element() |
indexOfpublic int indexOf(Object o)
| |
indexOfpublic int indexOf(Object o)
|
indexOfpublic int indexOf(Object o)
|
lastIndexOfpublic int lastIndexOf(Object o)
| |
lastIndexOfpublic int lastIndexOf(Object o)
|
lastIndexOfpublic int lastIndexOf(Object o)
|
offerpublic boolean offer(E e) | |
offerpublic boolean offer(E o) |
offerpublic boolean offer(E e) |
offerFirstpublic boolean offerFirst(E e)
|
offerLastpublic boolean offerLast(E e)
|
peekpublic E peek() | |
peekpublic E peek() |
peekpublic E peek() |
peekFirstpublic E peekFirst() |
peekLastpublic E peekLast() |
pollpublic E poll() | |
pollpublic E poll() |
pollpublic E poll() |
pollFirstpublic E pollFirst() |
pollLastpublic E pollLast() |
poppublic E pop()
|
pushpublic void push(E e)
|
removepublic E remove() | |
removepublic E remove()
|
removepublic E remove() |
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
removeFirstOccurrencepublic boolean removeFirstOccurrence(Object o)
|
removeLastOccurrencepublic boolean removeLastOccurrence(Object o)
|
sizepublic int size() | |
sizepublic int size()
|
sizepublic int size() |
toArraypublic Object[] toArray()
| |
toArraypublic Object[] toArray()
|
toArraypublic Object[] toArray()
|
toArraypublic <T> T[] toArray(T[] a)
| |
toArraypublic <T> T[] toArray(T[] a)
|
toArraypublic <T> T[] toArray(T[] a)
|
An ordered collection (also known as a sequence ). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare. The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience. The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation. The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list. The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the
equals
and
hashCode
methods are no longer well defined on Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. This interface is a member of the Java Collections Framework.
| |
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare. The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience. The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation. The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list. The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a list. Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. This interface is a member of the Java Collections Framework.
|
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare. The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience. The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation. The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list. The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list. Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. This interface is a member of the Java Collections Framework.
|
addboolean add(E e)
| |
addboolean add(E o)
|
addboolean add(E e)
|
addAllboolean addAll(int index, Collection<? extends E> c)
| |
addAllboolean addAll(int index, Collection<? extends E> c)
|
addAllboolean addAll(int index, Collection<? extends E> c)
|
addAllboolean addAll(Collection<? extends E> c)
| |
addAllboolean addAll(Collection<? extends E> c)
|
addAllboolean addAll(Collection<? extends E> c)
|
clearvoid clear()
| |
clearvoid clear()
|
clearvoid clear()
|
containsAllboolean containsAll(Collection<?> c)
| |
containsAllboolean containsAll(Collection<?> c)
|
containsAllboolean containsAll(Collection<?> c)
|
hashCodeint hashCode()
| |
hashCodeint hashCode()
|
hashCodeint hashCode()
|
indexOfint indexOf(Object o)
| |
indexOfint indexOf(Object o)
|
indexOfint indexOf(Object o)
|
lastIndexOfint lastIndexOf(Object o)
| |
lastIndexOfint lastIndexOf(Object o)
|
lastIndexOfint lastIndexOf(Object o)
|
listIteratorListIterator<E> listIterator(int index)
| |
listIteratorListIterator<E> listIterator(int index)
|
listIteratorListIterator<E> listIterator(int index)
|
removeboolean remove(Object o)
| |
removeboolean remove(Object o)
|
removeboolean remove(Object o)
|
removeAllboolean removeAll(Collection<?> c)
| |
removeAllboolean removeAll(Collection<?> c)
|
removeAllboolean removeAll(Collection<?> c)
|
retainAllboolean retainAll(Collection<?> c)
| |
retainAllboolean retainAll(Collection<?> c)
|
retainAllboolean retainAll(Collection<?> c)
|
toArrayObject[] toArray()
| |
toArrayObject[] toArray()
|
toArrayObject[] toArray()
|
toArray<T> T[] toArray(T[] a)
| |
toArray<T> T[] toArray(T[] a)
|
toArray<T> T[] toArray(T[] a)
|
equalsboolean equals(Object o)
| |
equalsboolean equals(Object o)
|
equalsboolean equals(Object o)
|
setValueV setValue(V value)
| |
setValueV setValue(V value)
|
setValueV setValue(V value)
|
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface. The Map interface provides three collection views , which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals
comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals
and hashCode
methods are no longer well defined on All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map , which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply. The "destructive" methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be "superimposed" is empty. Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. This interface is a member of the Java Collections Framework. Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object key) method says: "returns true if and only if this map contain a mapping for a key k such that (key==null ? k==null : key.equals(k)) ." This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k . Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.
| |
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not. Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map. All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply. The "destructive" methods contained in this interface, that is, the
methods that modify the map on which they operate, are specified to throw
UnsupportedOperationException if this map does not support the
operation. If this is the case, these methods may, but are not required
to, throw an UnsupportedOperationException if the invocation would
have no effect on the map. For example, invoking the Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. This interface is a member of the Java Collections Framework. Many methods in Collections Framework interfaces are defined
in terms of the
|
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not. Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map. All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply. The "destructive" methods contained in this interface, that is, the
methods that modify the map on which they operate, are specified to throw
UnsupportedOperationException if this map does not support the
operation. If this is the case, these methods may, but are not required
to, throw an UnsupportedOperationException if the invocation would
have no effect on the map. For example, invoking the Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. This interface is a member of the Java Collections Framework. Many methods in Collections Framework interfaces are defined
in terms of the
|
clearvoid clear()
| |
clearvoid clear()
|
clearvoid clear()
|
entrySetSet<Map.Entry<K,V>> entrySet()
| |
entrySetSet<Map.Entry<K,V>> entrySet()
|
entrySetSet<Map.Entry<K,V>> entrySet()
|
getV get(Object key)
| |
getV get(Object key)
|
getV get(Object key)
|
hashCodeint hashCode()
| |
hashCodeint hashCode()
|
hashCodeint hashCode()
|
keySetSet<K> keySet()
| |
keySetSet<K> keySet()
|
keySetSet<K> keySet()
|
putV put(K key, V value)
| |
putV put(K key, V value)
|
putV put(K key, V value)
|
putAllvoid putAll(Map<? extends K,? extends V> m)
| |
putAllvoid putAll(Map<? extends K,? extends V> t)
|
putAllvoid putAll(Map<? extends K,? extends V> m)
|
removeV remove(Object key)
| |
removeV remove(Object key)
|
removeV remove(Object key)
|
valuesCollection<V> values()
| |
valuesCollection<V> values()
|
valuesCollection<V> values()
|
A collection designed for holding elements prior to processing. Besides basic 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 null or false , depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.
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 head of the queue is that element which would be removed by a call to remove() or poll() . In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties. The offer method inserts an element if possible, otherwise returning false . This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues. The remove() and 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 remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null . The element() and peek() methods return, but do not remove, the head of the queue. The Queue interface does not define the blocking queue methods , which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the BlockingQueue interface, which extends this interface. Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList , do not prohibit insertion of null . Even in the implementations that permit it, null should not be inserted into a Queue , as null is also used as a special return value by the poll method to indicate that the queue contains no elements. Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object , because element-based equality is not always well-defined for queues with the same elements but different ordering properties. This interface is a member of the Java Collections Framework.
| |||||||||||||
A collection designed for holding elements prior to processing.
Besides basic 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 head of the queue is that
element which would be removed by a call to The The The The Queue interface does not define the blocking queue
methods, which are common in concurrent programming. These methods,
which wait for elements to appear or for space to become available, are
defined in the Queue implementations generally do not allow insertion
of null elements, although some implementations, such as
Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object, because element-based equality is not always well-defined for queues with the same elements but different ordering properties. This interface is a member of the Java Collections Framework.
|
A collection designed for holding elements prior to processing.
Besides basic
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 head of the queue is that
element which would be removed by a call to The The The The Queue interface does not define the blocking queue
methods, which are common in concurrent programming. These methods,
which wait for elements to appear or for space to become available, are
defined in the Queue implementations generally do not allow insertion
of null elements, although some implementations, such as
Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object, because element-based equality is not always well-defined for queues with the same elements but different ordering properties. This interface is a member of the Java Collections Framework.
|
addboolean add(E e)
|
elementE element()
| |
elementE element()
|
elementE element()
|
offerboolean offer(E e)
| |
offerboolean offer(E o)
|
offerboolean offer(E e)
|
peekE peek()
| |
peekE peek()
|
peekE peek()
|
pollE poll()
| |
pollE poll()
|
pollE poll()
|
removeE remove()
| |
removeE remove()
|
removeE remove()
|
A A NavigableMap may be viewed and traversed in either ascending or descending key order. The Map methods keySet and entrySet return ascending views, and the additional methods descendingKeySet and descendingEntrySet return descending views. The performance of ascending traversals is likely to be faster than descending traversals. Notice that it is possible to perform subrange traversals in either direction using navigableSubMap. Methods navigableSubMap, navigableHeadMap, and navigableTailMap differ from the similarly named SortedMap methods only in their declared return types. Submaps of any NavigableMap must implement the NavigableMap interface. This interface additionally defines methods firstEntry, pollFirstEntry, lastEntry, and pollLastEntry that return and/or remove the least and greatest mappings, if any exist, else returning null. Implementations of entry-returning methods are expected to return Map.Entry pairs representing snapshots of mappings at the time they were produced, and thus generally do not support the optional Entry.setValue method. Note however that it is possible to change mappings in the associated map using method put. This interface is a member of the Java Collections Framework.
|
ceilingEntryMap.Entry<K,V> ceilingEntry(K key)
|
ceilingKeyK ceilingKey(K key)
|
descendingEntrySetSet<Map.Entry<K,V>> descendingEntrySet()
|
descendingKeySetSet<K> descendingKeySet()
|
firstEntryMap.Entry<K,V> firstEntry()
|
floorEntryMap.Entry<K,V> floorEntry(K key)
|
floorKeyK floorKey(K key)
|
higherEntryMap.Entry<K,V> higherEntry(K key)
|
higherKeyK higherKey(K key)
|
lastEntryMap.Entry<K,V> lastEntry()
|
lowerEntryMap.Entry<K,V> lowerEntry(K key)
|
lowerKeyK lowerKey(K key)
|
navigableHeadMapNavigableMap<K,V> navigableHeadMap(K toKey)
|
navigableSubMapNavigableMap<K,V> navigableSubMap(K fromKey, K toKey)
|
navigableTailMapNavigableMap<K,V> navigableTailMap(K fromKey)
|
pollFirstEntryMap.Entry<K,V> pollFirstEntry()
|
pollLastEntryMap.Entry<K,V> pollLastEntry()
|
A The return values of navigation methods may be ambiguous in
implementations that permit null elements. However, even
in this case the result can be disambiguated by checking
contains(null). To avoid such issues, implementations of
this interface are encouraged to not permit insertion of
null elements. (Note that sorted sets of This interface is a member of the Java Collections Framework.
|
ceilingE ceiling(E e)
|
descendingIteratorIterator<E> descendingIterator()
|
floorE floor(E e)
|
higherE higher(E e)
|
iteratorIterator<E> iterator() |
lowerE lower(E e)
|
navigableHeadSetNavigableSet<E> navigableHeadSet(E toElement)
|
navigableSubSetNavigableSet<E> navigableSubSet(E fromElement, E toElement)
|
navigableTailSetNavigableSet<E> navigableTailSet(E fromElement)
|
pollFirstE pollFirst()
|
pollLastE pollLast()
|
An unbounded priority
queue
based on a priority heap. The elements of the priority queue are ordered according to their
natural ordering The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll , remove , peek , and element access the element at the head of the queue. A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()) . Note that this implementation is not synchronized. Multiple threads should not access a PriorityQueue instance concurrently if any of the threads modifies the list structurally. Instead, use the thread-safe PriorityBlockingQueue class. Implementation note: this implementation provides O(log(n)) time for the insertion methods ( offer , poll , remove() and add ) methods; linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods ( peek , element , and size ). This class is a member of the Java Collections Framework.
| |
An unbounded priority queue based on a priority
heap. This queue orders elements according to an order specified
at construction time, which is specified either according to their
natural order (see The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue. A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified. This class and its iterator implement all of the
optional methods of the Note that this implementation is not synchronized.
Multiple threads should not access a PriorityQueue
instance concurrently if any of the threads modifies the list
structurally. Instead, use the thread-safe Implementation note: this implementation provides O(log(n)) time for the insertion methods (offer, poll, remove() and add) methods; linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size). This class is a member of the Java Collections Framework.
|
An unbounded priority queue based on a priority
heap. The elements of the priority queue are ordered according to
their natural ordering, or by a The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue. A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified. This class and its iterator implement all of the
optional methods of the Note that this implementation is not synchronized.
Multiple threads should not access a PriorityQueue
instance concurrently if any of the threads modifies the list
structurally. Instead, use the thread-safe Implementation note: this implementation provides O(log(n)) time for the insertion methods (offer, poll, remove() and add) methods; linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods (peek, element, and size). This class is a member of the Java Collections Framework.
|
PriorityQueuepublic PriorityQueue()
| |
PriorityQueuepublic PriorityQueue()
|
PriorityQueuepublic PriorityQueue()
|
PriorityQueuepublic PriorityQueue(int initialCapacity)
| |
PriorityQueuepublic PriorityQueue(int initialCapacity)
|
PriorityQueuepublic PriorityQueue(int initialCapacity)
|
PriorityQueuepublic PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
| |
PriorityQueuepublic PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
|
PriorityQueuepublic PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
|
PriorityQueuepublic PriorityQueue(Collection<? extends E> c)
| |
PriorityQueuepublic PriorityQueue(Collection<? extends E> c)
|
PriorityQueuepublic PriorityQueue(Collection<? extends E> c)
|
PriorityQueuepublic PriorityQueue(PriorityQueue<? extends E> c)
| |
PriorityQueuepublic PriorityQueue(PriorityQueue<? extends E> c)
|
PriorityQueuepublic PriorityQueue(PriorityQueue<? extends E> c)
|
PriorityQueuepublic PriorityQueue(SortedSet<? extends E> c)
| |
PriorityQueuepublic PriorityQueue(SortedSet<? extends E> c)
|
PriorityQueuepublic PriorityQueue(SortedSet<? extends E> c)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
comparatorpublic Comparator<? super E> comparator()
| |
comparatorpublic Comparator<? super E> comparator()
|
comparatorpublic Comparator<? super E> comparator()
|
containspublic boolean contains(Object o)
|
offerpublic boolean offer(E e)
| |
offerpublic boolean offer(E o)
|
offerpublic boolean offer(E e)
|
peekpublic E peek() | |
peekpublic E peek() |
peekpublic E peek() |
pollpublic E poll() | |
pollpublic E poll() |
pollpublic E poll() |
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
sizepublic int size()
| |
sizepublic int size()
|
sizepublic int size()
|
addboolean add(E e)
| |
addboolean add(E o)
|
addboolean add(E e)
|
addAllboolean addAll(Collection<? extends E> c)
| |
addAllboolean addAll(Collection<? extends E> c)
|
addAllboolean addAll(Collection<? extends E> c)
|
clearvoid clear()
| |
clearvoid clear()
|
clearvoid clear()
|
containsAllboolean containsAll(Collection<?> c)
| |
containsAllboolean containsAll(Collection<?> c)
|
containsAllboolean containsAll(Collection<?> c)
|
hashCodeint hashCode()
| |
hashCodeint hashCode()
|
hashCodeint hashCode()
|
removeAllboolean removeAll(Collection<?> c)
| |
removeAllboolean removeAll(Collection<?> c)
|
removeAllboolean removeAll(Collection<?> c)
|
retainAllboolean retainAll(Collection<?> c)
| |
retainAllboolean retainAll(Collection<?> c)
|
retainAllboolean retainAll(Collection<?> c)
|
toArrayObject[] toArray()
| |
toArrayObject[] toArray()
|
toArrayObject[] toArray()
|
toArray<T> T[] toArray(T[] a)
| |
toArray<T> T[] toArray(T[] a)
|
toArray<T> T[] toArray(T[] a)
|
A
Map
that further provides a
All keys inserted into a sorted map must implement the
Comparable
interface (or be accepted by the specified comparator). Furthermore, all such keys must be
mutually comparable
:
k1.compareTo(k2)
(or
comparator.compare(k1, k2)
) must not throw a
ClassCastException
for any keys Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals .) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare ) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface. All general-purpose sorted map implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys. 2) A constructor with a single argument of type Comparator , which creates an empty sorted map sorted according to the specified comparator. 3) A constructor with a single argument of type Map , which creates a new map with the same key-value mappings as its argument, sorted according to the keys' natural ordering. 4) A constructor with a single argument of type SortedMap , which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map. There is no way to enforce this recommendation, as interfaces cannot contain constructors.
Note: several methods return submaps with restricted key ranges. Such ranges are SortedMap<String, V> sub = m.subMap(low, high+"\0");A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high , exclusive: SortedMap<String, V> sub = m.subMap(low+"\0", high); This interface is a member of the Java Collections Framework.
| |
A map that further guarantees that it will be in ascending key order, sorted according to the natural ordering of its keys (see the Comparable interface), or by a comparator provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of the SortedSet interface.) All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1, k2)) must not throw a ClassCastException for any elements k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException. Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface. All general-purpose sorted map implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural order of its keys. 2) A constructor with a single argument of type Comparator, which creates an empty sorted map sorted according to the specified comparator. 3) A constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument, sorted according to the keys' natural ordering. 4) A constructor with a single argument of type sorted map, which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but the JDK implementation (TreeMap) complies. This interface is a member of the Java Collections Framework.
|
A All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1, k2)) must not throw a ClassCastException for any keys k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException. Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface. All general-purpose sorted map implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys. 2) A constructor with a single argument of type Comparator, which creates an empty sorted map sorted according to the specified comparator. 3) A constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument, sorted according to the keys' natural ordering. 4) A constructor with a single argument of type SortedMap, which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map. There is no way to enforce this recommendation, as interfaces cannot contain constructors. Note: several methods return submaps with restricted key ranges. Such ranges are half-open, that is, they include their low endpoint but not their high endpoint (where applicable). If you need a closed range (which includes both endpoints), and the key type allows for calculation of the successor of a given key, merely request the subrange from lowEndpoint to successor(highEndpoint). For example, suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, inclusive: SortedMap<String, V> sub = m.subMap(low, high+"\0");A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, exclusive: SortedMap<String, V> sub = m.subMap(low+"\0", high); This interface is a member of the Java Collections Framework.
|
comparatorComparator<? super K> comparator()
| |
comparatorComparator<? super K> comparator()
|
comparatorComparator<? super K> comparator()
|
entrySetSet<Map.Entry<K,V>> entrySet()
|
firstKeyK firstKey()
| |
firstKeyK firstKey()
|
firstKeyK firstKey()
|
headMapSortedMap<K,V> headMap(K toKey)
| |
headMapSortedMap<K,V> headMap(K toKey)
|
headMapSortedMap<K,V> headMap(K toKey)
|
keySetSet<K> keySet()
|
lastKeyK lastKey()
| |
lastKeyK lastKey()
|
lastKeyK lastKey()
|
subMapSortedMap<K,V> subMap(K fromKey, K toKey)
| |
subMapSortedMap<K,V> subMap(K fromKey, K toKey)
|
subMapSortedMap<K,V> subMap(K fromKey, K toKey)
|
tailMapSortedMap<K,V> tailMap(K fromKey)
| |
tailMapSortedMap<K,V> tailMap(K fromKey)
|
tailMapSortedMap<K,V> tailMap(K fromKey)
|
valuesCollection<V> values()
|
A
Set
that further provides a
All elements inserted into a Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals .) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare ) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. All general-purpose sorted set implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor, which creates an empty sorted set sorted according to the natural ordering of its elements. 2) A constructor with a single argument of type Comparator , which creates an empty sorted set sorted according to the specified comparator. 3) A constructor with a single argument of type Collection , which creates a new sorted set with the same elements as its argument, sorted according to the natural ordering of the elements. 4) A constructor with a single argument of type SortedSet , which creates a new sorted set with the same elements and the same ordering as the input sorted set. There is no way to enforce this recommendation, as interfaces cannot contain constructors.
Note: several methods return subsets with restricted ranges. Such ranges are SortedSet<String> sub = s.subSet(low, high+"\0");}A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the Strings in s from low to high , exclusive: SortedSet<String> sub = s.subSet(low+"\0", high);} This interface is a member of the Java Collections Framework.
| |
A set that further guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements (see Comparable), or by a Comparator provided at sorted set creation time. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue of SortedMap.) All elements inserted into an sorted set must implement the Comparable interface (or be accepted by the specified Comparator). Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1, e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException. Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. All general-purpose sorted set implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor, which creates an empty sorted set sorted according to the natural order of its elements. 2) A constructor with a single argument of type Comparator, which creates an empty sorted set sorted according to the specified comparator. 3) A constructor with a single argument of type Collection, which creates a new sorted set with the same elements as its argument, sorted according to the elements' natural ordering. 4) A constructor with a single argument of type SortedSet, which creates a new sorted set with the same elements and the same ordering as the input sorted set. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but the JDK implementation (the TreeSet class) complies. This interface is a member of the Java Collections Framework.
|
A All elements inserted into a sorted set must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1, e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException. Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. All general-purpose sorted set implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor, which creates an empty sorted set sorted according to the natural ordering of its elements. 2) A constructor with a single argument of type Comparator, which creates an empty sorted set sorted according to the specified comparator. 3) A constructor with a single argument of type Collection, which creates a new sorted set with the same elements as its argument, sorted according to the natural ordering of the elements. 4) A constructor with a single argument of type SortedSet, which creates a new sorted set with the same elements and the same ordering as the input sorted set. There is no way to enforce this recommendation, as interfaces cannot contain constructors. Note: several methods return subsets with restricted ranges. Such ranges are half-open, that is, they include their low endpoint but not their high endpoint (where applicable). If you need a closed range (which includes both endpoints), and the element type allows for calculation of the successor of a given value, merely request the subrange from lowEndpoint to successor(highEndpoint). For example, suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s from low to high, inclusive: SortedSet<String> sub = s.subSet(low, high+"\0");}A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the Strings in s from low to high, exclusive: SortedSet<String> sub = s.subSet(low+"\0", high);} This interface is a member of the Java Collections Framework.
|
comparatorComparator<? super E> comparator()
| |
comparatorComparator<? super E> comparator()
|
comparatorComparator<? super E> comparator()
|
firstE first()
| |
firstE first()
|
firstE first()
|
headSetSortedSet<E> headSet(E toElement)
| |
headSetSortedSet<E> headSet(E toElement)
|
headSetSortedSet<E> headSet(E toElement)
|
lastE last()
| |
lastE last()
|
lastE last()
|
subSetSortedSet<E> subSet(E fromElement, E toElement)
| |
subSetSortedSet<E> subSet(E fromElement, E toElement)
|
subSetSortedSet<E> subSet(E fromElement, E toElement)
|
tailSetSortedSet<E> tailSet(E fromElement)
| |
tailSetSortedSet<E> tailSet(E fromElement)
|
tailSetSortedSet<E> tailSet(E fromElement)
|
A hashtable-based
Map
implementation with
weak keys
. An entry in a
WeakHashMap
will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class, and has the same efficiency parameters of initial capacity and load factor .
Like most collection classes, this class is not synchronized. A synchronized
WeakHashMap
may be constructed using the
Collections.synchronizedMap
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances. With such recreatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing.
The behavior of the
WeakHashMap
class depends in part upon the actions of the garbage collector, so several familiar (though not required)
Map
invariants do not hold for this class. Because the garbage collector may discard keys at any time, a
WeakHashMap
may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a
WeakHashMap
instance and invoke none of its mutator methods, it is possible for the
size
method to return smaller values over time, for the
isEmpty
method to return
false
and then
true
, for the
containsKey
method to return
true
and later
false
for a given key, for the
get
method to return a value for a given key but later return
null
, for the
put
method to return
null
and the
remove
method to return
false
for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector. Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object. One way to deal with this is to wrap values themselves within WeakReferences before inserting, as in: m.put(key, new WeakReference(value)) , and then unwrapping upon each get .
The iterators returned by the iterator
method of the collections returned by all of this class's "collection view methods" are
fail-fast
: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own
remove
method, the iterator will throw a
ConcurrentModificationException
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations. Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class, and has the same efficiency parameters of initial capacity and load factor. Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances. With such recreatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing. The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value set, and the entry set to yield successively smaller numbers of elements. Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector. Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object. One way to deal with this is to wrap values themselves within WeakReferences before inserting, as in: m.put(key, new WeakReference(value)), and then unwrapping upon each get. The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. 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. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations. Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class, and has the same efficiency parameters of initial capacity and load factor. Like most collection classes, this class is not synchronized.
A synchronized WeakHashMap may be constructed using the
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances. With such recreatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing. The behavior of the WeakHashMap class depends in part upon the actions of the garbage collector, so several familiar (though not required) Map invariants do not hold for this class. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements. Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector. Implementation note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself; that is, a value object may strongly refer to some other key object whose associated value object, in turn, strongly refers to the key of the first value object. One way to deal with this is to wrap values themselves within WeakReferences before inserting, as in: m.put(key, new WeakReference(value)), and then unwrapping upon each get. The iterators returned by the iterator method of the collections
returned by all of this class's "collection view methods" are
fail-fast: if the map is structurally modified at any time after the
iterator is created, in any way except through the iterator's own
remove method, the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
WeakHashMappublic WeakHashMap(int initialCapacity)
| |
WeakHashMappublic WeakHashMap(int initialCapacity)
|
WeakHashMappublic WeakHashMap(int initialCapacity)
|
WeakHashMappublic WeakHashMap(Map<? extends K,? extends V> m)
| |
WeakHashMappublic WeakHashMap(Map<? extends K,? extends V> t)
|
WeakHashMappublic WeakHashMap(Map<? extends K,? extends V> m)
|
clearpublic void clear() | |
clearpublic void clear() |
clearpublic void clear() |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
| |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
getpublic V get(Object key)
| |
getpublic V get(Object key)
|
getpublic V get(Object key)
|
keySetpublic Set<K> keySet()
| |
keySetpublic Set<K> keySet()
|
keySetpublic Set<K> keySet()
|
putpublic V put(K key, V value)
| |
putpublic V put(K key, V value)
|
putpublic V put(K key, V value)
|
removepublic V remove(Object key)
| |
removepublic V remove(Object key)
|
removepublic V remove(Object key)
|
valuespublic Collection<V> values()
| |
valuespublic Collection<V> values()
|
valuespublic Collection<V> values()
|
A Red-Black tree based
NavigableMap
implementation. The map is sorted according to the
natural ordering
of its keys, or by a
Comparator
provided at map creation time, depending on which constructor is used. This implementation provides guaranteed log(n) time cost for the containsKey , get , put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms . Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals .) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare ) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
Note that this implementation is not synchronized.
If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it
must
be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the
Collections.synchronizedSortedMap
SortedMap The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast : if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
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
All
This class is a member of the Java Collections Framework.
| |
Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used. This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms. Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface. Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map: Map m = Collections.synchronizedMap(new TreeMap(...)); The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
A Red-Black tree based This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms. Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface. Note that this implementation is not synchronized.
If multiple threads access a map concurrently, and at least one of the
threads modifies the map structurally, it must be synchronized
externally. (A structural modification is any operation that adds or
deletes one or more mappings; merely changing the value associated
with an existing key is not a structural modification.) This is
typically accomplished by synchronizing on some object that naturally
encapsulates the map.
If no such object exists, the map should be "wrapped" using the
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...)); The iterators returned by the iterator method of the collections
returned by all of this class's "collection view methods" are
fail-fast: if the map is structurally modified at any time after the
iterator is created, in any way except through the iterator's own
remove method, the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. All Map.Entry pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. (Note however that it is possible to change mappings in the associated map using put.) This class is a member of the Java Collections Framework.
|
TreeMappublic TreeMap()
| |
TreeMappublic TreeMap()
|
TreeMappublic TreeMap()
|
TreeMappublic TreeMap(Comparator<? super K> comparator)
| |
TreeMappublic TreeMap(Comparator<? super K> c)
|
TreeMappublic TreeMap(Comparator<? super K> comparator)
|
TreeMappublic TreeMap(Map<? extends K,? extends V> m)
| |
TreeMappublic TreeMap(Map<? extends K,? extends V> m)
|
TreeMappublic TreeMap(Map<? extends K,? extends V> m)
|
TreeMappublic TreeMap(SortedMap<K,? extends V> m)
| |
TreeMappublic TreeMap(SortedMap<K,? extends V> m)
|
TreeMappublic TreeMap(SortedMap<K,? extends V> m)
|
ceilingEntrypublic Map.Entry<K,V> ceilingEntry(K key)
|
ceilingKeypublic K ceilingKey(K key)
|
clearpublic void clear() | |
clearpublic void clear() |
clearpublic void clear() |
comparatorpublic Comparator<? super K> comparator()
| |
comparatorpublic Comparator<? super K> comparator()
|
comparatorpublic Comparator<? super K> comparator()
|
containsKeypublic boolean containsKey(Object key)
| |
containsKeypublic boolean containsKey(Object key)
|
containsKeypublic boolean containsKey(Object key)
|
containsValuepublic boolean containsValue(Object value)
| |
containsValuepublic boolean containsValue(Object value)
|
containsValuepublic boolean containsValue(Object value)
|
descendingEntrySetpublic Set<Map.Entry<K,V>> descendingEntrySet()
|
descendingKeySetpublic Set<K> descendingKeySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
| |
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
entrySetpublic Set<Map.Entry<K,V>> entrySet()
|
firstEntrypublic Map.Entry<K,V> firstEntry()
|
firstKeypublic K firstKey() | |
firstKeypublic K firstKey()
|
firstKeypublic K firstKey() |
floorEntrypublic Map.Entry<K,V> floorEntry(K key)
|
floorKeypublic K floorKey(K key)
|
getpublic V get(Object key)
| |
getpublic V get(Object key)
|
getpublic V get(Object key)
|
headMappublic SortedMap<K,V> headMap(K toKey)
| |
headMappublic SortedMap<K,V> headMap(K toKey)
|
headMappublic SortedMap<K,V> headMap(K toKey)
|
higherEntrypublic Map.Entry<K,V> higherEntry(K key)
|
higherKeypublic K higherKey(K key)
|
keySetpublic Set<K> keySet()
| |
keySetpublic Set<K> keySet()
|
keySetpublic Set<K> keySet()
|
lastEntrypublic Map.Entry<K,V> lastEntry()
|
lastKeypublic K lastKey() | |
lastKeypublic K lastKey()
|
lastKeypublic K lastKey() |
lowerEntrypublic Map.Entry<K,V> lowerEntry(K key)
|
lowerKeypublic K lowerKey(K key)
|
navigableHeadMappublic NavigableMap<K,V> navigableHeadMap(K toKey)
|
navigableSubMappublic NavigableMap<K,V> navigableSubMap(K fromKey, K toKey)
|
navigableTailMappublic NavigableMap<K,V> navigableTailMap(K fromKey)
|
pollFirstEntrypublic Map.Entry<K,V> pollFirstEntry()
|
pollLastEntrypublic Map.Entry<K,V> pollLastEntry()
|
putpublic V put(K key, V value)
| |
putpublic V put(K key, V value)
|
putpublic V put(K key, V value)
|
putAllpublic void putAll(Map<? extends K,? extends V> map)
| |
putAllpublic void putAll(Map<? extends K,? extends V> map)
|
putAllpublic void putAll(Map<? extends K,? extends V> map)
|
removepublic V remove(Object key)
| |
removepublic V remove(Object key)
|
removepublic V remove(Object key)
|
subMappublic SortedMap<K,V> subMap(K fromKey, K toKey)
| |
subMappublic SortedMap<K,V> subMap(K fromKey, K toKey)
|
subMappublic SortedMap<K,V> subMap(K fromKey, K toKey)
|
tailMappublic SortedMap<K,V> tailMap(K fromKey)
| |
tailMappublic SortedMap<K,V> tailMap(K fromKey)
|
tailMappublic SortedMap<K,V> tailMap(K fromKey)
|
valuespublic Collection<V> values()
| |
valuespublic Collection<V> values()
|
valuespublic Collection<V> values()
|
A
NavigableSet
implementation based on a
TreeMap
. The elements are ordered using their
natural ordering
, or by a
Comparator
provided at set creation time, depending on which constructor is used. This implementation provides guaranteed log(n) time cost for the basic operations ( add , remove and contains ).
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be
consistent with equals
if it is to correctly implement the
Set
interface. (See
Comparable
or
Comparator
for a precise definition of
consistent with equals
.) This is so because the
Set
interface is defined in terms of the
equals
operation, but a
TreeSet
instance performs all element
Note that this implementation is not synchronized.
If multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it
must
be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the
Collections.synchronizedSortedSet
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
The iterators returned by this class's
iterator
method are
fail-fast
: if the set is modified at any time after the iterator is created, in any way except through the iterator's own
remove
method, the iterator will throw a
ConcurrentModificationException
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
| |
This class implements the Set interface, backed by a TreeMap instance. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used. This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. Note that this implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...)); The Iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
A This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. Note that this implementation is not synchronized.
If multiple threads access a tree set concurrently, and at least one
of the threads modifies the set, it must be synchronized
externally. This is typically accomplished by synchronizing on some
object that naturally encapsulates the set.
If no such object exists, the set should be "wrapped" using the
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...)); The iterators returned by this class's iterator method are
fail-fast: if the set is modified at any time after the iterator is
created, in any way except through the iterator's own remove
method, the iterator will throw a Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.
|
TreeSetpublic TreeSet()
| |
TreeSetpublic TreeSet()
|
TreeSetpublic TreeSet()
|
TreeSetpublic TreeSet(Collection<? extends E> c)
| |
TreeSetpublic TreeSet(Collection<? extends E> c)
|
TreeSetpublic TreeSet(Collection<? extends E> c)
|
TreeSetpublic TreeSet(Comparator<? super E> comparator)
| |
TreeSetpublic TreeSet(Comparator<? super E> c)
|
TreeSetpublic TreeSet(Comparator<? super E> comparator)
|
TreeSetpublic TreeSet(SortedSet<E> s)
| |
TreeSetpublic TreeSet(SortedSet<E> s)
|
TreeSetpublic TreeSet(SortedSet<E> s)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
addAllpublic boolean addAll(Collection<? extends E> c)
| |
addAllpublic boolean addAll(Collection<? extends E> c)
|
addAllpublic boolean addAll(Collection<? extends E> c)
|
ceilingpublic E ceiling(E e)
|
clearpublic void clear()
| |
clearpublic void clear()
|
clearpublic void clear()
|
comparatorpublic Comparator<? super E> comparator()
| |
comparatorpublic Comparator<? super E> comparator()
|
comparatorpublic Comparator<? super E> comparator()
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object o)
|
containspublic boolean contains(Object o)
|
descendingIteratorpublic Iterator<E> descendingIterator()
|
firstpublic E first()
| |
firstpublic E first()
|
firstpublic E first()
|
floorpublic E floor(E e)
|
headSetpublic SortedSet<E> headSet(E toElement)
| |
headSetpublic SortedSet<E> headSet(E toElement)
|
headSetpublic SortedSet<E> headSet(E toElement)
|
higherpublic E higher(E e)
|
iteratorpublic Iterator<E> iterator()
| |
iteratorpublic Iterator<E> iterator()
|
iteratorpublic Iterator<E> iterator()
|
lastpublic E last()
| |
lastpublic E last()
|
lastpublic E last()
|
lowerpublic E lower(E e)
|
navigableHeadSetpublic NavigableSet<E> navigableHeadSet(E toElement)
|
navigableSubSetpublic NavigableSet<E> navigableSubSet(E fromElement, E toElement)
|
navigableTailSetpublic NavigableSet<E> navigableTailSet(E fromElement)
|
pollFirstpublic E pollFirst()
|
pollLastpublic E pollLast()
|
removepublic boolean remove(Object o)
| |
removepublic boolean remove(Object o)
|
removepublic boolean remove(Object o)
|
subSetpublic SortedSet<E> subSet(E fromElement, E toElement)
| |
subSetpublic SortedSet<E> subSet(E fromElement, E toElement)
|
subSetpublic SortedSet<E> subSet(E fromElement, E toElement)
|
tailSetpublic SortedSet<E> tailSet(E fromElement)
| |
tailSetpublic SortedSet<E> tailSet(E fromElement)
|
tailSetpublic SortedSet<E> tailSet(E fromElement)
|
addpublic boolean add(E e)
| |
addpublic boolean add(E o)
|
addpublic boolean add(E e)
|
containspublic boolean contains(Object o)
| |
containspublic boolean contains(Object elem)
|
containspublic boolean contains(Object o)
|
indexOfpublic int indexOf(Object o)
| |
indexOfpublic int indexOf(Object elem)
|
indexOfpublic int indexOf(Object o)
|
indexOfpublic int indexOf(Object o, int index)
| |
indexOfpublic int indexOf(Object elem, int index)
|
indexOfpublic int indexOf(Object o, int index)
|
lastIndexOfpublic int lastIndexOf(Object o)
| |
lastIndexOfpublic int lastIndexOf(Object elem)
|
lastIndexOfpublic int lastIndexOf(Object o)
|
lastIndexOfpublic int lastIndexOf(Object o, int index)
| |
lastIndexOfpublic int lastIndexOf(Object elem, int index)
|
lastIndexOfpublic int lastIndexOf(Object o, int index)
|
removeAllpublic boolean removeAll(Collection<?> c)
| |
removeAllpublic boolean removeAll(Collection<?> c)
|
removeAllpublic boolean removeAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
| |
retainAllpublic boolean retainAll(Collection<?> c)
|
retainAllpublic boolean retainAll(Collection<?> c)
|