コード例 #1
0
ファイル: DiskStoreTest.java プロジェクト: GeomaticM/ehcache
  /**
   * This test is designed to be used with a profiler to explore the ways in which DiskStore uses
   * memory. It does not do much on its own.
   */
  @Test
  public void testOutOfMemoryErrorOnOverflowToDisk() throws Exception {

    // Set size so the second element overflows to disk.
    Cache cache =
        new Cache(
            "test",
            1000,
            MemoryStoreEvictionPolicy.LRU,
            true,
            null,
            false,
            500,
            500,
            false,
            1,
            null);
    manager.addCache(cache);
    int i = 0;

    Random random = new Random();
    for (; i < 5500; i++) {
      byte[] bytes = new byte[10000];
      random.nextBytes(bytes);
      cache.put(new Element("" + i, bytes));
    }
    LOG.info("Elements written: " + i);
    // Thread.sleep(100000);
  }
コード例 #2
0
 public void drawItem(int ind, Graphics g) {
   Rectangle rect = getItemRect(ind);
   rect.setX(rect.getX() + 4);
   rect.setWidth(rect.getWidth() - 8);
   Item item = inven.items.get(ind);
   int number = inven.getItemAmount(item);
   Sprite.drawSpriteFrame(
       Cache.getImage("IconSet.png"),
       g,
       x + 16 + rect.getX() + 8,
       y + 16 + rect.getY(),
       16,
       item.getIndex(),
       24,
       24);
   Cache.getFont().drawString(x + 24 + 16 + rect.getX() + 8, y + 16 + rect.getY(), item.getName());
   Cache.getFont()
       .drawString(
           x
               + (rect.getWidth())
               + rect.getX()
               + 8
               - Cache.getFont().getWidth(String.format(":%2d", number)),
           y + 16 + rect.getY(),
           String.format(":%2d", number));
 }
コード例 #3
0
 public void putObect(String skey, Object value) {
   if (skey == null) return;
   if (cache.contain(skey)) return;
   cache.put(skey, new CacheableWrapper(skey, value));
   Debug.logVerbose(
       "[JdonFramework]<-cache->save cache: " + skey + ", cache size:" + cache.size(), module);
 }
コード例 #4
0
ファイル: TestCache.java プロジェクト: hdadler/sensetrace-src
    public void testCacheSimpleReturn(String type) {

      int size = 100;
      // this test does not fill the cache
      Cache c1 = CacheManager.createCache(type, "c1", size);

      String k1 = "one";
      String k2 = k1;
      String k3 = k2;
      Integer v1 = new Integer(-1);
      Integer v2 = v1;
      Integer v3 = v2;
      c1.put(k1, v1);

      for (int i = 0; i < size; i++) {
        k1 = k2;
        v1 = v2;
        Object o = c1.get(k1);
        assertTrue("expected a hit", o != null);
        assertEquals("should be the expected object", o, v1);
        k2 = k3;
        v2 = v3;
        o = c1.get(k2);
        assertTrue("expected a hit", o != null);
        assertEquals("should be the expected object", o, v2);

        k3 = "T" + i;
        v3 = new Integer(i);
        c1.put(k3, v3);
      }
    }
コード例 #5
0
 /**
  * 如果该cache已经存在,则不再创建并返回已有cache
  *
  * @param groupId 如果cache和账号无关,置为null,创建全局cache
  * @param expireTime 小于0(比如-1)则忽略超时
  */
 public <K, V> Cache<K, V> createPersistedLruExpireCache(
     String groupId, CacheKey cacheID, int capacity, long expireTime) {
   if (groupId == null) {
     groupId = GLOBAL_CACHE_GROUP_ID;
   }
   Map<CacheKey, Cache> caches;
   synchronized (cacheMap) {
     caches = cacheMap.get(groupId);
     if (caches == null) {
       caches = new ConcurrentHashMap<>();
       cacheMap.put(groupId, caches);
       LogUtil.w(sTAG, groupId + " caches not exist, warning.");
     }
   }
   Cache<K, V> cache = caches.get(cacheID);
   if (cache == null) {
     try {
       cache = new PersistedLruExpireCache(cacheID.getKey(), groupId, capacity, 1, expireTime);
       caches.put(cacheID, cache);
     } catch (IOException e) {
       LogUtil.e(sTAG, e.getMessage(), e);
     }
   } else {
     cache.setCapacity(capacity);
   }
   return cache;
 }
