Ejemplo n.º 1
0
  public MethodInvoker getMethod(Class<?> clazz, String name, Class<?>[] parameters) {
    MethodDescriptor mDescriptor = new MethodDescriptor(name, clazz, parameters);
    MethodInvoker mInvoker = null;
    List<Method> acceptableMethods = null;
    LRUCache<MethodDescriptor, MethodInvoker> cache = cacheHolder.get();

    mInvoker = cache.get(mDescriptor);

    if (mInvoker == null) {
      acceptableMethods = getMethodsByNameAndLength(clazz, name, parameters.length);

      if (acceptableMethods.size() == 1) {
        mInvoker = MethodInvoker.buildInvoker(acceptableMethods.get(0), parameters);
      } else {
        mInvoker = getBestMethod(acceptableMethods, parameters);
      }

      if (mInvoker != null && mInvoker.getCost() != -1) {
        cache.put(mDescriptor, mInvoker);
      } else {
        String errorMessage =
            "Method " + name + "(" + Arrays.toString(parameters) + ") does not exist";
        logger.log(Level.WARNING, errorMessage);
        throw new Py4JException(errorMessage);
      }
    }

    return mInvoker;
  }
Ejemplo n.º 2
0
  /**
   * Method to remove the user profile from cache.
   *
   * @param userId
   */
  protected void removeProfileDataFromCache(String userId) throws ProfileServiceException {
    if (logger.isLoggable(Level.FINEST)) {
      logger.entering(sourceClass, "removeProfileDataFromCache", userId);
    }
    if (isEmail(userId)) {
      String key;
      Set<String> keys = lruCache.getKeySet();
      Iterator<String> itr = keys.iterator();
      while (itr.hasNext()) {
        key = itr.next();
        Document data = lruCache.get(key);
        // check if email in profile object is same as input userId
        String email = "";
        try {
          email = DOMUtil.value(data, Profile.xpathMap.get("email"));
        } catch (XMLException e) {
          continue;
        }

        // cache hit
        if (StringUtil.equalsIgnoreCase(email, userId)) {
          lruCache.remove(key);
        }
      }
      // Cache miss

    } else {
      lruCache.remove(userId);
    }
    if (logger.isLoggable(Level.FINEST)) {
      logger.exiting(sourceClass, "removeProfileDataFromCache");
    }
  }
