Search in sources :

Example 1 with IdentifiableValue

use of com.google.appengine.api.memcache.MemcacheService.IdentifiableValue in project Cached-Datastore by Emperorlou.

the class CachedDatastoreService method addToSet_MC.

// //////////////////////////
// QUERY CACHE FUNCTIONS
// Map<String, Map<String,Object>> oldEntityValues = new HashMap<String, Map<String,Object>>();
// 
// /**
// * This is supposed to be called every time an entity is get() from the database or memcache. We need it
// * because we use the "oldEntityValues" to compare field values on put to know which fields were changed
// * and what they were changed to. This is necessary to properly invalidate QueryModels.
// * @param list
// */
// protected void addEntityValuesToOldEntityValuesMap(List<Entity> list)
// {
// for(Entity entity:list)
// addEntityValuesToOldEntityValuesMap(entity);
// }
// 
// protected void addEntityValuesToOldEntityValuesMap(Entity entity)
// {
// if (entity==null) return;
// Map<String,Object> copy = new HashMap<String,Object>();
// copy.putAll(entity.getProperties());
// oldEntityValues.put(entity.getKey().toString(), copy);
// }
// 
// private void reportNewEntity(Entity entity)
// {
// for(String fieldName:entity.getProperties().keySet())
// {
// reportEntityPropertyChange(entity, fieldName);
// }
// }
// 
// private void reportDeletedEntity(Key entity)
// {
// if (queryModelCacheEnabled==false)
// return;
// Map<String,Object> oldValues = oldEntityValues.get(entity.toString());
// if (oldValues==null) throw new IllegalStateException("Entity "+entity+" did not have it's old property values stored.");
// 
// for(String fieldName:oldValues.keySet())
// {
// reportEntityPropertyChange(entity.getKind(), fieldName, oldValues.get(fieldName));
// }
// }
// 
// private void detectAndReportEntityPropertyChange(Entity entity)
// {
// if (queryModelCacheEnabled==false)
// return;
// Map<String,Object> oldValues = oldEntityValues.get(entity.getKey().toString());
// if (oldValues==null) throw new IllegalStateException("Entity "+entity+" did not have it's old property values stored.");
// 
// for(String fieldName:entity.getProperties().keySet())
// {
// if (ObjectUtils.equals(entity.getProperty(fieldName), oldValues)==false)
// reportEntityPropertyChange(entity, fieldName);
// }
// }
// 
// private void reportEntityPropertyChange(String kind, String fieldName, Object value, Object oldValue)
// {
// Set<String> queryModelIds_oldValues = null;
// 
// String qmfKeyOld = QueryModel.generateQueryModelFilterKey(kind, fieldName, oldValue);
// queryModelIds_oldValues = getQueryModelIdsFor(qmfKeyOld);
// 
// String qmfKey = QueryModel.generateQueryModelFilterKey(kind, fieldName, value);
// 
// Set<String> queryModelIds = getQueryModelIdsFor(qmfKey);
// queryModelIds.addAll(queryModelIds_oldValues);
// 
// // Now we're going to delete the queryModels that were invalidated due to this change...
// deleteQueryModels(queryModelIds);
// }
// 
// 
// private void reportEntityPropertyChange(String kind, String fieldName, Object value)
// {
// String qmfKey = QueryModel.generateQueryModelFilterKey(kind, fieldName, value);
// Set<String> queryModelIds = getQueryModelIdsFor(qmfKey);
// 
// // Now we're going to delete the queryModels that were invalidated due to this change...
// deleteQueryModels(queryModelIds);
// }
// 
// 
// private void reportEntityPropertyChange(Entity entity, String fieldName)
// {
// Map<String,Object> oldValues = oldEntityValues.get(entity.getKey().toString());
// 
// 
// String kind = entity.getKind();
// Object value = entity.getProperty(fieldName);
// if (oldValues!=null)
// {
// Object oldValue = oldValues.get(fieldName);
// reportEntityPropertyChange(kind, fieldName, value, oldValue);
// }
// else
// reportEntityPropertyChange(kind, fieldName, value);
// 
// }
// 
// private void deleteQueryModels(Set<String> queryModelIds)
// {
// //		Iterator<String> iterator = queryModelIds.iterator();
// //		while(iterator.hasNext())
// //		{
// //			if (clearedQueryModelIds.contains(iterator.next()))
// //				iterator.remove();
// //		}
// 
// //		if (queryModelIds.size()>0)
// //		{
// mc.deleteAll(queryModelIds);
// //			clearedQueryModelIds.addAll(queryModelIds);
// //		}
// 
// }
// 
// private Set<String> getQueryModelIdsFor(String qmfKey)
// {
// @SuppressWarnings("unchecked")
// Set<String> queryModels = (Set<String>)mc.get(qmfKey);
// if (queryModels==null)
// queryModels = new HashSet<String>();
// 
// return queryModels;
// }
// /////////////////////////////////////////
// Different memcache functions
@SuppressWarnings("unchecked")
public /**
 * @param key
 * @param objectToAdd
 * @return True if the objectToAdd was in fact added to the set and was NOT already there
 */
