GigaSpaces XAP 9.7.2 API

com.j_spaces.core.client
Class GSIterator

java.lang.Object
  extended by com.j_spaces.core.client.GSIterator
All Implemented Interfaces:
Iterable, Iterator

public class GSIterator
extends Object
implements Iterator, Iterable

Creates an iterator that can be used to exhaustively read through all of the visible matching entities in the space and any additional entities that match.

The templates parameter must be a Collection of entity instances (Entry or plain java objects) to be used as templates, but can't coexist with an ExternalEntry as a template. All of the entities iterated will match one or more of these templates. templates may contain null values and may contain duplicates. An entity is said to be visible to an invocation of this iterator if the entity could have been returned by a singleton read using a null transaction.

The resulting iterator must initially contain all of the visible matching entities in the space (note the iteratorScope parameter). During the lifetime of the iterator an entity may be added to the iterator if it becomes visible. If the iterator's leaseDuration expires, no more entries can be added.

Iteration is done by polling results into a buffer. The buffer size can be configured using GSIteratorConfig. The buffer serves as a static snapshot of the entities in space and remains unchanged during the life of its iteration. Modifications only affect unbuffered entities. Once the buffer has been iterated over, a new buffer is polled from the space. Generally speaking, it is impossible to make any hard guarantees in the presence of concurrent modifications.

The iterator's lease duration can be configured using GSIteratorConfig. If the iteration is leased the lease duration must be positive. If leaseDuration is Lease.ANY, the initial duration of the lease can be any positive value desired by the implementation - in this case Lease.FOREVER.

If there are remote method constraints associated with an invocation of this iterator, any remote communications performed by or on behalf of the iterator's next methods will be performed in compliance with these constraints, not with the constraints (if any) associated with next. The next with timeout blocks until a next entity is available or timeout expires.

Sample usage: Here is an example of using an iterator for iterating over matching entities:


 GSIteratorConfig config = new GSIteratorConfig();
 config.setBufferSize(100);
 config.setIteratorScope(IteratorScope.CURRENT_AND_FUTURE);
 Collection<Entry> templates = new LinkedList<Entry>();
 templates.add(new MyEntry());
 GSIterator iterator = new GSIterator(space, templates, config);
 
 long LATENCY = 30000;  //30 seconds
 
 //may return false due to communication constraints
 while (iterator.hasNext())
 {
        Entry next = (Entry) iterator.next();
        Thread.sleep(LATENCY);
 }
 

Here is an example of using a blocking iterator for iterating over matching entities:


 Collection<Entry> templates = new LinkedList<Entry>();
 templates.add(new MyEntry());
 
 GSIterator iterator = new GSIterator(space, templates, config);
 
 long NEXT_TIMEOUT = 30000; //30 seconds
 
 try
 {
        while (true)
        {
                Entry next = (Entry) iterator.next(NEXT_TIMEOUT);
        }
 }
 catch (NoSuchElementException nsee)
 {
        System.out.println("iteration presumably complete.");
 }
 

Note that this implementation is not synchronized. If multiple threads access this iterator concurrently, it must be synchronized externally.

The GSIterator also implements Iterable allowing to use the iterator within a foreach element. Note, when using the iterator within a foreach element, at the end of the foreach, the iterator will be canceled.

Since:
5.0
Version:
2.0
Author:
moran

Constructor Summary
GSIterator(IJSpace spaceProxy, Collection<?> templates)
          Equivalent to calling GSIterator(IJSpace, Collection, com.gigaspaces.client.iterator.GSIteratorConfig).
GSIterator(IJSpace spaceProxy, Collection<?> templates, GSIteratorConfig config)
          Constructs an iterator over a space using a collection of entity instances to be incrementally returned.
GSIterator(IJSpace spaceProxy, Collection<?> templates, int bufferSize, boolean withHistory, long leaseDuration)
          Deprecated. Use GSIterator(IJSpace, Collection, GSIteratorConfig) instead.
 
Method Summary
 void cancel()
          Used by the iterator holder to indicate that there is no further interest in this iterator.
 long getExpiration()
          Returns the absolute time that the lease will expire, represented as milliseconds from the beginning of the epoch, relative to the local clock.
 boolean hasNext()
          Returns true if the iterator has more elements to iterate over.
 Iterator<?> iterator()
           
 Object next()
          Removes one entity from the iterated buffered set and returns a copy to the caller.
 Object next(long timeout)
          Same as next() but with blocking behavior, blocking until a matched entity is available or until timeout expires.
 Object[] nextBatch(int limit)
          Removes number of entities from the iterated buffered set and returns a copy to the caller.
 void remove()
          Not supported operation.
 void renew(long duration)
          Used to renew the iterator's lease for an additional period of time, specified in milliseconds.
 com.j_spaces.core.client.EntrySnapshot snapshot()
          Returns a snapshot, as defined in section JS.2.6 of the JavaSpaces specification, of the entry returned by the last next call.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