Ejemplo n.º 3
0
  private void waitForBlockStored(Sha256Hash hash) {
    if (hash.toString().equals("0000000000000000000000000000000000000000000000000000000000000000"))
      return;

    try {
      if (file_db.getBlockMap().containsKey(hash)) return;
    } finally {

    }

    Semaphore block_wait_sem = null;
    synchronized (in_progress) {
      block_wait_sem = in_progress.get(hash);
      if (block_wait_sem == null) {
        block_wait_sem = new Semaphore(0);
        in_progress.put(hash, block_wait_sem);
      }
    }

    try {
      // System.out.println("Waiting for " + hash);
      block_wait_sem.acquire(1);

    } catch (java.lang.InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 4
0
 public Pattern getPatternForRegex(String regex) {
   Pattern pattern = cache.get(regex);
   if (pattern == null) {
     pattern = Pattern.compile(regex);
     cache.put(regex, pattern);
   }
   return pattern;
 }
Ejemplo n.º 5
0
 @Test
 public void shouldReturnValueWhenCallGetWithKeyTest() {
   LRUCache cacheOneElement = new LRUCache(5);
   cacheOneElement.set(1, 1);
   int expected = 1;
   int actual = cacheOneElement.get(1);
   assertEquals(expected, actual);
 }
Ejemplo n.º 6
0
 /** @throws Exception On test failure. */
 @AfterClass(groups = {"cache"})
 public void clear() throws Exception {
   fillCache();
   AssertJUnit.assertEquals(5, cache.size());
   cache.clear();
   AssertJUnit.assertEquals(0, cache.size());
   cache.close();
 }
Ejemplo n.º 7
0
 @Test
 public void shouldReturnMinusOneWhenNotFoundTest() {
   LRUCache cache = new LRUCache(5);
   cache.set(1, 1);
   int expected = -1;
   int actual = cache.get(2);
   assertEquals(expected, actual);
 }
Ejemplo n.º 8
0
  @Test
  public void smoke() {

    LRUCache<String, String> cache = new LRUCache<String, String>(2);
    cache.put("a", "a");
    cache.put("b", "b");
    cache.put("c", "c");
    List<String> witness = new LinkedList<String>();
    witness.add("b");
    witness.add("c");
    assertEquals(witness, cache.keyList());
  }
Ejemplo n.º 9
0
  public void testLRUCache() {
    MyService service1 = new MyService();
    MyService service2 = new MyService();

    cache.put("A", service1);
    cache.put("B", service2);

    assertEquals(2, cache.size());

    assertSame(service1, cache.get("A"));
    assertSame(service2, cache.get("B"));
  }
Ejemplo n.º 10
0
 /*
  * Method to check if the Profile is cached. Calls findInCache to find for the profile in Cache.
  *
  * @param userId
  * @return Document
  */
 private Document getProfileDataFromCache(String userId) {
   // this should return just the content ..xmldoc
   // should a have a common caching framework for all services
   Document data = null;
   if (isEmail(userId)) {
     data = findInCache(userId);
   } else {
     if (lruCache.hasKey(userId)) {
       data = lruCache.get(userId);
     }
   }
   return data;
 }
Ejemplo n.º 11
0
  private String getNamespace(int id) throws IOException {
    Integer cacheID = new Integer(id);
    String namespace = namespaceCache.get(cacheID);

    if (namespace == null) {
      byte[] namespaceData = dataStore.getData(id);
      namespace = data2namespace(namespaceData);

      namespaceCache.put(cacheID, namespace);
    }

    return namespace;
  }
Ejemplo n.º 12
0
 @Test
 public void shouldReturnMinusOneAfterLatestKeyGetTest() {
   LRUCache cache = new LRUCache(5);
   cache.set(1, 1);
   cache.set(2, 2);
   cache.set(3, 3);
   cache.set(4, 4);
   cache.set(5, 5);
   cache.set(6, 6);
   int expected = -1;
   int actual = cache.get(1);
   assertEquals(expected, actual);
 }
Ejemplo n.º 13
0
  /**
   * Stores the supplied value and returns the ID that has been assigned to it. In case the value
   * was already present, the value will not be stored again and the ID of the existing value is
   * returned.
   *
   * @param value The Value to store.
   * @return The ID that has been assigned to the value.
   * @exception IOException If an I/O error occurred.
   */
  public int storeValue(Value value) throws IOException {
    // Try to get the internal ID from the value itself
    boolean isOwnValue = isOwnValue(value);

    if (isOwnValue) {
      NativeValue nativeValue = (NativeValue) value;

      if (revisionIsCurrent(nativeValue)) {
        // Value's ID is still current
        int id = nativeValue.getInternalID();

        if (id != NativeValue.UNKNOWN_ID) {
          return id;
        }
      }
    }

    // ID not stored in value itself, try the ID cache
    Integer cachedID = valueIDCache.get(value);

    if (cachedID != null) {
      int id = cachedID.intValue();

      if (isOwnValue) {
        // Store id in value for fast access in any consecutive calls
        ((NativeValue) value).setInternalID(id, revision);
      }

      return id;
    }

    // Unable to get internal ID in a cheap way, just store it in the data
    // store which will handle duplicates
    byte[] valueData = value2data(value, true);

    int id = dataStore.storeData(valueData);

    NativeValue nv = isOwnValue ? (NativeValue) value : getNativeValue(value);

    // Store id in value for fast access in any consecutive calls
    nv.setInternalID(id, revision);

    // Update cache
    valueIDCache.put(nv, new Integer(id));

    return id;
  }
Ejemplo n.º 14
0
 /** Gets the lock on a document. */
 public Lock getLock(final Serializable id) throws StorageException {
   serializationLock.lock();
   try {
     Lock lock;
     if (caching && (lock = lockCache.get(id)) != null) {
       return lock == NULL_LOCK ? null : lock;
     }
     // no transaction needed, single operation
     lock = mapper.getLock(id);
     if (caching) {
       lockCache.put(id, lock == null ? NULL_LOCK : lock);
     }
     return lock;
   } finally {
     serializationLock.unlock();
   }
 }
Ejemplo n.º 15
0
  public void testLRUCacheStop() throws Exception {
    MyService service1 = new MyService();
    MyService service2 = new MyService();

    cache.put("A", service1);
    cache.put("B", service2);

    assertEquals(false, service1.isStopped());
    assertEquals(false, service2.isStopped());

    cache.stop();

    assertEquals(0, cache.size());

    assertEquals(true, service1.isStopped());
    assertEquals(true, service2.isStopped());
  }
Ejemplo n.º 16
0
 /** @throws Exception On test failure. */
 @Test(
     groups = {"cache"},
     threadPoolSize = 5,
     invocationCount = 100,
     timeOut = 60000)
 public void get() throws Exception {
   SearchResult result =
       cache.get(new SearchRequest("dc=ldaptive,dc=org", new SearchFilter("uid=3")));
   AssertJUnit.assertEquals(
       new SearchResult(new LdapEntry("uid=3,ou=test,dc=ldaptive,dc=org")), result);
   result = cache.get(new SearchRequest("dc=ldaptive,dc=org", new SearchFilter("uid=4")));
   AssertJUnit.assertEquals(
       new SearchResult(new LdapEntry("uid=4,ou=test,dc=ldaptive,dc=org")), result);
   result = cache.get(new SearchRequest("dc=ldaptive,dc=org", new SearchFilter("uid=5")));
   AssertJUnit.assertEquals(
       new SearchResult(new LdapEntry("uid=5,ou=test,dc=ldaptive,dc=org")), result);
 }
 private RecentLabelList(int paramInt) {
   int i;
   mRecentLabelsLRU = new LRUCache(i);
   this$1 = paramInt.iterator();
   while (hasNext()) {
     paramInt = (String) next();
     mRecentLabelsLRU.addElement(paramInt, null);
   }
 }
Ejemplo n.º 18
0
    public String format(double value) {
      String f = cache.get(value);
      if (f == null) {
        f = String.format(format, value);
        cache.put(value, f);
        //                if ( cache.usedEntries() < maxCacheSize ) {
        //                    System.out.printf("CACHE size %d%n", cache.usedEntries());
        //                } else {
        //                    System.out.printf("CACHE is full %f%n", value);
        //                }
        //            }
        //            } else {
        //                System.out.printf("CACHE hit %f%n", value);
        //            }
      }

      return f;
    }
Ejemplo n.º 19
0
  public Transaction getTransaction(Sha256Hash hash) {
    Transaction tx = null;
    synchronized (transaction_cache) {
      tx = transaction_cache.get(hash);
    }
    if (tx == null) {

      SerializedTransaction s_tx = file_db.getTransactionMap().get(hash);

      if (s_tx != null) {
        tx = s_tx.getTx(params);
        synchronized (transaction_cache) {
          transaction_cache.put(hash, SerializedTransaction.scrubTransaction(params, tx));
        }
      }
    }
    return tx;
  }
Ejemplo n.º 20
0
  /**
   * Gets the value for the specified ID.
   *
   * @param id A value ID.
   * @return The value for the ID, or <tt>null</tt> no such value could be found.
   * @exception IOException If an I/O error occurred.
   */
  public NativeValue getValue(int id) throws IOException {
    // Check value cache
    Integer cacheID = new Integer(id);
    NativeValue resultValue = valueCache.get(cacheID);

    if (resultValue == null) {
      // Value not in cache, fetch it from file
      byte[] data = dataStore.getData(id);

      if (data != null) {
        resultValue = data2value(id, data);

        // Store value in cache
        valueCache.put(cacheID, resultValue);
      }
    }

    return resultValue;
  }
Ejemplo n.º 21
0
 @Test
 @Ignore // slow test that is known to pass
 public void multiThreadedScenario() throws InterruptedException {
   int cacheSize = 100;
   int worldSize = cacheSize * 2;
   LRUCache<String, String> lruCache = new LRUCache<String, String>(cacheSize);
   T_LRUCache<String> tlruCache = new T_LRUCache<String>(cacheSize);
   SimulatorRunnable[] simulatorArray = new SimulatorRunnable[5];
   for (int i = 0; i < simulatorArray.length; i++) {
     simulatorArray[i] = new SimulatorRunnable(lruCache, tlruCache, worldSize);
   }
   for (int i = 0; i < simulatorArray.length; i++) {
     simulatorArray[i].start();
   }
   for (int i = 0; i < simulatorArray.length; i++) {
     simulatorArray[i].join();
   }
   assertEquals(tlruCache.keyList(), lruCache.keyList());
 }
Ejemplo n.º 22
0
 /**
  * Clear the whole cache.
  */
 public synchronized void clear() {
     synchronized(cache){
         for(String key : keys){
             super.remove(key);
             File fileForKey = getFileForKey(key);
             fileForKey.delete();
         }
         keys.clear();
     }        
 }
Ejemplo n.º 23
0
 public void clearCaches() {
   serializationLock.lock();
   try {
     if (caching) {
       lockCache.clear();
     }
   } finally {
     serializationLock.unlock();
   }
 }
Ejemplo n.º 24
0
 /**
  * Removes both: from the memory and from the disk
  */
 public synchronized void remove(String key) {
     synchronized(cache){
         if(DEBUG){
             System.out.println("Disk cache - Removing: "+key);
         }
         super.remove(key);
         File fileForKey = getFileForKey(key);
         fileForKey.delete();
         keys.remove(key);
     }
 }
Ejemplo n.º 25
0
 /**
  * Adds to both: the memory and the disk
  */
 public synchronized void add(String key, Serializable n) {
     synchronized(cache){
         super.add(key, n);
         File fileForKey = getFileForKey(key);
         if(DEBUG){
             System.out.println("Disk cache - Adding: "+key+" file: "+fileForKey);
         }
         REF.writeToFile(n, fileForKey);
         keys.add(key);
     }
 }
Ejemplo n.º 26
0
  private int getNamespaceID(String namespace, boolean create) throws IOException {
    Integer cacheID = namespaceIDCache.get(namespace);
    if (cacheID != null) {
      return cacheID.intValue();
    }

    byte[] namespaceData = namespace.getBytes("UTF-8");

    int id;
    if (create) {
      id = dataStore.storeData(namespaceData);
    } else {
      id = dataStore.getID(namespaceData);
    }

    if (id != -1) {
      namespaceIDCache.put(namespace, new Integer(id));
    }

    return id;
  }
Ejemplo n.º 27
0
 /**
  * Fetch cache value
  *
  * @param id ItemId
  * @return cached value or null when not in cache
  */
 public Boolean get(ItemId id) {
   if (maxCacheSize < 1) {
     return null;
   }
   accesses++;
   Boolean obj = readAccessCache.get(id);
   if (obj == null) {
     misses++;
   } else {
     hits++;
   }
   return obj;
 }
Ejemplo n.º 28
0
 /*
  * Method to search the cache
  *
  * @param userId
  * @return Document
  */
 private Document findInCache(String userId) {
   String key;
   Set<String> keys = lruCache.getKeySet();
   Iterator<String> itr = keys.iterator();
   while (itr.hasNext()) {
     key = itr.next();
     Document data = lruCache.get(key);
     // check if email in profile object is same as input userId
     String email = "";
     try {
       email = DOMUtil.value(data, Profile.xpathMap.get("email"), Profile.nameSpaceCtx);
     } catch (XMLException e) {
       continue;
     }
     // cache hit
     if (StringUtil.equalsIgnoreCase(email, userId)) {
       return data;
     }
   }
   // Cache miss
   return null;
 }
Ejemplo n.º 29
0
 /** Unlocks a document. */
 public Lock removeLock(final Serializable id, final String owner) throws StorageException {
   serializationLock.lock();
   try {
     Lock oldLock = null;
     if (caching && (oldLock = lockCache.get(id)) == NULL_LOCK) {
       return null;
     }
     if (oldLock != null && !canLockBeRemoved(oldLock, owner)) {
       // existing mismatched lock, flag failure
       oldLock = new Lock(oldLock, true);
     } else {
       if (oldLock == null) {
         oldLock =
             callInTransaction(
                 new Callable<Lock>() {
                   @Override
                   public Lock call() throws Exception {
                     return mapper.removeLock(id, owner, false);
                   }
                 });
       } else {
         // we know the previous lock, we can force
         // no transaction needed, single operation
         mapper.removeLock(id, owner, true);
       }
     }
     if (caching) {
       if (oldLock != null && oldLock.getFailed()) {
         // failed, but we now know the existing lock
         lockCache.put(id, new Lock(oldLock, false));
       } else {
         lockCache.put(id, NULL_LOCK);
       }
     }
     return oldLock;
   } finally {
     serializationLock.unlock();
   }
 }
Ejemplo n.º 30
0
 protected Lock setLockInternal(final Serializable id, final Lock lock) throws StorageException {
   serializationLock.lock();
   try {
     Lock oldLock;
     if (caching && (oldLock = lockCache.get(id)) != null && oldLock != NULL_LOCK) {
       return oldLock;
     }
     oldLock =
         callInTransaction(
             new Callable<Lock>() {
               @Override
               public Lock call() throws Exception {
                 return mapper.setLock(id, lock);
               }
             });
     if (caching && oldLock == null) {
       lockCache.put(id, lock == null ? NULL_LOCK : lock);
     }
     return oldLock;
   } finally {
     serializationLock.unlock();
   }
 }