boolean addToSet_MC(String key, Object objectToAdd) {
    while (true) {
        Set<Object> set;
        IdentifiableValue identifiable = mc.getIdentifiable(key);
        if (identifiable == null)
            set = new HashSet<>();
        else
            set = (Set<Object>) identifiable.getValue();
        // If this object is already in the set, then don't bother adding it and just get out
        if (set.contains(objectToAdd))
            return false;
        set.add(objectToAdd);
        if (identifiable == null) {
            boolean success = mc.put(key, set, null, SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
            if (success)
                return true;
        } else {
            boolean success = mc.putIfUntouched(key, identifiable, set);
            if (success)
                return true;
        }
    }
}
Also used : IdentifiableValue(com.google.appengine.api.memcache.MemcacheService.IdentifiableValue) HashSet(java.util.HashSet) Set(java.util.Set) HashSet(java.util.HashSet)

Example 2 with IdentifiableValue

use of com.google.appengine.api.memcache.MemcacheService.IdentifiableValue in project java-docs-samples by GoogleCloudPlatform.

the class MemcacheConcurrentServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        // ignore the request for favicon.ico
        return;
    }
    String key = "count-concurrent";
    // Using the synchronous cache.
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    // Write this value to cache using getIdentifiable and putIfUntouched.
    for (long delayMs = 1; delayMs < 1000; delayMs *= 2) {
        IdentifiableValue oldValue = syncCache.getIdentifiable(key);
        byte[] newValue = oldValue == null ? BigInteger.valueOf(0).toByteArray() : // newValue depends on old value
        increment((byte[]) oldValue.getValue());
        resp.setContentType("text/plain");
        resp.getWriter().print("Value is " + new BigInteger(newValue).intValue() + "\n");
        if (oldValue == null) {
            // Key doesn't exist. We can safely put it in cache.
            syncCache.put(key, newValue);
            break;
        } else if (syncCache.putIfUntouched(key, oldValue, newValue)) {
            // newValue has been successfully put into cache.
            break;
        } else {
            // Wait a while before trying again, waiting longer on successive loops.
            try {
                Thread.sleep(delayMs);
            } catch (InterruptedException e) {
                throw new ServletException("Error when sleeping", e);
            }
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) MemcacheService(com.google.appengine.api.memcache.MemcacheService) IdentifiableValue(com.google.appengine.api.memcache.MemcacheService.IdentifiableValue) BigInteger(java.math.BigInteger)

Example 3 with IdentifiableValue

use of com.google.appengine.api.memcache.MemcacheService.IdentifiableValue in project Cached-Datastore by Emperorlou.

the class CachedDatastoreService method deleteFromSet_MC.

@SuppressWarnings("unchecked")
public /**
 * @param key
 * @param objectToDelete
 * @return True if the objectToDelete actually needed to be deleted
 */
boolean deleteFromSet_MC(String key, Object objectToDelete) {
    while (true) {
        Set<Object> set;
        IdentifiableValue identifiable = mc.getIdentifiable(key);
        if (identifiable == null)
            return false;
        else
            set = (Set<Object>) identifiable.getValue();
        // If this object is already deleted from the set, then don't bother and just get out
        if (set.contains(objectToDelete) == false)
            return false;
        set.remove(objectToDelete);
        boolean success = mc.putIfUntouched(key, identifiable, set);
        if (success)
            return true;
    }
}
Also used : IdentifiableValue(com.google.appengine.api.memcache.MemcacheService.IdentifiableValue) HashSet(java.util.HashSet) Set(java.util.Set)

Example 4 with IdentifiableValue

use of com.google.appengine.api.memcache.MemcacheService.IdentifiableValue in project Cached-Datastore by Emperorlou.

the class CachedDatastoreService method incrementStat.

protected double incrementStat(String statKey, double amount) {
    while (true) {
        IdentifiableValue identifiable = mc.getIdentifiable(statKey);
        if (identifiable == null) {
            throw new InvalidValueException("Cannot increment a stat that starts from null.");
        } else {
            double newValue = (((Double) identifiable.getValue()) + amount);
            boolean success = mc.putIfUntouched(statKey, identifiable, newValue);
            if (success)
                return newValue;
        }
    }
}
Also used : InvalidValueException(com.google.appengine.api.memcache.InvalidValueException) IdentifiableValue(com.google.appengine.api.memcache.MemcacheService.IdentifiableValue)

Example 5 with IdentifiableValue

use of com.google.appengine.api.memcache.MemcacheService.IdentifiableValue in project community by GoogleCloudPlatform.

the class MemcacheConcurrentServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        // ignore the request for favicon.ico
        return;
    }
    String key = "count-concurrent";
    // Using the synchronous cache.
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    // Write this value to cache using getIdentifiable and putIfUntouched.
    for (long delayMs = 1; delayMs < 1000; delayMs *= 2) {
        IdentifiableValue oldValue = syncCache.getIdentifiable(key);
        byte[] newValue = oldValue == null ? BigInteger.valueOf(0).toByteArray() : // newValue depends on old value
        increment((byte[]) oldValue.getValue());
        resp.setContentType("text/plain");
        resp.getWriter().print("Value is " + new BigInteger(newValue).intValue() + "\n");
        if (oldValue == null) {
            // Key doesn't exist. We can safely put it in cache.
            syncCache.put(key, newValue);
            break;
        } else if (syncCache.putIfUntouched(key, oldValue, newValue)) {
            // newValue has been successfully put into cache.
            break;
        } else {
            // Wait a while before trying again, waiting longer on successive loops.
            try {
                Thread.sleep(delayMs);
            } catch (InterruptedException e) {
                throw new ServletException("Error when sleeping", e);
            }
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) MemcacheService(com.google.appengine.api.memcache.MemcacheService) IdentifiableValue(com.google.appengine.api.memcache.MemcacheService.IdentifiableValue) BigInteger(java.math.BigInteger)

Aggregations

IdentifiableValue (com.google.appengine.api.memcache.MemcacheService.IdentifiableValue)5 MemcacheService (com.google.appengine.api.memcache.MemcacheService)2 BigInteger (java.math.BigInteger)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 ServletException (javax.servlet.ServletException)2 InvalidValueException (com.google.appengine.api.memcache.InvalidValueException)1