コード例 #6
0
 public void printAllCaches() {
   System.out.println("All Caches begin");
   for (Cache tmp : caches) {
     tmp.printCache();
   }
   System.out.println("All Caches end");
 }
コード例 #7
0
ファイル: Sentence.java プロジェクト: cnspica/textrank
  /** Main processing per sentence. */
  public void mapTokens(final LanguageModel lang, final Cache cache, final Graph graph)
      throws Exception {
    token_list = lang.tokenizeSentence(text);

    // determine an MD5 signature for this sentence

    cache.md_sent.reset();

    for (int i = 0; i < token_list.length; i++) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("token: " + token_list[i]);
      }

      cache.md_sent.update(token_list[i].getBytes());
    }

    md5_hash = hexFormat(cache.md_sent.digest());

    // use MD5 hash to lookup sentence in the cache

    final Sentence cache_hit = cache.get(md5_hash);

    if (cache_hit == null) {
      // add another scanned sentence to the cache

      cache.put(md5_hash, this);

      // scan each token to determine part-of-speech

      final String[] tag_list = lang.tagTokens(token_list);

      // create nodes for the graph

      Node last_node = null;
      node_list = new Node[token_list.length];

      for (int i = 0; i < token_list.length; i++) {
        final String pos = tag_list[i];

        if (LOG.isDebugEnabled()) {
          LOG.debug("token: " + token_list[i] + " pos tag: " + pos);
        }

        if (lang.isRelevant(pos)) {
          final String key = lang.getNodeKey(token_list[i], pos);
          final KeyWord value = new KeyWord(token_list[i], pos);
          final Node n = Node.buildNode(graph, key, value);

          // emit nodes to construct the graph

          if (last_node != null) {
            n.connect(last_node);
          }

          last_node = n;
          node_list[i] = n;
        }
      }
    }
  }
コード例 #8
0
ファイル: CacheTest.java プロジェクト: elmarouani/joshua
  @Test
  public void test() {

    Cache<String, Integer> cache = new Cache<String, Integer>(5);

    cache.put("a", 1);
    cache.put("b", 2);
    cache.put("c", 3);
    cache.put("d", 4);
    cache.put("e", 5);

    Assert.assertTrue(cache.containsKey("a"));
    Assert.assertTrue(cache.containsKey("b"));
    Assert.assertTrue(cache.containsKey("c"));
    Assert.assertTrue(cache.containsKey("d"));
    Assert.assertTrue(cache.containsKey("e"));

    // Access the "a" element in the cache
    cache.get("a");

    // Now add a new element that exceeds the capacity of the cache
    cache.put("f", 6);

    Assert.assertTrue(cache.containsKey("a"));
  }
コード例 #9
0
  public List<ReferenceType> visibleClasses() {
    List<ReferenceType> classes = null;
    try {
      Cache local = (Cache) getCache();

      if (local != null) {
        classes = local.visibleClasses;
      }
      if (classes == null) {
        JDWP.ClassLoaderReference.VisibleClasses.ClassInfo[] jdwpClasses =
            JDWP.ClassLoaderReference.VisibleClasses.process(vm, this).classes;
        classes = new ArrayList<ReferenceType>(jdwpClasses.length);
        for (int i = 0; i < jdwpClasses.length; ++i) {
          classes.add(vm.referenceType(jdwpClasses[i].typeID, jdwpClasses[i].refTypeTag));
        }
        classes = Collections.unmodifiableList(classes);
        if (local != null) {
          local.visibleClasses = classes;
          if ((vm.traceFlags & VirtualMachine.TRACE_OBJREFS) != 0) {
            vm.printTrace(
                description()
                    + " temporarily caching visible classes (count = "
                    + classes.size()
                    + ")");
          }
        }
      }
    } catch (JDWPException exc) {
      throw exc.toJDIException();
    }
    return classes;
  }
