Summary: The ISpaceProxy interface provides access to the In-Memory Data Grid or the Space. The ISpaceProxy interface is used to read froom and write to the space.

Overview

The ISpaceProxy interface is ideal for connecting to data stored in the Space. The ISpaceProxy interface is used to interact with the Space, allowing both read and write actions.

Initializing an ISpaceProxy Object

An ISpaceProxy is initialized using the GigaSpacesFactor static class object.

An ISpaceProxy can be initialized directly in the code or in the pu.config file in XML format. To define an ISpaceProxy:

PU.config
<GigaSpaces.XAP>
    <ProcessingUnitContainer Type="GigaSpaces.XAP.ProcessingUnit.Containers.BasicContainer.BasicProcessingUnitContainer, GigaSpaces.Core"/>
      <BasicContainer>
//Defining the space proxy. These details are used to create the {{ISpaceProxy}} instance.
        <SpaceProxies>
          <add Name="MySpace" Url="/./mySpace" ClusterInfoAware="false"/>
          <add Name="MyClusteredSpace" Url="/./myClusteredProxy" Mode="Clustered"/>
        </SpaceProxies>
      </BasicContainer>
  </GigaSpaces.XAP>

Code
ISpaceProxy mySpace = GigaSpacesFactory.FindSpace("/./spaceName")

Several ISpaceProxy instances can be defined within a single Processing Unit, each with its own properties.

ISpaceProxy simplifies most operations used with the space, but some operations still require access to IJSpace, which can be accessed through the ISpaceProxy API.

  • The ISpaceProxy variable represents a remote or embedded space proxy (for a single space or clustered) and should be constructed only once throughout the lifetime of the application process.
  • You should treat the ISpaceProxy variable as a singleton to be shared across multiple different threads.
  • The ISpaceProxy interface is a thread safe and there is no need to create an ISpaceProxy variable per application thread.
  • In case the space has been fully terminated (no backup or primary instances running any more) the client space proxy will try to reconnect to the space up to a predefined timeout based on the Proxy Connectivity settings. If it fails to reconnect, an error will be displayed.

ISpaceProxy Properties to be set when Initializing the Object

When starting an embedded space with a cluster topology, or when looking up a remote space started with a cluster topology, a clustered proxy is returned. A clustered proxy is a smart proxy that performs operations against the whole cluster.

Many times, especially when working with a Processing Unit that starts an embedded space, operations against the space should be performed directly on the cluster member. This is a core concept of SBA and Processing Unit, where most, if not all operations should be performed in-memory without leaving the processing unit boundaries when a Processing Unit starts an embedded space.

The decision of working directly with a cluster member or against the whole cluster is done in the ISpaceProxy level. The GigaSpacesFactory provides a clustered flag with the following logic as the default value: If the space is started in embedded mode (for example, /./space), the clustered flag is set to false. When the space is looked up in a remote protocol (Jini or RMI), the clustered flag is set to true. In addition to automatically setting the flag, the flag can be set explicitly. To configure a clustered proxy:

Namespace
<GigaSpaces.XAP>
    <ProcessingUnitContainer Type="GigaSpaces.XAP.ProcessingUnit.Containers.BasicContainer.BasicProcessingUnitContainer, GigaSpaces.Core"/>
      <BasicContainer>
        <SpaceProxies>
          <add Name="MySpace" Url="/./mySpace" ClusterInfoAware="false"/>
          <add Name="MyClusteredSpace" Url="/./myClusteredProxy" Mode="Clustered"/>
        </SpaceProxies>
      </BasicContainer>
  </GigaSpaces.XAP>

Code
//define the space configuration object
SpaceConfig mySettings = new SpaceConfig();
//set the clustered property to true
mySettings.ClusterInfo = true;

//use the FindSpace method in the GigaSpacesFactory static class to create the ISpaceProxy object. Include the SpaceConfig object to set the ISpaceProxy as clustered.
ISpaceProxy proxy = GigaSpacesFactory.FindSpace("/./embSpace", mySettings);

The above example shows a typical scenario where the clustered flag is used. Within a Processing Unit, an application might need to access both the cluster member and the whole cluster directly.

ISPaceProxy Methods

The ISpaceProxy interface includes the following main operations:

Id Based operations Batch operations Asynchronous operations Data Count operations
ReadById
TakeById
ReadByIds
TakeByIds
ReadIfExistsById
TakeIfExistsById
ReadMultiple
TakeMultiple
WriteMultiple
ReadByIds
TakeByIds
BeginExecute
BeginTake
EndExecute
EndTake
Count
Data Query operations Data Insert and Update operations Business logic execution operations Data removal operations
Read
ReadMultiple
GetSpaceIterator
Write
WriteMultiple
Execute
Clean
Clear
Take
TakeMultiple

The diagram below demonstrates how each operation interacts with the Space.

The Clear and Clean operations do not remove the Space class definition from the Space. You should restart the Space to allow it to drop the class definitions.

Code Snippets

Write and Read

Write and Read

The ISpaceProxy.Write method saves new objects to, and updates existing objects in the Space. In order to override these default semantics, you can use the overloaded Write methods which accept update modifiers such as UpdateModifiers.UPDATE_ONLY.

The Read methods are used to retrieve objects from the Space. The Read method returns a copy of the matching object to the client. To read more than one object, you should use the ReadMultiple methods of the ISpaceProxy interface. To define the criteria for the operation, all of these methods accept either a template object, or an SQLQuery instance. A template object is an example object of the class you would like to read. For an object in the space to match the template, each of the non-null properties in the template must match its values for these properties. To read an object by its ID (key), you should use one of the ReadById/ReadByIds methods.

Getting Space proxy:

ISpaceProxy mySpace = GigaSpaceFactory.FindSpace("spaceURL");
mySpace.defaultTimeout = 1000;
mySpace.defaultLeaseTime = 1000;

The following writes an Employee object and reads it back using a simple template:

ISpaceProxy mySpace;
Employee employee = new Employee("Last Name", new Integer(32));
employee.setFirstName("first name");
LeaseContext<Employee> lc = mySpace.Write(employee);
Employee template = new Employee();
Employee result = mySpace.Read(template);

Notification Registration

Notification Registration

The ISpaceProxy can register Listener objects to create notifications. The following registers for notifications:

//Create a notification listener for object of type person, and specify a function as the Event Handler.
ISpaceProxy proxy;
IEventRegistration eventReg = proxy.DefaultDataEventSession.AddListener(new Person(), Space_PersonChanged);
//create the person object 
Person person = new Person();
person.UserID = "123456";
//save the person to the Space. The event handler for the notifications listener is called.
proxy.Write(person);
//update person object. The event handler for the notifications listener is called.
proxy.Write(person, WriteModifiers.UpdateOrWrite);
//delete the person object from the Space. The event handler for the notifications is called.
proxy.Take(person);

// Remove the notifications listener
proxy.DefaultDataEventSession.RemoveListener(eventReg);

Batch Write

Batch Write

When writing a batch of objects into the Space, these should be placed into an array to be used by the ISpaceProxy.WriteMultiple operation. The returned array will include the corresponding LeaseContext object.

