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);
GigaSpaces.com - Legal Notice - 3rd Party Licenses - Site Map - API Docs - Forum - Downloads - Blog - White Papers - Contact Tech Writing - Gen. by Atlassian Confluence