コード例 #10
0
  /** @see de.willuhn.jameica.hbci.rmi.HibiscusTransfer#getKonto() */
  public Konto getKonto() throws RemoteException {
    Integer i = (Integer) super.getAttribute("konto_id");
    if (i == null) return null; // Kein Konto zugeordnet

    Cache cache = Cache.get(Konto.class, true);
    return (Konto) cache.get(i);
  }
コード例 #11
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    Cache cache;

    if (convertView == null) {
      convertView = LayoutInflater.from(context).inflate(R.layout.item_horas_forecast, null);
      cache = new Cache();
      cache.tvHora = (TextView) convertView.findViewById(R.id.tvHora);
      cache.ivIconoHora = (ImageView) convertView.findViewById(R.id.ivIconoHora);
      cache.tvResumen = (TextView) convertView.findViewById(R.id.tvResumenHora);
      cache.tvTemperatura = (TextView) convertView.findViewById(R.id.tvTemperaturaHora);

      convertView.setTag(cache);
    } else {
      cache = (Cache) convertView.getTag();
    }

    Hora hora = horas[position];
    cache.tvHora.setText(hora.obtenerHora());
    cache.ivIconoHora.setImageResource(hora.getImagenId());
    cache.tvResumen.setText(hora.getResumen());
    cache.tvTemperatura.setText(hora.getTemperatura() + "");

    return convertView;
  }
コード例 #12
0
ファイル: CacheTQ.java プロジェクト: pologood/Lealone
 public CacheObject find(int pos) {
   CacheObject r = lru.find(pos);
   if (r == null) {
     r = fifo.find(pos);
   }
   return r;
 }
コード例 #13
0
ファイル: ModifiedSelector.java プロジェクト: neilgmiller/ant
  /**
   * The business logic of this selector for use as ResourceSelector of FileSelector.
   *
   * @param basedir as described in BaseExtendSelector
   * @param filename as described in BaseExtendSelector
   * @param cacheKey the name for the key for storing the hashvalue
   * @return
   */
  private boolean isSelected(File basedir, String filename, String cacheKey) {
    validate();
    File f = new File(basedir, filename);

    // You can not compute a value for a directory
    if (f.isDirectory()) {
      return selectDirectories;
    }

    // Get the values and do the comparison
    String cachedValue = String.valueOf(cache.get(f.getAbsolutePath()));
    String newValue = algorithm.getValue(f);

    boolean rv = (comparator.compare(cachedValue, newValue) != 0);

    // Maybe update the cache
    if (update && rv) {
      cache.put(f.getAbsolutePath(), newValue);
      setModified(getModified() + 1);
      if (!getDelayUpdate()) {
        saveCache();
      }
    }

    return rv;
  }
コード例 #14
0
ファイル: DiskStoreTest.java プロジェクト: GeomaticM/ehcache
  /** Any disk store with an auto generated random directory should not be able to be loaded. */
  @Test
  public void testCannotLoadPersistentStoreWithAutoDir() throws IOException, InterruptedException {
    // initialise
    String cacheName = "testPersistent";
    Store diskStore = createAutoPersistentDiskStore(cacheName);
    diskStore.removeAll();

    for (int i = 0; i < 100; i++) {
      byte[] data = new byte[1024];
      diskStore.put(new Element("key" + (i + 100), data));
    }
    waitLonger();
    assertEquals(ELEMENT_ON_DISK_SIZE * 100, diskStore.getOnDiskSizeInBytes());
    assertEquals(100, diskStore.getSize());
    manager2.removeCache(cacheName);
    Thread.sleep(1000);

    Cache cache = new Cache(cacheName, 10000, true, false, 5, 1, true, 600);
    manager2.addCache(cache);

    File dataFile = ((DiskPersistentStore) diskStore).getDataFile();
    assertTrue("File exists", dataFile.exists());
    assertEquals(0, dataFile.length());
    assertEquals(0, cache.getSize());
    manager.removeCache(cacheName);
    assertTrue("File exists", dataFile.exists());
    assertEquals(0, dataFile.length());
  }
