Java tutorial
/** * Copyright Suchkov Dmitrii * * 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.codio.collab.core; import com.codio.collab.core.redis.RedisDriver; import com.codio.collab.core.types.CollabDocument; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class DocumentFactory { private static final Logger LOG = LoggerFactory.getLogger(DocumentFactory.class); private RedisDriver redisDriver; private ConcurrentMap<String, CollabDocument> documents = new ConcurrentHashMap<String, CollabDocument>(); private ConcurrentMap<String, DateTime> accessTime = new ConcurrentHashMap<String, DateTime>(); public DocumentFactory() { class DelayReconnectTask extends TimerTask { public DelayReconnectTask() { } @Override public void run() { try { List<String> cleanup = new ArrayList<String>(); for (ConcurrentMap.Entry<String, DateTime> entry : accessTime.entrySet()) { if (entry.getValue().isBeforeNow()) { final String key = entry.getKey(); LOG.debug("cleanup {}", key); documents.remove(key); cleanup.add(key); } } for (String id : cleanup) { accessTime.remove(id); } } catch (Exception ex) { } } } Timer timer = new Timer(); timer.scheduleAtFixedRate(new DelayReconnectTask(), 1000, 60000); } private String docId(final String collection, final String document) { return collection + "/" + document; } public CollabDocument getDocument(final String collection, final String document) { final String docId = docId(collection, document); accessTime.put(docId, DateTime.now().plusMinutes(10)); if (documents.containsKey(docId)) { return documents.get(docId); } CollabDocument doc = getRedisDriver().getDocument(collection, document); documents.put(docId, doc); return doc; } public RedisDriver getRedisDriver() { return redisDriver; } public void setRedisDriver(RedisDriver redisDriver) { this.redisDriver = redisDriver; } }