Author: olamy
Date: Wed Jul 10 11:20:33 2013
New Revision: 1501724

URL: http://svn.apache.org/r1501724
Log:
[DIRECTMEMORY-131] Using DirectMemory as level 2 cache for Guava Cache
Submitted by Chetan Mehrotra

Added:
    directmemory/trunk/integrations/guava/
    directmemory/trunk/integrations/guava/pom.xml   (with props)
    directmemory/trunk/integrations/guava/src/
    directmemory/trunk/integrations/guava/src/main/
    directmemory/trunk/integrations/guava/src/main/java/
    directmemory/trunk/integrations/guava/src/main/java/org/
    directmemory/trunk/integrations/guava/src/main/java/org/apache/
    directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/
    
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/
    
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/ForwardingListener.java
   (with props)
    
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/OffHeapCache.java
   (with props)
    directmemory/trunk/integrations/guava/src/test/
    directmemory/trunk/integrations/guava/src/test/java/
    directmemory/trunk/integrations/guava/src/test/java/org/
    directmemory/trunk/integrations/guava/src/test/java/org/apache/
    directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/
    
directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/
    
directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/GuavaCacheTest.java
   (with props)
Modified:
    directmemory/trunk/integrations/pom.xml

Added: directmemory/trunk/integrations/guava/pom.xml
URL: 
http://svn.apache.org/viewvc/directmemory/trunk/integrations/guava/pom.xml?rev=1501724&view=auto
==============================================================================
--- directmemory/trunk/integrations/guava/pom.xml (added)
+++ directmemory/trunk/integrations/guava/pom.xml Wed Jul 10 11:20:33 2013
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Licensed to the Apache Software Foundation (ASF) under one
+  ~ or more contributor license agreements.  See the NOTICE file
+  ~ distributed with this work for additional information
+  ~ regarding copyright ownership.  The ASF licenses this file
+  ~ to you 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.
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd";>
+
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.apache.directmemory</groupId>
+        <artifactId>directmemory-integrations</artifactId>
+        <version>0.2-SNAPSHOT</version>
+    </parent>
+
+    <artifactId>directmemory-guava</artifactId>
+    <name>Apache DirectMemory :: Integrations :: Guava</name>
+    <packaging>bundle</packaging>
+    <description>Provides second level cache implementation for Guava 
Cache</description>
+
+    <properties>
+        <osgi.import>
+            org.apache.directmemory*;version="${project.version}",
+            *
+        </osgi.import>
+        <osgi.export>
+            
org.apache.directmemory.guava;version="${project.version}";-noimport:=true,
+        </osgi.export>
+    </properties>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <configuration>
+                    <argLine>-Xmx512m -Xms512m 
-XX:MaxDirectMemorySize=512m</argLine>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+    <dependencies>
+        <!-- DirectMemory Dependency -->
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>directmemory-cache</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.google.guava</groupId>
+            <artifactId>guava</artifactId>
+            <version>14.0.1</version>
+        </dependency>
+
+        <!-- Testing Dependencies -->
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-simple</artifactId>
+        </dependency>
+    </dependencies>
+
+</project>

Propchange: directmemory/trunk/integrations/guava/pom.xml
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: directmemory/trunk/integrations/guava/pom.xml
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/ForwardingListener.java
URL: 
http://svn.apache.org/viewvc/directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/ForwardingListener.java?rev=1501724&view=auto
==============================================================================
--- 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/ForwardingListener.java
 (added)
+++ 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/ForwardingListener.java
 Wed Jul 10 11:20:33 2013
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.directmemory.guava;
+
+import com.google.common.cache.RemovalListener;
+import com.google.common.cache.RemovalNotification;
+
+/**
+ * Listener which forwards the notifications to a delegate. It is used to 
bridge the
+ * Guava Cache with DirectMemory CacheService
+ */
+public class ForwardingListener<K, V> implements RemovalListener<K, V>
+{
+    private RemovalListener<K, V> delegate;
+
+    public ForwardingListener()
+    {
+    }
+
+    public ForwardingListener(RemovalListener<K, V> delegate)
+    {
+        this.delegate = delegate;
+    }
+
+    @Override
+    public void onRemoval(RemovalNotification<K, V> notification)
+    {
+        if (delegate != null)
+        {
+            delegate.onRemoval(notification);
+        }
+    }
+
+    public void setDelegate(RemovalListener<K, V> delegate)
+    {
+        this.delegate = delegate;
+    }
+
+    public static <K, V> ForwardingListener<K, V> newInstance()
+    {
+        return new ForwardingListener<K, V>();
+    }
+
+    public static <K, V> ForwardingListener<K, V> 
newInstance(RemovalListener<K, V> delegate)
+    {
+        return new ForwardingListener<K, V>(delegate);
+    }
+}

Propchange: 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/ForwardingListener.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/ForwardingListener.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/OffHeapCache.java
URL: 
http://svn.apache.org/viewvc/directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/OffHeapCache.java?rev=1501724&view=auto
==============================================================================
--- 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/OffHeapCache.java
 (added)
