Apache VFS Files Cache implemented using Guava CacheBuilder

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
 
import java.util.concurrent.TimeUnit;
 
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.cache.AbstractFilesCache;
 
class GuavaFilesCache extends AbstractFilesCache
{
   static class CacheOfFilesystem
   {
      private final Cache<FileName, FileObject> files = CacheBuilder.newBuilder()
               .concurrencyLevel(4)
               .maximumSize(10000)
               .expireAfterWrite(10, TimeUnit.MINUTES)
               .build();
 
      public FileObject getFile(final FileName name)
      {
         return files.getIfPresent(name);
      }
 
      public void putFile(final FileObject file)
      {
         files.put(file.getName(), file);
      }
 
      public boolean putFileIfAbsent(final FileObject file)
      {
         return files.asMap().putIfAbsent(file.getName(), file) == null;
      }
 
      public void removeFile(final FileName name)
      {
         files.invalidate(name);
      }
   }
 
   private final LoadingCache<FileSystem, CacheOfFilesystem> filesystems = CacheBuilder.newBuilder()
         .concurrencyLevel(4)
         .maximumSize(10000)
         .expireAfterWrite(10, TimeUnit.MINUTES)
         .build(new CacheLoader<FileSystem, CacheOfFilesystem>(){
            @Override
            public CacheOfFilesystem load(@SuppressWarnings("unused") final FileSystem key) throws Exception
            {
               return new CacheOfFilesystem();
            }});
 
   @Override
   public void putFile(final FileObject file)
   {
      filesystems.getUnchecked(file.getFileSystem()).putFile(file);
   }
 
   @Override
   public boolean putFileIfAbsent(final FileObject file)
   {
      return filesystems.getUnchecked(file.getFileSystem()).putFileIfAbsent(file);
   }
 
   @Override
   public FileObject getFile(final FileSystem filesystem, final FileName name)
   {
      return filesystems.getUnchecked(filesystem).getFile(name);
   }
 
   @Override
   public void clear(final FileSystem filesystem)
   {
      filesystems.invalidate(filesystem);
   }
 
   @Override
   public void removeFile(final FileSystem filesystem, final FileName name)
   {
      filesystems.getUnchecked(filesystem).removeFile(name);
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *