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.
OverviewThe 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 ObjectAn 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 Properties to be set when Initializing the ObjectWhen 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 MethodsThe ISpaceProxy interface includes the following main operations:
The diagram below demonstrates how each operation interacts with the Space.
Code Snippets
Write and Read
Write and ReadThe 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 RegistrationThe 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 WriteWhen 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 ReadThe 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);
Clear Clear ObjectsYou 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);
Updating an Object Updating an ObjectThe 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.
The ISpaceProxy.Write has a few activity modes. The return object options are different for each mode:
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
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:
Using Generics and Default Values in the ISpaceProxy objectThe 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 ObjectGigaSpaces 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 AccessEach 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.
See the ID Queries for details. Template Based Data AccessThe 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 AccessThe 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 IteratorThe 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 OperationsThe 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.
Deleting Data with the TakeIfExists and Take OperationsThe 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.
Batch OperationsThe 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:
When using the batch operations:
Manipulating Data using the ISpaceProxy ObjectSaving Data to the SpaceThe 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 ValueWhen 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 UpdateYou 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.
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 OperationsThe 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 ISpaceProxyAll 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 |