GSIterator

public GSIterator(IJSpace spaceProxy,
                  Collection<?> templates)
           throws RemoteException,
                  UnusableEntryException
Equivalent to calling GSIterator(IJSpace, Collection, com.gigaspaces.client.iterator.GSIteratorConfig).

i.e. new GSIterator(spaceProxy, templates, new GSIteratorConfig());

Parameters:
spaceProxy - a Space instance to iterate over.
templates - a Collection of entity instances, each representing a template. All the entities added to the resulting match set will match one or more elements of templates.
Throws:
RemoteException - if a communication error occurs.
UnusableEntryException - if history contained an unusable entity.
IllegalArgumentException - if any non-null element of templates is a mix of ExternalEntry and Entry/POJO instance, if templates is empty or null, if bufferSize is non-positive, or if leaseDuration is neither positive nor Lease.ANY.
See Also:
GSIterator(IJSpace, Collection, GSIteratorConfig)

GSIterator

@Deprecated
public GSIterator(IJSpace spaceProxy,
                             Collection<?> templates,
                             int bufferSize,
                             boolean withHistory,
                             long leaseDuration)
           throws RemoteException,
                  UnusableEntryException
Deprecated. Use GSIterator(IJSpace, Collection, GSIteratorConfig) instead.

Equivalent to calling GSIterator(IJSpace, Collection, GSIteratorConfig), translating withHistory to CURRENT_AND_FUTURE or FUTURE.

Parameters:
spaceProxy - a Space instance to iterate over.
templates - a Collection of entity instances, each representing a template. All the entities added to the resulting match set will match one or more elements of templates.
bufferSize - the maximum number of entities to pool each time from the space.
withHistory - set true to initially contain all of the visible matching entities in the space. Otherwise, will contain only visible matching entities thereafter.
leaseDuration - the requested initial lease time on the resulting match set.
Throws:
RemoteException - if a communication error occurs.
UnusableEntryException - if history contained an unusable entity.
IllegalArgumentException - if any non-null element of templates is a mix of ExternalEntry and Entry/POJO instance, if templates is empty or null, if bufferSize is non-positive, or if leaseDuration is neither positive nor Lease.ANY.

GSIterator

public GSIterator(IJSpace spaceProxy,
                  Collection<?> templates,
                  GSIteratorConfig config)
           throws RemoteException,
                  UnusableEntryException
Constructs an iterator over a space using a collection of entity instances to be incrementally returned. Some operations on a space must return more entities than can be conveniently returned by a single call, generally because returning all the entries in one result would consume too many resources in the client or introduce too much latency before the first entity could be processed. In these cases, iterators are used to incrementally return the necessary entries. A GSIterator instance is used to access a set of matches returned by next.

The iterator will initially contain some population of entities. These entities can be retrieved by calling next. A successful call to next will remove the returned entity from the iteration. An iterator can end up in one of two terminal states, invalidated or exhausted.

A leased iterator which expires is considered as invalidated. A canceled iterator is an exhausted iterator and will have no more entities added to it. Calling next on an iterator with either state always returns null or it may throw one of the allowed exceptions. In particular next(timeout) may throw NoSuchObjectException to indicate that no entity has been found during the allowed timeout. There is no guarantee that once next(timeout) throws a NoSuchObjectException, or next returns null, all future calls on that instance will do the same.

Between the time an iterator is created and the time it reaches a terminal state, entities may be added by the space. However, an entity that is removed by a next call may be added back to the iterator if its uniqueness is equivalent. The space may also update or remove entities that haven't yet been returned by a next call, and are not part of the buffered set.

If there is a possibility that an iterator may become invalidated, it must be leased. If there is no possibility that the iterator will become invalidated, implementations should not lease it (i.e. use Lease.FOREVER). If there is no further interest an iterator may be canceled.

An active lease on an iterator serves as a hint to the space that the client is still interested in matching entities, and as a hint to the client that the iterator is still functioning. There are cases, however, where this may not be possible in particular, it is not expected that iteration will maintain across crashes. If the lease expires or is canceled, the iterator is invalidated. Clients should not assume that the resources associated with a leased match set will be freed if the match set reaches the exhausted state, and should instead cancel the lease.