ISpaceProxy space; 
Employee emps[] = new Employee[2]; 
emps[0] = new Employee("Last Name A", new Integer(10)); 
emps[1] = new Employee("Last Name B", new Integer(20)); 
try { 
    ILeaseContext[] leaseContexts = space.WriteMultiple(emps); 
    for (int i = 0;i<leaseContexts.length ; i++) { 
        System.out.println ("Object UID " + leaseContexts[i].getUID() + " inserted into the space"); 
    } 
} catch (WriteMultipleException e) { 
    IWriteResult[] writeResult = e.getResults(); 
    for (int i = 0;i< writeResult.length ; i++) { 
        System.out.println ("Problem with Object UID " + writeResult "); 
    } 
}

Batch Read

Batch Read

The following queries the space using SQL:

ISpaceQuery space;
String querystr	= "age>40";
SQLQuery query = new SQLQuery(Employee.class, querystr);
Employee results[] = space.readMultiple(query , Integer.MAX_VALUE);
Constructing SQLQuery objects is a relatively expensive operation. You should not construct these with every space query operation. Instead, it is recommended to construct it once, and then use it with dynamic query options: SQLQuery.SetParameters and SQLQuery.SetParameter.

Clear

Clear Objects

You can use the SQLQuery with the GigaSpace.clear to remove objects from the space:

ISpaceProxy space;
String querystr	= "age>30";
SQLQuery query = new SQLQuery(Employee.class, querystr);
space.clear(query);
When using the SQLQuery with greater/less than queries, turn on the extended indexing.

Updating an Object

Updating an Object

The ISpaceProxy.Write with the WriteModifiers.UPDATE_ONLY modifier should be used to explicitly perform an update operation. The WriteModifiers.UPDATE_OR_WRITE is the default mode with Write operations. This means that subsequent calls to the Write operation with an object with identical SpaceId will result in an update operation, i.e. a new object will not be inserted into the space.

Make sure your Space Class has the SpaceId(autoGenerate=false) when performing update operations.

The ISpaceProxy.Write has a few activity modes. The return object options are different for each mode:

  1. Inserting or updating an existing object: The WriteModifiers.UPDATE_OR_WRITE modifier should be used. This is the default mode.
  2. Inserting a new object into the space: The WriteModifiers.WRITE_ONLY modifier should be used.
  3. Updating an existing object: The WriteModifiers.UPDATE_ONLY modifier should be used.
  4. Updating an existing object but sending only the modified fields to the space: The WriteModifiers.PARTIAL_UPDATE modifier should be used.
Modifier On Success OnFailure
UPDATE_OR_WRITE *NULL returned when inserting a new object \ * The previous object is returned when updating an existing object. UpdateOperationTimeoutException thrown on timeout. The object is locked in another transaction.
WRITE_ONLY NULL EntryAlreadyInSpaceException thrown
UPDATE_ONLY The previous object is returned
  • NULL if there's a timeout. The object is locked in another transaction
  • EntryNotInSpaceException - when the object is not found in the Space.
  • SpaceOptimisticLockingFailureException, thrown only when running in Optimistic locking mode. This Exception includes the existing version id of the object within the space and the client side version id of the object. In this case you should read the object again and retry the update operation. See Optimistic Locking for more details.
PARTIAL_UPDATE The previous object is returned
  • NULL if there's a timeout. The object is locked in another transaction
  • EntryNotInSpaceException - when the object is not found in the Space.
  • SpaceOptimisticLockingFailureException, thrown only when running in Optimistic locking mode. This Exception includes the existing version id of the object within the space and the client side version id of the object. In this case you should read the object again and retry the update operation. See Optimistic Locking for more details.
When using PARTIAL_UPDATE, assign a null value to fields that should not be updated. Only set fields are sent to the Space to replace the existing field's value. Make sure the updated object includes its ID when using this option.

When updating an object, you can specify 0 (ZERO) as the lease time. This will instruct the space to use the original lease time used when the object has been written into the space.

UPDATE_OR_WRITE Example:

try
{
	LeaseContext ret = space.Write(employee ,/*lease*/  0 ,/*timeout*/  1000 , WriteModifiers.UPDATE_OR_WRITE);
	if ( ret.getObject() == null)
	{
		//  successful write
	}
	if (ret.getObject() instanceof Employee)
	{
		//  successful update
	}
}
catch (UpdateOperationTimeoutException uote)
{
	// Object is locked - unsuccessful update
}

WRITE_ONLY Example:

try
{
	LeaseContext ret = space.Write(employee ,/*lease*/  0 ,/*timeout*/  1000 , WriteModifiers.WRITE_ONLY);
	if ( ret.getObject() == null)
	{
		//  successful write
	}
}
catch (EntryAlreadyInSpaceException eainse)
{
	// Object already exists - unsuccessful write
}

UPDATE_ONLY Example:

try
{
	LeaseContext ret = space.Write(employee ,/*lease*/  0 ,/*timeout*/  1000 , WriteModifiers.UPDATE_ONLY);
	if ( ret == null)
	{
		// Object is locked - unsuccessful update
	}
	else if (ret.getObject() instanceof Employee)
	{
		//  successful update
	}
}
catch (EntryNotInSpaceException enise)
{
	// Object not in space - unsuccessful update
}
catch (SpaceOptimisticLockingFailureException solfe)
{
	// Client holds wrong version of the object - unsuccessful update. We need to read it again and issue the update call again.
}

PARTIAL_UPDATE Example:

ISpaceProxy space = GigaSpacesFactory.FindSpace("jini://*/*/mySpace");
space.NoWriteLeaseMode = true;

// initial insert
MyClass obj = new MyClass();
obj.setId("1");
obj.setField1("A");
obj.setField2("B");
obj.setField3("C");                               
space.Write(obj);

// reading object back from the space
MyClass obj2 = space.readById(MyClass.class , "1");

// updating only field2 
obj2.setField1(null);
obj2.setField2("BBBB");
obj2.setField3(null);
try
{
	space.Write(obj2,0,0,WriteModifiers.PARTIAL_UPDATE);
}
catch (EntryNotInSpaceException enise)
{
	// Object not in space - unsuccessful update
}

Batch Update

Batch Update

Make sure your Space Class will have the SpaceId(autoGenerate=false) when performing update operations.

The GigaSpace.updateMultiple returns an array of objects which correspond to the input object array. The returned object element can be one of the following:

  • when the WriteModifiers.UPDATE_OR_WRITE modifier is applied the following returns:
    • For a successful operation:
      • null - if a new object is inserted (write operation)
      • The previous version of the object (update operation)
        Since the GigaSpace.updateMultiple in WriteModifiers.UPDATE_OR_WRITE

        mode does not support timeout based updates, there is no way to identify if an updated object is already locked under a transaction - i.e. the
        UpdateOperationTimeoutException is not returned as part of the returned array elements.
        With a transactional system, it is recommended to perform batch updates using the WriteModifiers.UPDATE_ONLY
        modifier.

        UPDATE_ONLY Example:

        ISpaceProxy space;
        Employee employees[] = space.ReadMultiple(query , 10000);
        Object retUpdateMulti[] = space.WriteMultiple(employees ,/*leases*/ new long[results.length],WriteModifiers.UPDATE_ONLY);
        
        for (int i = 0;i<retUpdateMulti ; i++)
        {
        	if  (retUpdateMulti[i] == null ) {
        		//  unsuccessful update
        		break;
        	}
        	else if  (retUpdateMulti[i] instanceof Exception) {
        		//  unsuccessful update
        		if (retUpdateMulti[i] instanceof EntryNotInSpaceException)
        		{
        		...
        		}
        
        		else if (retUpdateMulti[i] instanceof SpaceOptimisticLockingFailureException)
        		{
        		...
        		}
        
        
        		break;
        	}
        
        	else if  (retUpdateMulti[i] instanceof Employee ) {
        		//  successful update
        	}
        }

        PARTIAL_UPDATE Example:

        ISpaceProxy space;
        for (int i=0;i<employees.length;i++)
        {
        	employees[i].setFirstName(null);
        	employees[i].setLastName(null);
        	employees[i].setBalance(newValue);
        	leases[i] = Lease.FOREVER;
        }
        
        space.WriteMultiple(employees, Lease.FOREVER, WriteModifiers.PARTIAL_UPDATE);

Using Generics and Default Values in the ISpaceProxy object

The ISpaceProxy interface is implemented to provide a wide variety of options for reading data. By receiving and returning a generic parameter, the function provides the capability to read all types of objects in the Space. By implementing many overriding functions, you can take advantage of the in-built default values, or choose to specify your own values according to your own needs. In the Take function below, you can choose to override the timeout value, or use the default value of 0 and not specify a timeout value at all.

public interface ISpaceProxy{

    // ....
    
    <T> T Take(T template) throws DataAccessException;
    
    <T> T Take(T template, long timeout) throws DataAccessException;

   
}

In a similar manner, the read timeout and write lease can be specified.

Namespace
<GigaSpaces.XAP>
    <ProcessingUnitContainer Type="GigaSpaces.XAP.ProcessingUnit.Containers.BasicContainer.BasicProcessingUnitContainer, GigaSpaces.Core"/>
      <BasicContainer>
//Defining the space proxy. These details are used to create the {{ISpaceProxy}} instance.
        <SpaceProxies>
          <add Name="MySpace" Url="/./mySpace" ClusterInfoAware="false"/>
          <add Name="MyClusteredSpace" Url="/./myClusteredProxy" Mode="Clustered" Default-Timeout="1000"/>
        </SpaceProxies>
      </BasicContainer>
  </GigaSpaces.XAP>

Code
ISpaceProxy myProxy = GigaFactory.FindSpace("spacePath");

//call Take function using the default timeout value
    myProxy.Take(myTemplate);

//call Take function overriding the default timeout value
    myProxy.Take(myTemplate, 10000);

Accessing Data in the Space with an ISpaceProxy Object

GigaSpaces XAP.NET offers a number of methods for accessing data in the Space. Different data access methods allow you to select the most efficient way to access your data, depending on each scenario. Accessing your data can be achieved using:

ID Based Data Access

Each space object includes an ID. You may read or remove objects from the space using their ID via the ReadByID,TakeByID,ReadIfExistsById,TakeIfExistsById, ReadByIDs or the TakeByIDs operations.

The ReadByID and ReadByIDs have a special performance optimization when running a Local Cache or Local View.

See the ID Queries for details.

Template Based Data Access

The template is an object of the desired entry type, and the properties which are set on the template (i.e. not null) are matched against the respective properties of entries of the same type in the space. Properties with null values are ignored (not matched).

See the Template Matching for details.

SQL Based Data Access

The SqlQuery class is used to query the space using SQL-like syntax. The query statement includes only the WHERE clause. The selection aspect of a SQL statement is embedded in other parameters for a SQL query.

See the SqlQuery for details.

Space Iterator

The IteratorBuilder with the GSIterator allows you to iterate over large amount of space objects in a paging approach. It avoids the need to retrieve the entire result set in one batch as the ReadMultiple since it is fetching the result set in batches. This optimizes the resource utilization (memory and CPU) involved when executing the query both at the client and server side.

See the Paging Support with Space Iterator for details.

ReadIfExists and Read Operations

The two forms of the Read operations query the space for an object that matches the template/SqlQuery provided. If a match is found, a copy of the matching object is returned. If no match is found, null is returned. Passing a null reference as the template will match any object.

The Read function returns one matching object from the Space. By default, when you perform successive Read requests, a different matching object may be returned, even if no intervening modifications have been made to the Space. This means that the function by default does not consider the order the objects were inserted to the Space in. Therefore, each Read request can result in different objects being returned.

If you would like to Read objects in the same order they were written to the Space, the FIFO mode should be turned on.

A ReadIfExists operation will return a matching object, or a null if there is currently no matching object in the space. If the only possible matches for the template have conflicting locks from one or more other transactions, the timeout value specifies how long the client is willing to wait for interfering transactions to settle before returning a value. If at the end of that time no value can be returned that would not interfere with transactional state, null is returned. Note that, due to the remote nature of the space, Read and ReadIfExists may throw a RemoteException if the network or server fails prior to the timeout expiration.

A Read operation acts like a ReadIfExists except that it will wait until a matching object is found or until transactions settle, whichever is longer, up to the timeout period.

In both read methods, a timeout of 0 means to return immediately, with no waiting, which is equivalent to using a zero timeout. An IllegalArgumentException will be thrown if a negative timeout value is used.

The Read operation default timeout is 0.

Deleting Data with the TakeIfExists and Take Operations

The Take operations perform exactly like the corresponding Read operations, except that the matching object is removed from the space on one atomic operation. Two Take operations will never return copies of the same object, although if two equivalent objects were in the space the two Take operations could return equivalent objects.

If a Take returns a non-null value, the object has been removed from the space, possibly within a transaction. This modifies the claims to once-only retrieval: A take is considered to be successful only if all enclosing transactions commit successfully. If a RemoteException is thrown, the take may or may not have been successful. If an UnusableEntryException is thrown, the take removed the unusable object from the space. If any other exception is thrown, the take did not occur, and no object was removed from the space.

With a RemoteException, an object can be removed from a space and yet never returned to the client that performed the take, thus losing the object in between. In circumstances in which this is unacceptable, the take can be wrapped inside a transaction that is committed by the client when it has the requested object in hand.

If you would like to take objects from the space in the same order they have been written into the space you should perform the take objects in a FIFO mode.

Taking an object from the space might generate notifications to registered objects/queries.

The Take operation default timeout is 0.

Batch Operations

The ISpaceProxy interface provides simple way to perform bulk operations. You may read or write large numbers of objects in one call. The batch operations are called using the following functions:

  • ISpaceProxy.ReadMultiple: Bulk read.
  • ISpaceProxy.TakeMultiple: Bulk take (read+remove). Returns the removed objects to the client.
  • ISpaceProxy.WriteMultiple: Bulk write and update.

To remove a batch of objects without returning them back to the client use the ISpaceProxy.Clear(SQLQuery); method.

When using the batch operations:

  • The ReadMultiple and TakeMultiple operations boost performance, since they perform multiple operations using one call. These methods returns the matching results in one result object back to the client. This allows the client and server to utilize the network bandwidth in an efficient manner. In some cases, these batch operations can be up to 10 times faster than multiple single based operations.
  • The ReadMultiple and TakeMultiple operations should be handled with care, since they can return a large data set (potentially all the space data). This might cause an out of memory error in the space and client process. You should use the GSIterator to return the result in batches (paging) in such cases.
  • Destructive batch operations (TakeMultiple , WriteMultiple) should be performed with transactions, as this allows the client to roll back the space to its initial state prior the operation was started, in case of a failure.
  • When calling WriteMultiple, make sure null values are not part of the passed array.
  • When using WriteMultiple, you should verify that duplicated entries (with the same ID) do not appear as part of the passed array, since the identity of the object is determined based on its ID and not based on its reference. This is extremely important with an embedded space, since WriteMultiple injects the ID value into the object after the write operation (when autogenerate=false).
  • The ReadMultiple and TakeMultiple operations do not support timeout operations. The simple way to achieve this is by calling the Read operation first with the proper timeout, and if non-null values are returned, perform the batch operation.
  • The WriteMultiple throws a WriteMultipleException. The WriteMultipleException returns details of which write operations were successful and which were not, together with the reason for an unsuccessful operation.

Manipulating Data using the ISpaceProxy Object

Saving Data to the Space

The ISpaceProxy.Write() operation saves a copy of an object into the Space. The actual object passed as a parameter to the Write function is not affected by the operation. As with the Read operation, the Write operation supports default values and generic parameters. When the object to be saved already exists in the Space (objects are identified with their ID), the default behavior is to perform an update operation. To change the default update operation scenario, change the update mode in the WriteModifiers enum settings to WriteModifiers.WRITE_ONLY mode.

When updating an object with many fields use the PARTIAL_UPDATE mode.

When performing a Write operation you may provide a lease (time to live) duration (in milliseconds time unit) for the object. The Write invocation returns a Lease object allowing you to cancel or renew the object lease. When the lease expires, the object is removed from the Space. The default lease duration is FOREVER. An IllegalArgumentException is thrown if the lease time requested is negative.

If a Write returns without throwing an exception, that object is committed to the Space, possibly within a transaction. When the Write operation throws an exception, the exception type and message must be considered in order to know whether the object was successfully committed to the Space or not. For example, the EntryAlreadyInSpaceException when using write with a WriteOnly modifier means the object was not committed, as it already exists in the Space.

Writing an object into a space might generate notifications to registered objects.

Returning Previous Value

When updating an existing object in the space, you may need the object's value before it was updated. The previous value is returned as an ILeaseContext Object. The default behavior is to return a null value. To change the setting, set the WriteModifiers.RETURN_PREV_ON_UPDATE to true.

Performing a Delta Update

You may update selected Space object fields (delta) using the WriteModifiers.PARTIAL_UPDATE modifier. This option is useful when having objects with large number of fields where you would like to update only few of the space object fields. This optimizes the network utilization and avoids serializing/de-serializing the entire object fields when interacting with a remote space.

How to Perform a Delta Update?

When using the PARTIAL_UPDATE modifier, only enter values into the fields that should be updated. All other fields should be assigned a null value. This means that only fields which are set are sent from the client to the Space to replace the existing field's value. In case of a backup (replica) space, the primary space only replicates the updated fields (delta).

Make sure the updated object include its ID when using this option.

To use Delta updates you don't have to implement any special interface or have special serialization code. You can use a regular Object.

When updating an object, you can specify 0 (ZERO) as the lease time. This instructs the space to use the original lease time used when the object was written to the Space.

PARTIAL_UPDATE Example:

ISpaceProxy mySpace = GigaSpaceFactory.FindSpace("spaceURL");

// initial insert with full update.  
MyClass obj = new MyClass();
obj.setId("1");
obj.setField1("A");
obj.setField2("B");
obj.setField3("C");                               
mySpace.Write(obj);

// reading object back from the space
MyClass obj2 = Space.ReadById(MyClass.class , "1");

// updating only field2 
obj2.setField1(null);
obj2.setField2("BBBB");
obj2.setField3(null);
try
{
	mySpace.Write(obj2,0,0,WriteModifiers.PARTIAL_UPDATE);
}
catch (EntryNotInSpaceException enise)
{
	// Object not in space - unsuccessful update
}

Performing Asynchronous Operations

The ISpaceProxy interface implements the Asynchronous Programming Model (APM). The ISpaceProxy asynchronous or non-blocking model defines the BeginRead, BeginTake and BeginExecute functions. The BeginRead function performs an asynchronous Read operation; the BeginTake performs an Asynchronous take operation and the BeginExecute function performs an asynchronous Execute or Write operation. The BeginExecute function is used to execute an ISpaceTask.

Each function returns an IAsynchResult<T> object, where T where T is the type of the object the request returns. The IAsynchResult return object is passed as a parameter to the EndRead, EndExecute and EndTake functions. The EndRead, EndExecute and EndTake functions return the IAsynchResult object as the Template object from the Space.

An asynchronous Write operation can be implemented using a ISpaceTask, where the ISpaceTask implementation includes a write operation. With this approach the ISpaceTask is sent to the space and executed in an asynchronous manner. The write operation itself will be completed once both the primary and the backup confirm the operation is completed. This activity is performed as background activity from the client's perspective.

Space Class
[Serializable]
public class MyClass {
	String data;
	Integer id;	
	public MyClass(){}
	public MyClass(int id , String data){
		this.id = id;
		this.data = data;
	}
	public MyClass(int id){this.id = id;}		

        public string data
       {
        get 
           {
               return data; 
           }
        set 
            {
               data = value; 
            }
        }
	
	@SpaceId (autoGenerate = false)
	@SpaceRouting
	public Integer id 
        {
          get 
              {
                 return id;
              }
          set
              {
                 id = value;
              }
         }
}

Async Read
//GetTestProxy initializes the ISpaceProxy object
ISpaceProxy proxy = GetTestProxy();
IAsyncResult<MyClass> asyncResult = proxy.BeginRead(template, 10000, null, null);

Async Take
//GetTestProxy initializes the ISpaceProxy object
ISpaceProxy proxy = GetTestProxy();
MyClass result = proxy.EndRead(asyncResult);

Async Write
ISpaceProxy spaceProxy = GetTestProxy();
IAsyncResult<MyClass> asyncResult = spaceProxy.BeginExecute(new TestSpaceTask(false), null, null, null, null);                                                                            
MyClass result = spaceProxy.EndExecute(asyncResult);

space.Execute(new AsyncWriteTask(obj));
The AsyncWriteTask
public class AsyncWriteTask implements ISpaceTask<Integer>{
	MyClass obj;
	public AsyncWriteTask (MyClass obj)
	{
		this.obj=obj;
	}
	ISpaceProxy space;
	public Integer Execute() throws Exception {
		space.Write (obj);
		return 1;
	}
}

Using Transactions with the ISpaceProxy

All methods in the ISpaceProxy interface that interact with the Space include overriding methods which can receive a transaction object. Transactions are created by first creating an ITransactionManager Object using the GigaSpacesFactory.CreateDistributedTransactionManager() method. The ITransactionManager object in turn creates the transaction object with the ITransactionManager.Create() which returns an ITransaction object.

See Transactions for more information on the Transaction Manager and the Transaction objects.

GigaSpaces.com - Legal Notice - 3rd Party Licenses - Site Map - API Docs - Forum - Downloads - Blog - White Papers - Contact Tech Writing - Gen. by Atlassian Confluence