+++ 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/OffHeapCache.java
 Wed Jul 10 11:20:33 2013
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.directmemory.guava;
+
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.directmemory.cache.CacheService;
+
+import com.google.common.base.Stopwatch;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheStats;
+import com.google.common.cache.ForwardingCache;
+import com.google.common.cache.RemovalCause;
+import com.google.common.cache.RemovalListener;
+import com.google.common.cache.RemovalNotification;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+import static com.google.common.cache.AbstractCache.SimpleStatsCounter;
+import static com.google.common.cache.AbstractCache.StatsCounter;
+
+public class OffHeapCache<K, V> extends 
ForwardingCache.SimpleForwardingCache<K, V>
+        implements RemovalListener<K, V>
+{
+    private final CacheService<K, V> cacheService;
+    private final StatsCounter statsCounter = new SimpleStatsCounter();
+
+
+    public OffHeapCache(CacheService<K, V> cacheService, Cache<K, V> 
primaryCache,
+                        ForwardingListener<K,V> listener)
+    {
+        super(primaryCache);
+        this.cacheService = cacheService;
+        listener.setDelegate(this);
+    }
+
+    @Override
+    public V getIfPresent(Object key)
+    {
+        V result = super.getIfPresent(key);
+        if (result == null)
+        {
+            result = retrieve(key);
+        }
+        return result;
+    }
+
+
+    @Override
+    public V get(final K key, final Callable<? extends V> valueLoader) throws 
ExecutionException
+    {
+        return super.get(key, new Callable<V>()
+        {
+            @Override
+            public V call() throws Exception
+            {
+                //Check in offHeap first
+                V result = retrieve(key);
+
+                //Not found in L2 then load
+                if (result == null)
+                {
+                    result = valueLoader.call();
+                }
+                return result;
+            }
+        });
+    }
+
+    @Override
+    public ImmutableMap<K, V> getAllPresent(Iterable<?> keys)
+    {
+        List<?> list = Lists.newArrayList(keys);
+        ImmutableMap<K, V> result = super.getAllPresent(list);
+
+        //All the requested keys found then no
+        //need to check L2
+        if (result.size() == list.size())
+        {
+            return result;
+        }
+
+        //Look up value from L2
+        Map<K, V> r2 = Maps.newHashMap(result);
+        for (Object key : list)
+        {
+            if (!result.containsKey(key))
+            {
+                V val = retrieve(key);
+                if (val != null)
+                {
+                    //Ideally the signature of method should have been
+                    //getAllPresent(Iterable<? extends K> keys) in that
+                    //case this cast would not have been required
+                    r2.put((K) key, val);
+                }
+            }
+        }
+        return ImmutableMap.copyOf(r2);
+    }
+
+    @Override
+    public void invalidate(Object key)
+    {
+        super.invalidate(key);
+        cacheService.free((K) key);
+    }
+
+    @Override
+    public void invalidateAll(Iterable<?> keys)
+    {
+        super.invalidateAll(keys);
+        for (Object key : keys)
+        {
+            cacheService.free((K) key);
+        }
+    }
+
+    @Override
+    public void invalidateAll()
+    {
+        super.invalidateAll();
+
+        //TODO Problem with calling clear here is that
+        //it invokes clear on MemoryManagerService. If same
+        //MemoryManagerService is shared between multiple cacheService
+        //then it would lead to clearing of all other caches
+        cacheService.clear();
+    }
+
+    @Override
+    public void onRemoval(RemovalNotification<K, V> notification)
+    {
+        if (notification.getCause() == RemovalCause.SIZE)
+        {
+            cacheService.put(notification.getKey(), notification.getValue());
+        }
+    }
+
+    public CacheStats offHeapStats()
+    {
+        return statsCounter.snapshot();
+    }
+
+    protected V retrieve(Object key)
+    {
+        Stopwatch watch = new Stopwatch().start();
+
+        V value = cacheService.retrieve((K) key);
+
+        if (value != null)
+        {
+            
statsCounter.recordLoadSuccess(watch.elapsed(TimeUnit.NANOSECONDS));
+        } else
+        {
+            statsCounter.recordMisses(1);
+        }
+
+        return value;
+    }
+
+}

Propchange: 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/OffHeapCache.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: 
directmemory/trunk/integrations/guava/src/main/java/org/apache/directmemory/guava/OffHeapCache.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Added: 
directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/GuavaCacheTest.java
URL: 
http://svn.apache.org/viewvc/directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/GuavaCacheTest.java?rev=1501724&view=auto
==============================================================================
--- 
directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/GuavaCacheTest.java
 (added)
+++ 
directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/GuavaCacheTest.java
 Wed Jul 10 11:20:33 2013
