Concurrent updates (put) in TIBCO ActiveSpaces (Java).

Concurrent updates (put) in TIBCO ActiveSpaces (Java).

book

Article ID: KB0085866

calendar_today

Updated On:

Products Versions
TIBCO ActiveSpaces -
Not Applicable -

Description

Resolution:
Description:
===========
How to achieve concurrent updates (put) in TIBCO ActiveSpaces (Java).

Environment:
===========
TIBCO ActiveSpaces 2.x .
All Operating Systems.


Resolution:
========

There are two options, optimistic (less contention) and pessimistic (lot of contention).

Code samples:

1).
    //optimistic – less contention
    public void optimistic () throws Exception
    {
        Tuple tuple = Tuple.create();
        tuple.put("key", SequenceID);
        Tuple current = space.get(tuple);

        while (true)
        {
            long num = (current == null) ? 0L : current.getLong("value") + 1;
            tuple.putLong("value", num);
            Tuple result = space.compareAndPut(current, tuple);
            if (result == tuple)
            {
                System.out.println("update successful " + tuple);
                break;
            }

            // if comparison fails, compare and put returns current value
            // no need to issue get
            current = result;
        }
    }

    
2).
    //pessimistic – a lot of contention
    public void pessimistic () throws Exception
    {
        Tuple tuple = Tuple.create();
        tuple.put("key", SequenceID);
        // continue until lock is successfully taken
        Tuple current;
        int count = 0;
        while (true)
        {
            try
            {
                count++;
                current = space.lock(tuple, LockOptions.create().setLockWait(100));
                break;
            }
            catch (ASException as)
            {
                if (as.getStatus() == ASStatus.LOCKED)
                {
                    System.out.println("lock failed count=" + count);
                    if (count == 100)
                    {
                        throw new Exception("failed to lock key for 100 attempt");
                    }
                    continue;
                }
                throw as;
            }
        }
        long num = (current == null) ? 0L : current.getLong("value") + 1;
        tuple.putLong("value", num);
        Tuple result = space.put(tuple, PutOptions.create().setUnlock(true));
        System.out.println("update successful " + tuple);
    }

Issue/Introduction

Concurrent updates (put) in TIBCO ActiveSpaces (Java).