コード例 #15
0
 @Override
 public <T extends ObjectType> PrismObject<T> getObject(
     Class<T> type,
     String oid,
     Collection<SelectorOptions<GetOperationOptions>> options,
     OperationResult parentResult)
     throws ObjectNotFoundException, SchemaException {
   if (!isCacheable(type) || !nullOrHarmlessOptions(options)) {
     log("Cache: PASS {} ({})", oid, type.getSimpleName());
     return repository.getObject(type, oid, options, parentResult);
   }
   Cache cache = getCache();
   if (cache == null) {
     log("Cache: NULL {} ({})", oid, type.getSimpleName());
   } else {
     PrismObject<T> object = (PrismObject) cache.getObject(oid);
     if (object != null) {
       // TODO: result?
       log("Cache: HIT {} ({})", oid, type.getSimpleName());
       return object.clone();
     }
     log("Cache: MISS {} ({})", oid, type.getSimpleName());
   }
   PrismObject<T> object = repository.getObject(type, oid, null, parentResult);
   cacheObject(cache, object);
   return object;
 }
コード例 #16
0
ファイル: XACacheTest.java プロジェクト: GeomaticM/ehcache
  // TODO: Re-enabled when we can have XA not-clusted.
  public void xtestXACache() throws IllegalStateException, SecurityException, SystemException {
    Cache cache = createTestCache();
    TransactionManager txnManager = cache.getTransactionManagerLookup().getTransactionManager();
    Element element1 = new Element("key1", "value1");
    Element element2 = new Element("key1", "value1");
    CyclicBarrier barrier1 = new CyclicBarrier(2);
    CyclicBarrier barrier2 = new CyclicBarrier(2);
    CyclicBarrier txnBarrier = new CyclicBarrier(2);

    Transaction1Thread thread1 =
        new Transaction1Thread(
            cache, element1, element2, txnManager, barrier1, barrier2, txnBarrier);
    Transaction2Thread thread2 =
        new Transaction2Thread(
            cache, element1, element2, txnManager, barrier1, barrier2, txnBarrier);
    thread1.start();
    thread2.start();
    try {
      thread1.join();
      thread2.join();

    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #17
0
  @Override
  public <T extends ObjectType> SearchResultList<PrismObject<T>> searchObjects(
      Class<T> type,
      ObjectQuery query,
      Collection<SelectorOptions<GetOperationOptions>> options,
      OperationResult parentResult)
      throws SchemaException {
    if (!isCacheable(type) || !nullOrHarmlessOptions(options)) {
      log("Cache: PASS ({})", type.getSimpleName());
      return repository.searchObjects(type, query, options, parentResult);
    }
    Cache cache = getCache();
    if (cache == null) {
      log("Cache: NULL ({})", type.getSimpleName());
    } else {
      SearchResultList queryResult = cache.getQueryResult(type, query, prismContext);
      if (queryResult != null) {
        log("Cache: HIT {} ({})", query, type.getSimpleName());
        return queryResult.clone();
      }
      log("Cache: MISS {} ({})", query, type.getSimpleName());
    }

    // Cannot satisfy from cache, pass down to repository
    SearchResultList<PrismObject<T>> objects =
        repository.searchObjects(type, query, options, parentResult);
    if (cache != null && options == null) {
      for (PrismObject<T> object : objects) {
        cacheObject(cache, object);
      }
      cache.putQueryResult(type, query, objects, prismContext);
    }
    return objects;
  }
コード例 #18
0
  /**
   * Method declaration
   *
   * @throws SQLException
   */
  void checkpoint(boolean defrag) throws SQLException {

    if (defrag) {
      ArrayList rootsArray = cCache.defrag();

      for (int i = 0; i < rootsArray.size(); i++) {
        int[] roots = (int[]) rootsArray.get(i);

        if (roots != null) {
          Trace.printSystemOut(org.hsqldb.lib.StringUtil.getList(roots, " ", ""));
        }
      }

      DataFileDefrag2.updateTableIndexRoots(dDatabase.getTables(), rootsArray);
    }

    close(false);
    pProperties.setProperty("modified", "yes");
    pProperties.save();

    if (cCache != null) {
      cCache.open(false);
    }

    reopenAllTextCaches();
    openScript();
  }
コード例 #19
0
ファイル: ObjectLoader.java プロジェクト: ProtoScape/Client
 final ObjectDefinition getObject(int i, int i_0_) {
   anInt3351++;
   ObjectDefinition class51;
   synchronized (aClass60_3350) {
     class51 = (ObjectDefinition) aClass60_3350.method583((long) i_0_, i ^ 0x32);
   }
   if (class51 != null) return class51;
   byte[] is;
   synchronized (aClass45_3343) {
     is =
         aClass45_3343.getChildArchive(
             Class239_Sub29.method1850(i_0_, 111), Class5_Sub1.method185(i_0_, (byte) -90));
   }
   class51 = new ObjectDefinition();
   ((ObjectDefinition) class51).anInt941 = i_0_;
   ((ObjectDefinition) class51).aClass263_933 = this;
   if (is != null) class51.method479((byte) 0, new ByteBuffer(is));
   class51.method488(-105);
   if (i != 0) ((ObjectLoader) this).aClass60_3361 = null;
   if (!((ObjectLoader) this).aBoolean3359 && ((ObjectDefinition) class51).aBoolean942) {
     ((ObjectDefinition) class51).anIntArray917 = null;
     ((ObjectDefinition) class51).aStringArray913 = null;
   }
   if (((ObjectDefinition) class51).aBoolean876) {
     ((ObjectDefinition) class51).anInt920 = 0;
     ((ObjectDefinition) class51).aBoolean896 = false;
   }
   synchronized (aClass60_3350) {
     aClass60_3350.method582(class51, (long) i_0_, (byte) -109);
   }
   return class51;
 }
コード例 #20
0
ファイル: CacheManager.java プロジェクト: wanghl/Roller
  /** Flush a single cache. */
  public static void clear(String cacheId) {

    Cache cache = (Cache) caches.get(cacheId);
    if (cache != null) {
      cache.clear();
    }
  }
  @Test
  public void testMaxCapacity() throws Exception {

    ListenableFuture<String> val =
        cache.apply(
            "Key1",
            () -> {
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              return "key1";
            },
            executorService);

    ListenableFuture<String> val2 =
        cache.apply(
            "key2",
            () -> {
              try {
                Thread.sleep(500);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              return "key2";
            },
            executorService);

    ListenableFuture<String> val3 =
        cache.apply(
            "key3",
            () -> {
              try {
                Thread.sleep(500);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              return "key3";
            },
            executorService);

    ListenableFuture<String> val4 =
        cache.apply(
            "key1",
            () -> {
              try {
                Thread.sleep(500);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              return "key_new";
            },
            executorService);

    assertEquals("Value should be key1", "key1", this.awaitForFutureOrElse(val, null));
    assertEquals("Value should be key2", "key2", this.awaitForFutureOrElse(val2, null));
    assertEquals("Value should be key3", "key3", this.awaitForFutureOrElse(val3, null));
    assertEquals("Value should be key1", "key_new", this.awaitForFutureOrElse(val4, null));
  }
コード例 #22
0
ファイル: IndexCache.java プロジェクト: aldaris/opensso
  private void cache(String dn, Set<String> indexes, Cache cache) {
    rwlock.writeLock().lock();
    String cacheName = cacheToName.get(cache);

    try {
      for (String s : indexes) {
        Set<String> setDNs = (Set<String>) cache.get(s);
        if (setDNs == null) {
          setDNs = new HashSet<String>();
          cache.put(s, setDNs);
          setDNs.add(dn);
        } else {
          if (!CacheTaboo.isTaboo(cacheName, s)) {
            if (setDNs.size() >= CACHE_BUCKET_LIMIT) {
              CacheTaboo.taboo(cacheName, s);
              cache.remove(s);
            } else {
              setDNs.add(dn);
            }
          }
        }
      }
    } finally {
      rwlock.writeLock().unlock();
    }
  }
コード例 #23
0
  @Override
  @Nullable
  public Entry get(@Nonnull Key key) {
    if (cache != null) {
      synchronized (this) {
        final Entry entry = cache.get(key);
        if (entry == null) {
          Billing.debug(TAG, "Key=" + key + " is not in the cache");
          return null;
        }
        final long now = currentTimeMillis();
        if (now >= entry.expiresAt) {
          Billing.debug(
              TAG,
              "Key="
                  + key
                  + " is in the cache but was expired at "
                  + entry.expiresAt
                  + ", now is "
                  + now);
          cache.remove(key);
          return null;
        }
        Billing.debug(TAG, "Key=" + key + " is in the cache");
        return entry;
      }
    }

    return null;
  }
コード例 #24
0
ファイル: StoreAppend.java プロジェクト: dave68/mapdb
  @Override
  public void close() {
    if (closed) return;
    commitLock.lock();
    try {
      if (closed) return;

      if (isSnapshot) {
        snapshots.remove(this);
        return;
      }

      vol.sync();
      vol.close();
      indexTable.close();

      if (caches != null) {
        for (Cache c : caches) {
          c.close();
        }
        Arrays.fill(caches, null);
      }
      closed = true;
    } finally {
      commitLock.unlock();
    }
  }
コード例 #25
0
  /** Internal method to read an existing pkg from the database */
  synchronized AreaOfInterest read(String id, Connection conn) throws Exception {
    // check cache
    AreaOfInterest pkg = (AreaOfInterest) cache.get(id);
    if (pkg != null) {
      return pkg;
    }
    // pull from database and populate the object
    PreparedStatement pstmt =
        conn.prepareStatement("SELECT * FROM AreaOfInterest WHERE guid LIKE ?");
    pstmt.setString(1, id);
    ResultSet rs = pstmt.executeQuery();
    pkg = new AreaOfInterest(id);
    if (rs.next()) {
      pkg.setObjectAlreadyInDB(true);
      pkg.setDirty(false);
      pkg.setDescription(rs.getString(2));

    } else {
      throw new DataException("bad AreaOfInterest read");
    }
    pkg.setDirty(false);
    pkg.setObjectAlreadyInDB(true);
    // put in the cache

    cache.put(pkg.getId(), pkg);

    // return the object

    return pkg;
  } // read
コード例 #26
0
 private void sendFailure(String url) {
   Cache cache2 = cache.get(url);
   String body = cache2.getFailureBody();
   HttpResponseStatus status = cache2.getStatus();
   HttpBadResponse resp = new HttpBadResponse(url, status, body);
   promise.addResponse(resp);
   cache.clear();
 }
コード例 #27
0
 @Override
 public Cache<K, V> newInstance() {
   Cache<K, V> cache = new HyBridLRUCache<K, V>(maxEntriesInMemory, maxEntries, fileName);
   cache.register(converter);
   cache.initialize();
   cache.start();
   return cache;
 }
コード例 #28
0
ファイル: CacheManager.java プロジェクト: SiteView/ECC8_JAVA
 // 载入缓存信息
 public static void putCacheInfo(String key, Cache obj, long dt, boolean expired) {
   Cache cache = new Cache();
   cache.setKey(key);
   cache.setTimeOut(dt + System.currentTimeMillis()); // 设置多久后更新缓存
   cache.setValue(obj);
   cache.setExpired(expired); // 缓存默认载入时,终止状态为FALSE
   cacheMap.put(key, cache);
 }
コード例 #29
0
ファイル: CacheManager.java プロジェクト: SiteView/ECC8_JAVA
 // 重写载入缓存信息方法
 public static void putCacheInfo(String key, Cache obj, long dt) {
   Cache cache = new Cache();
   cache.setKey(key);
   cache.setTimeOut(dt + System.currentTimeMillis());
   cache.setValue(obj);
   cache.setExpired(false);
   cacheMap.put(key, cache);
 }
コード例 #30
0
ファイル: CacheTest.java プロジェクト: alexrios/memcached
  @Test
  public void removeTest() throws InterruptedException {
    cache.set("foo", tenSeconds, "bar");
    assertEquals("bar", cache.get("foo"));

    cache.delete("foo");
    assertEquals(null, cache.get("foo"));
  }