Blog

How to check if an object exists in server-side cache

by on April 4, 2015

Previously I wrote about how to store and retrieve objects to and from server-side in-memory cache. Quite often when working with your cache, it is required to check if an object already exists in cache. Backendless provides an API for that function. The code below checks if an object exists in cache, and if not, it places it in there and then runs the existence check again.

Asynchronous API (Android and Plain Java):

checkInCacheSync();
addToCachetSync();
checkInCacheSync();
private static void checkInCacheSync()
{
    boolean containsKey = Backendless.Cache.contains( "myobject" );
    System.out.println( "Cache contains key 'mypbject' - " + containsKey );
}
private static void addToCachetSync()
{
    Person p = new Person();
    p.name = "James Bond";
    p.age = 42;
    Backendless.Cache.put( "myobject", p );
}

Synchronous API (Plain Java only):

private static void checkInCacheAsync()
{
    Backendless.Cache.contains( "myobject", new AsyncCallback<Boolean>()
    {
        @Override
        public void handleResponse( Boolean containsKey )
        {
            System.out.println( "Cache contains key 'mypbject' - " + containsKey );
        }
        @Override
        public void handleFault( BackendlessFault backendlessFault )
        {
            System.out.println( "Server reported an error " + backendlessFault.getMessage() );
        }
    } );
}
private static void addToCacheAsync()
{
    Person p = new Person();
    p.name = "James Bond";
    p.age = 42;
    Backendless.Cache.put( "myobject", p, new AsyncCallback<Object>()
    {
        @Override
        public void handleResponse( Object o )
        {
            System.out.println( "Object has been placed into cache" );
        }
        @Override
        public void handleFault( BackendlessFault backendlessFault )
        {
            System.out.println( "Server reported an error " + backendlessFault.getMessage() );
        }
    } );
}

The first time you run the code it produces the following output:

Cache contains key 'mypbject' - false
Object has been placed into cache
Cache contains key 'mypbject' - true