Example usage for org.springframework.cache Cache putIfAbsent

List of usage examples for org.springframework.cache Cache putIfAbsent

Introduction

In this page you can find the example usage for org.springframework.cache Cache putIfAbsent.

Prototype

@Nullable
default ValueWrapper putIfAbsent(Object key, @Nullable Object value) 

Source Link

Document

Atomically associate the specified value with the specified key in this cache if it is not set already.

Usage

From source file:org.thingsboard.server.dao.entityview.EntityViewServiceImpl.java

@Override
public ListenableFuture<List<EntityView>> findEntityViewsByTenantIdAndEntityIdAsync(TenantId tenantId,
        EntityId entityId) {/*w  ww .j a va 2  s.com*/
    log.trace("Executing findEntityViewsByTenantIdAndEntityIdAsync, tenantId [{}], entityId [{}]", tenantId,
            entityId);
    validateId(tenantId, INCORRECT_TENANT_ID + tenantId);
    validateId(entityId.getId(), "Incorrect entityId" + entityId);

    List<Object> tenantIdAndEntityId = new ArrayList<>();
    tenantIdAndEntityId.add(tenantId);
    tenantIdAndEntityId.add(entityId);

    Cache cache = cacheManager.getCache(ENTITY_VIEW_CACHE);
    List<EntityView> fromCache = cache.get(tenantIdAndEntityId, List.class);
    if (fromCache != null) {
        return Futures.immediateFuture(fromCache);
    } else {
        ListenableFuture<List<EntityView>> entityViewsFuture = entityViewDao
                .findEntityViewsByTenantIdAndEntityIdAsync(tenantId.getId(), entityId.getId());
        Futures.addCallback(entityViewsFuture, new FutureCallback<List<EntityView>>() {
            @Override
            public void onSuccess(@Nullable List<EntityView> result) {
                cache.putIfAbsent(tenantIdAndEntityId, result);
            }

            @Override
            public void onFailure(Throwable t) {
                log.error("Error while finding entity views by tenantId and entityId", t);
            }
        });
        return entityViewsFuture;
    }
}