Parameters:
spaceProxy - a Space instance to iterate over.
templates - a Collection of entity instances, each representing a template. All the entities added to the resulting match set will match one or more elements of templates.
config - a set of configurations to determine the iterator's behaviour.
Throws:
RemoteException - if a communication error occurs.
UnusableEntryException - if history contained an unusable entity.
IllegalArgumentException - if any non-null element of templates is a mix of ExternalEntry and Entry/POJO instance, if templates is empty or null, if bufferSize is non-positive, or if leaseDuration is neither positive nor Lease.ANY.
Method Detail

snapshot

public com.j_spaces.core.client.EntrySnapshot snapshot()
                                                throws IllegalStateException
Returns a snapshot, as defined in section JS.2.6 of the JavaSpaces specification, of the entry returned by the last next call. If the last next call returned null or failed with an exception or error, snapshot will throw an IllegalStatException

Returns:
Entry snapshot of last next call
Throws:
IllegalStateException - when last next call failed

hasNext

public boolean hasNext()
Returns true if the iterator has more elements to iterate over. If the iterator was constructed to initially contain matching entities, then hasNext() will return true until the entire initial set has been iterated over. Still, hasNext() may return false iterating over any additional matching entities due to communication constraints - thus, it does not guarantee that the iterator is in one of its terminal states. It is advised to use Thread.sleep(long) between subsequent calls, to allow the iterator to receive possible additional matches.

Specified by:
hasNext in interface Iterator
Returns:
true if the iterator has more matches; false if currently there are no more available matches to return from a call to next().

nextBatch

public Object[] nextBatch(int limit)
                   throws NoSuchElementException
Removes number of entities from the iterated buffered set and returns a copy to the caller.

A given invocation of this method may perform remote communications, retrieving the next buffer set, but generally the nextBatch method is not expected to have remote method constraints that can vary from invocation to invocation.

Parameters:
limit - a limit on the number of entities to be returned. Use Integer.MAX_VALUE for the uppermost limit.
Returns:
an entity from the iterated buffered set, or null if the iterated set is empty or presumably complete.
Throws:
NoSuchElementException

next

public Object next()
Removes one entity from the iterated buffered set and returns a copy to the caller. Returns null if a call to hasNext would have returned false.

A given invocation of this method may perform remote communications, retrieving the next buffer set, but generally the next method is not expected to have remote method constraints that can vary from invocation to invocation.

Specified by:
next in interface Iterator
Returns:
an entity from the iterated buffered set, or null if the iterated set is empty or presumably complete.

next

public Object next(long timeout)
            throws NoSuchElementException
Same as next() but with blocking behavior, blocking until a matched entity is available or until timeout expires.

Parameters:
timeout - time to wait until a next element is available.
Returns:
an entity from the iterated buffered set.
Throws:
NoSuchElementException - when timeout expires and no available match was found.

getExpiration

public long getExpiration()
Returns the absolute time that the lease will expire, represented as milliseconds from the beginning of the epoch, relative to the local clock.

Returns:
a long value in milliseconds from the beginning of the epoch relative to the local clock that represents the absolute time that the lease will expire.

renew

public void renew(long duration)
           throws IllegalArgumentException,
                  LeaseDeniedException
Used to renew the iterator's lease for an additional period of time, specified in milliseconds. This duration is not added to the original lease, but is used to determine a new expiration time for the existing lease. If the renewal is granted this is reflected in value returned by getExpiration. If the renewal fails, the lease is left intact for the same duration that was in force prior to the call to renew.

An expired iterator is an invalidated iterator and will have no more entities added to it. Subsequent calls to next on this iterator will always return null.

Parameters:
duration - the requested duration in milliseconds
Throws:
IllegalArgumentException - if invalid lease expiration time
LeaseDeniedException - if the iterator's lease has already expired

cancel

public void cancel()
Used by the iterator holder to indicate that there is no further interest in this iterator. The overall effect of a cancel call is the same as lease expiration, but instead of happening at the end of a pre-agreed duration it happens immediately.

A cancelled iterator is an exhausted iterator and will have no more entities added to it. Subsequent calls to next on this iterator will always return null.


remove

public void remove()
Not supported operation. Here because of Iterator implementation.

Specified by:
remove in interface Iterator

iterator

public Iterator<?> iterator()
Specified by:
iterator in interface Iterable

GigaSpaces XAP 9.7.2 API

Copyright © GigaSpaces.