get one value from map

16 views
Skip to first unread message

Samuel Fung

unread,
Feb 10, 2012, 5:06:41 AM2/10/12
to Hazelcast
Suppose my application needs to randomly get one value from a map, the
obvious method is
MyClass myObject = myMap.values().iterator().next();
Does the call to values() actually serialize all entries to the node
running this statement? If yes, is there a more efficient way?

Tim Peierls

unread,
Feb 10, 2012, 9:50:44 AM2/10/12
to haze...@googlegroups.com
I'm assuming you mean arbitrary rather than random, in which case this code:

static MyClass getArbitraryValue(IMap<MyKey, MyClass> myMap) {
    Set<MyKey> keys =  myMap.localKeySet() ;
    if (keys.isEmpty()) {
        keys = myMap.keySet();
        if (keys.isEmpty()) {
            return null;
        }
    }
    return myMap.get(keys.iterator().next());
}

should work reasonably well, since most of the time you can expect there to be a local value. 

This code is slightly race-y, because the value associated with the first key could be removed in between reading the first key and getting the value from the map, but you could beef this code up with a loop, if you wanted.

Or you could add an EntryListener for the map that keeps around a few arbitrary values gleaned from adds and updates (and culled by removals), falling back on the above scheme only if necessary.

Wondering why you want this, though.

--tim



--
You received this message because you are subscribed to the Google Groups "Hazelcast" group.
To post to this group, send email to haze...@googlegroups.com.
To unsubscribe from this group, send email to hazelcast+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/hazelcast?hl=en.


Samuel Fung

unread,
Feb 10, 2012, 11:00:06 AM2/10/12
to Hazelcast
Thanks Tim. This is for concurrent workers to get an arbitrary task
for processing (with the lock API for concurrency control). I don't
use a queue because I want to keep the task objects in the cluster
during processing, remove them only when they are processed
successfully.

Mehmet Dogan

unread,
Feb 10, 2012, 11:59:52 AM2/10/12
to haze...@googlegroups.com

You can implement something like this:

* put keys to a queue
* put tasks to map
* poll the queue to get key
* get task from map using key
* execute task
* finally either remove task from map or offer key to queue back.

Reply all
Reply to author
Forward
0 new messages