com.rationaldevelopers.oss.service.CacheService.java Source code

Java tutorial

Introduction

Here is the source code for com.rationaldevelopers.oss.service.CacheService.java

Source

/*
 * Copyright 2016 Ryan McGuinness
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.rationaldevelopers.oss.service;

import com.hazelcast.core.ILock;
import com.hazelcast.core.IMap;
import com.rationaldevelopers.oss.domain.SimpleItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.StreamSupport;

/**
 * @author Ryan McGuinness [rmcguinness@walmartlabs.com]
 * @version 8/31/16
 */
@Service
public class CacheService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CacheService.class);
    @Autowired
    private SimpleItemService simpleItemService;

    @Autowired
    private IMap<String, SimpleItem> cache;

    @Autowired
    private ILock lock;

    @PostConstruct
    public void initializeCache() {
        trueUpCache();
    }

    public void update(SimpleItem simpleItem) {
        if (simpleItem != null && simpleItem.getSid() != null) {
            cache.put(simpleItem.getSid(), simpleItem, 2, TimeUnit.MINUTES);
        }
    }

    public void clear() {
        if (!lock.isLocked()) {
            try {
                lock.lock();
                cache.clear();
            } finally {
                lock.unlock();
            }
        } else {
            LOGGER.warn("Unable to clear cache as it was being updated");
        }
    }

    @Scheduled(fixedRate = 60000)
    public void trueUpCache() {
        if (!lock.isLocked()) {
            lock.lock();
            try {
                LOGGER.info("Running Timed Task");
                final Iterable<SimpleItem> all = simpleItemService.findAll();
                final AtomicInteger itemsUpdated = new AtomicInteger(0);
                StreamSupport.stream(all.spliterator(), false).filter(i -> !cache.containsKey(i.getSid())
                        || cache.containsKey(i.getSid()) && !cache.get(i.getSid()).equals(i)).forEach(i -> {
                            cache.put(i.getSid(), i);
                            itemsUpdated.incrementAndGet();
                        });
                LOGGER.info("Total Items Updated: {}", itemsUpdated.get());
            } finally {
                lock.unlock();
            }
        }
    }
}