@@ -0,0 +1,166 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.directmemory.guava;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import org.apache.directmemory.DirectMemory;
+import org.apache.directmemory.cache.CacheService;
+import org.junit.Test;
+
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+public class GuavaCacheTest
+{
+
+    private int maxSize = 100;
+    private int offHeapSize = 20;
+    private Cache<Integer,Integer> primaryCache;
+    private CacheService<Integer, Integer> cacheService;
+    private OffHeapCache<Integer,Integer> cache;
+
+    @Test
+    public void testEviction()
+    {
+        createScenario();
+
+        //No of entries in off heap cache should be equal to the extra entries
+        //over and above the maxSize specified for Cache as those would be 
evicted
+        assertEquals(offHeapSize, cacheService.entries());
+
+        for(int i = 0; i < maxSize + offHeapSize; i++)
+        {
+            Integer ignored = cache.getIfPresent(i);
+        }
+
+        assertEquals(offHeapSize, cache.offHeapStats().loadCount());
+    }
+
+    @Test
+    public void testWithLoader() throws ExecutionException
+    {
+        createScenario();
+
+        Callable<Integer> testCallable = new Callable<Integer>()
+        {
+            @Override
+            public Integer call() throws Exception
+            {
+                return -1;
+            }
+        };
+
+        Integer result = cache.get(1000,testCallable);
+        assertEquals(new Integer(-1),result);
+    }
+
+    @Test
+    public void testInvalidate(){
+        createScenario();
+
+        //Find a key which is actually part of L2
+        Integer key = Iterables.get(cacheService.getMap().keySet(),0);
+
+        cache.invalidate(key);
+
+        assertNull(cacheService.retrieve(key));
+    }
+
+    @Test
+    public void testInvalidateAllWithKeys()
+    {
+        createScenario();
+        Integer keyInL1 = Iterables.get(cache.asMap().keySet(), 0);
+        Integer keyInL2 = Iterables.get(cacheService.getMap().keySet(),0);
+
+        Iterable<Integer> keys = Lists.newArrayList(keyInL1,keyInL2);
+        cache.invalidateAll(keys);
+
+        assertNull(cacheService.retrieve(keyInL2));
+        assertNull(cache.getIfPresent(keyInL1));
+    }
+
+    @Test
+    public void testInvalidateAll()
+    {
+        createScenario();
+        cache.invalidateAll();
+        assertEquals(0,cacheService.entries());
+    }
+
+    @Test
+    public void getAllPresent()
+    {
+        createScenario();
+        Integer keyInL1 = Iterables.get(cache.asMap().keySet(), 0);
+        Integer keyInL2 = Iterables.get(cacheService.getMap().keySet(),0);
+
+        Iterable<Integer> keys = Lists.newArrayList(keyInL1,keyInL2,1000);
+        Map<Integer,Integer> result = cache.getAllPresent(keys);
+
+        assertEquals(2,result.size());
+        assertEquals(result.get(keyInL1),keyInL1);
+        assertEquals(result.get(keyInL2),keyInL2);
+
+        Iterable<Integer> keys2 = Lists.newArrayList(keyInL1);
+        Map<Integer,Integer> result2 = cache.getAllPresent(keys2);
+
+        assertEquals(1,result2.size());
+        assertEquals(result2.get(keyInL1),keyInL1);
+    }
+
+    private void createScenario()
+    {
+        //1. First create a bridge listener
+        ForwardingListener<Integer,Integer> listener = 
ForwardingListener.newInstance();
+
+        //2. Second create the Guava cache with the bridge listener
+        primaryCache =
+                CacheBuilder.newBuilder()
+                        .maximumSize(maxSize)
+                        .removalListener(listener)
+                        .build();
+
+        //3. Create the CacheService
+        cacheService =
+                new DirectMemory<Integer, Integer>().setNumberOfBuffers( 10 )
+                        .setSize(1000)
+                        .setInitialCapacity(10000)
+                        .setConcurrencyLevel(4)
+                        .newCacheService();
+
+        //4. Create the L2 cache with bridge listener and Guava cache
+        cache = new OffHeapCache<Integer, 
Integer>(cacheService,primaryCache,listener);
+
+        //Add number of entries so as to cause overflow and thus trigger 
eviction
+        for(int i = 0; i < maxSize + offHeapSize; i++)
+        {
+            cache.put(i,i);
+        }
+    }
+
+}

Propchange: 
directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/GuavaCacheTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: 
directmemory/trunk/integrations/guava/src/test/java/org/apache/directmemory/guava/GuavaCacheTest.java
------------------------------------------------------------------------------
    svn:keywords = Author Date Id Revision

Modified: directmemory/trunk/integrations/pom.xml
URL: 
http://svn.apache.org/viewvc/directmemory/trunk/integrations/pom.xml?rev=1501724&r1=1501723&r2=1501724&view=diff
==============================================================================
--- directmemory/trunk/integrations/pom.xml (original)
+++ directmemory/trunk/integrations/pom.xml Wed Jul 10 11:20:33 2013
@@ -35,6 +35,7 @@
   <modules>
     <module>solr</module>
     <module>ehcache</module>
+    <module>guava</module>
     <!--
     This integration is not yet ready for a release
     <module>guice</module>


Reply via email to