コード例 #1
0
        /**
         * Adds an object to the cache. The add fails if the object or key is null, or if the size is zero, negative or
         * greater than the maximmum capacity.
         *
         * @param key              The unique reference key that identifies this object.
         * @param clientObject     The actual object to be cached.
         * @param clientObjectSize The size of the object in cache units.
         *
         * @return returns true if clientObject was added, false otherwise.
         */
        public bool add(Object key, Object clientObject, long clientObjectSize)
        {
            long cap = this.capacity.get();

            if (key == null || clientObject == null || clientObjectSize <= 0 || clientObjectSize > cap)
            {
                String message = Logging.getMessage("BasicMemoryCache.CacheItemNotAdded");

                if (clientObjectSize > cap)
                {
                    message += " - " + Logging.getMessage("BasicMemoryCache.ItemTooLargeForCache");
                }

                Logging.logger().warning(message);

                return(false);
                // the logic behind not throwing an exception is that whether we throw an exception or not,
                // the object won't be added. This doesn't matter because that object could be removed before
                // it is accessed again anyway.
            }

            BasicMemoryCache.CacheEntry entry = new BasicMemoryCache.CacheEntry(key, clientObject, clientObjectSize);

            synchronized(this.lock)
            {
                CacheEntry existing = this.entries.get(key);

                if (existing != null) // replacing
                {
                    this.removeEntry(existing);
                }

                if (this.currentUsedCapacity.get() + clientObjectSize > cap)
                {
                    this.makeSpace(clientObjectSize);
                }

                this.currentUsedCapacity.addAndGet(clientObjectSize);
                this.entries.putIfAbsent(entry.key, entry);
            }

            return(true);
        }
コード例 #2
0
        public bool add(Object key, Object clientObject, long clientObjectSize)
        {
            BasicMemoryCache.CacheEntry entry = new BasicMemoryCache.CacheEntry(key, clientObject, clientObjectSize);

            synchronized(this.lock)
            {
                this.removeExpiredEntries();

                CacheEntry existing = this.entries.get(key);

                if (existing != null) // replacing
                {
                    this.removeEntry(existing);
                }

                this.currentUsedCapacity.addAndGet(clientObjectSize);
                this.entries.putIfAbsent(entry.key, entry);
                this.updateMemorySemaphore();
            }

            return(true);
        }