called from CacheBuilder
329655
public void setCacheConfig(final Cache2kConfiguration c) {
    valueType = c.getValueType();
    keyType = c.getKeyType();
    if (name != null) {
      throw new IllegalStateException("already configured");
    }
    setName(c.getName());
    setFeatureBit(KEEP_AFTER_EXPIRED, c.isKeepDataAfterExpired());
    setFeatureBit(REJECT_NULL_VALUES, !c.isPermitNullValues());
    setFeatureBit(BACKGROUND_REFRESH, c.isRefreshAhead());
    setFeatureBit(UPDATE_TIME_NEEDED, c.isRecordRefreshedTime());
    setFeatureBit(RECORD_REFRESH_TIME, c.isRecordRefreshedTime());

    metrics = TUNABLE.commonMetricsFactory.create(new CommonMetricsFactory.Parameters() {
      @Override
      public boolean isDisabled() {
        return c.isDisableStatistics();
      }

      @Override
      public boolean isPrecise() {
        return false;
      }
    });

    if (c.getLoaderExecutor() != null) {
      loaderExecutor = createCustomization((CustomizationSupplier<Executor>) c.getLoaderExecutor());
    } else {
      if (c.getLoaderThreadCount() > 0) {
        loaderExecutor = provideDefaultLoaderExecutor(c.getLoaderThreadCount());
      }
    }
    if (c.getPrefetchExecutor() != null) {
      prefetchExecutor = createCustomization((CustomizationSupplier<Executor>) c.getPrefetchExecutor());
    }
  }
830099
private @Nullable CacheWriterException writeAllToCacheWriter(Map<? extends K, ? extends V> map) {
    if (!configuration.isWriteThrough() || map.isEmpty()) {
      return null;
    }
    List<Cache.Entry<? extends K, ? extends V>> entries = map.entrySet().stream()
        .map(entry -> new EntryProxy<>(entry.getKey(), entry.getValue()))
        .collect(toList());
    try {
      writer.writeAll(entries);
      return null;
    } catch (CacheWriterException e) {
      entries.forEach(entry -> {
        map.remove(entry.getKey());
      });
      throw e;
    } catch (RuntimeException e) {
      entries.forEach(entry -> {
        map.remove(entry.getKey());
      });
      return new CacheWriterException("Exception in CacheWriter", e);
    }
  }
1247251
private final void forceRebuildDirtyCache() {
    final long[] tgtArr = new long[1 << lgArrLongs_];
    curCount_ = HashOperations.hashArrayInsert(cache_, tgtArr, lgArrLongs_, thetaLong_);
    cache_ = tgtArr;
    dirty_ = false;
    //hashTableThreshold stays the same
  }
394826
static synchronized CacheInstanceInfo [] getCacheInstanceInfo( CacheServiceImpl cacheService ) {
		CacheInstanceInfo infoOut [] = currentCacheInstanceInfoOut;
		if ( System.currentTimeMillis() - lastPopulate > populateInterval ) {
			if (cacheService!=null) {
				if ( cacheInstanceInfo == null ) {
					cacheInstanceInfo = new CacheInstanceInfo();
				}
				cacheService.populateCacheInstanceInfo( cacheInstanceInfo );
				CacheInstanceInfo.cacheService = cacheService;
				infoOut = new CacheInstanceInfo[allConfigured.size()];
				Iterator i = allConfigured.iterator();
				int x=0;
				while ( i.hasNext() ) {
					String cacheName =  (String)i.next();
					CacheInstanceInfo info = new CacheInstanceInfo();

					info.cacheName      = cacheName;
					info.isActive       = CacheInstanceInfo.allActive.contains(cacheName);
					info.isFactory      = CacheInstanceInfo.allFactory.contains(cacheName);
					info.isFile         = CacheInstanceInfo.allFile.contains(cacheName);
					info.isObjectCache  = CacheInstanceInfo.objectConfigured.contains(cacheName);
					info.isServletCache = CacheInstanceInfo.servletConfigured.contains(cacheName);

					infoOut[x++] = info;
				}
				currentCacheInstanceInfoOut = infoOut;
				CacheInstanceInfo.allConfigured.clear();
				CacheInstanceInfo.allActive.clear();
				CacheInstanceInfo.allFactory.clear();
				CacheInstanceInfo.allFile.clear();
				CacheInstanceInfo.objectConfigured.clear();
				CacheInstanceInfo.servletConfigured.clear();

			}
			lastPopulate = System.currentTimeMillis();
		}
		return infoOut;
	}
908768
@Override
    public void cacheKnowledgeBuilderForKieBase( String kieBaseName, KnowledgeBuilder kbuilder ) {
        internalKieModule.cacheKnowledgeBuilderForKieBase( kieBaseName, kbuilder );
    }
1141899
@Override
    protected T readCacheDataFromFile(File file) throws CacheLoadingException {
        try {
            JsonParser jsonParser = jsonFactory.createJsonParser(new FileReader(file));
            T result = jsonParser.parse(getHandledClass(), null);
            jsonParser.close();
            return result;
        } catch (FileNotFoundException e) {
            // Should not occur (we test before if file exists)
            // Do not throw, file is not cached
            Ln.w("file " + file.getAbsolutePath() + " does not exists", e);
            return null;
        } catch (Exception e) {
            throw new CacheLoadingException(e);
        }
    }
28804
@Override
    public void batchUpdate(HashMap invalidateIdEvents, HashMap invalidateTemplateEvents, ArrayList pushEntryEvents) {
        final String methodName = "batchUpdate()";
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, methodName + " cacheName=" + cacheName + " ERROR because it should not be called");
        }
    }
1158275
public
  void prepareCache(int size){
   if (tc.isEntryEnabled())
      tc.entry(this,cclass, "prepareCache", "size: " + size);

    int oldSize = (cacheTag == null) ? 0 : cacheTag.length;

    if (size <= oldSize) {
      // If the cache is big enough, make sure we are not out of counters
      if (generation == Integer.MAX_VALUE) {
        generation = 1;
        for (int i = 0; i < size; i++)
          cacheTag[i] = 0;
      } else generation++;

    if (tc.isEntryEnabled())
	  tc.exit(this,cclass, "prepareCache");

      return;
    }

    // Allocate fresh

    cacheTag = new int[2*size];
    cacheValue = new Object[2*size];

    // Reset generation since all cache fields are null.
    generation = 1;

    if (tc.isEntryEnabled())
	  tc.exit(this,cclass, "prepareCache");
  }
659879
@Override
	public void initialized(ICacheManager cacheManager) {
		final String sourceMethod = "initialized"; //$NON-NLS-1$
		final boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(sourceClass, sourceMethod);
		}
		// Cache manager is initialized.  De-register the listener and add our named cache
		cacheMgrListenerReg.unregister();
		JsxConverter converter = newConverter();
		IGenericCache cache = newCache(converter, "jsx.", ""); //$NON-NLS-1$ //$NON-NLS-2$
		cache.setAggregator(aggregator);
		ResourceConverterCacheImpl oldCache = (ResourceConverterCacheImpl)cacheManager.getCache().putIfAbsent(JSX_CACHE_NAME, cache);
		if (oldCache != null) {
			converter = (JsxConverter)oldCache.getConverter();
		}
		if (isTraceLogging) {
			log.logp(Level.FINER, sourceClass, sourceMethod, "Initializing resource converter" + (oldCache != null ? " from cache." : ".")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		}
		converter.initialize(es, xformerRes.getURI());

		if (isTraceLogging) {
			log.exiting(sourceClass, sourceMethod);
		}
	}
731845
public UserManagedCacheBuilder<K, V, T> withLoaderWriter(CacheLoaderWriter<K, V> loaderWriter) {
    if (loaderWriter == null) {
      throw new NullPointerException("Null loaderWriter");
    }
    UserManagedCacheBuilder<K, V, T> otherBuilder = new UserManagedCacheBuilder<>(this);
    otherBuilder.cacheLoaderWriter = loaderWriter;
    return otherBuilder;
  }
1190542
@SuppressWarnings({"unchecked", "SuspiciousToArrayCall"})
  public Cache<K, V> buildAsIs() {
    if (config.getValueType() == null) {
      config.setValueType((Class<V>) Object.class);
    }
    if (config.getKeyType() == null) {
      config.setKeyType((Class<K>) Object.class);
    }
    if (config.getName() == null) {
      config.setName(deriveNameFromStackTrace());
    }
    checkConfiguration();
    Class<?> _implClass = HeapCache.class;
    Class<?> _keyType = config.getKeyType().getType();
    if (_keyType == Integer.class) {
      _implClass = IntHeapCache.class;
    } else if (_keyType == Long.class) {
      _implClass = LongHeapCache.class;
    }
    InternalCache<K, V> _cache = constructImplementationAndFillParameters(_implClass);
    InternalClock _timeReference = (InternalClock) _cache.createCustomization(config.getTimeReference());
    if (_timeReference == null) {
      _timeReference = ClockDefaultImpl.INSTANCE;
    }
    HeapCache bc = (HeapCache) _cache;
    bc.setCacheManager(manager);
    if (config.hasCacheClosedListeners()) {
      bc.setCacheClosedListeners(config.getCacheClosedListeners());
    }
    configureViaSettersDirect(bc);
    bc.setClock(_timeReference);

    if (config.isRefreshAhead() && !(
          config.getAsyncLoader() != null ||
          config.getLoader() != null ||
          config.getAdvancedLoader() != null)) {
      throw new IllegalArgumentException("refresh ahead enabled, but no loader defined");
    }

    boolean _wrap =
      config.getWeigher() != null ||
      config.hasListeners() ||
      config.hasAsyncListeners() ||
      config.getWriter() != null ||
      config.getAsyncLoader() != null;


    WiredCache<K, V> wc = null;
    if (_wrap) {
      if (_keyType == Integer.class) {
        wc = (WiredCache<K, V>) new IntWiredCache<V>();
      } else if (_keyType == Long.class) {
        wc = (WiredCache<K, V>) new LongWiredCache<V>();
      } else {
        wc = new WiredCache<K, V>();
      }
      wc.heapCache = bc;
      _cache = wc;
    }

    String _name = manager.newCache(_cache, bc.getName());
    bc.setName(_name);
    if (_wrap) {
      wc.loader = bc.loader;
      wc.writer = (CacheWriter<K, V>) bc.createCustomization(config.getWriter());
      wc.asyncLoader = (AsyncCacheLoader<K, V>) bc.createCustomization(config.getAsyncLoader());
      List<CacheEntryCreatedListener<K, V>> _syncCreatedListeners = new ArrayList<CacheEntryCreatedListener<K, V>>();
      List<CacheEntryUpdatedListener<K, V>> _syncUpdatedListeners = new ArrayList<CacheEntryUpdatedListener<K, V>>();
      List<CacheEntryRemovedListener<K, V>> _syncRemovedListeners = new ArrayList<CacheEntryRemovedListener<K, V>>();
      List<CacheEntryExpiredListener<K, V>> _syncExpiredListeners = new ArrayList<CacheEntryExpiredListener<K, V>>();
      List<CacheEntryEvictedListener<K, V>> _syncEvictedListeners = new ArrayList<CacheEntryEvictedListener<K,V>>();
      List<CacheEntryExpiredListener<K, V>> _expiredListeners = new ArrayList<CacheEntryExpiredListener<K, V>>();
      if (config.hasListeners()) {
        for (CustomizationSupplier<CacheEntryOperationListener<K, V>> f : config.getListeners()) {
          CacheEntryOperationListener<K, V> el = ( CacheEntryOperationListener<K, V>) bc.createCustomization(f);
          if (el instanceof CacheEntryCreatedListener) {
            _syncCreatedListeners.add((CacheEntryCreatedListener) el);
          }
          if (el instanceof CacheEntryUpdatedListener) {
            _syncUpdatedListeners.add((CacheEntryUpdatedListener) el);
          }
          if (el instanceof CacheEntryRemovedListener) {
            _syncRemovedListeners.add((CacheEntryRemovedListener) el);
          }
          if (el instanceof CacheEntryExpiredListener) {
            _expiredListeners.add((CacheEntryExpiredListener) el);
          }
          if (el instanceof CacheEntryEvictedListener) {
            _syncEvictedListeners.add((CacheEntryEvictedListener) el);
          }
        }
      }
      if (config.hasAsyncListeners() || !_expiredListeners.isEmpty()) {
        Executor _executor = DEFAULT_ASYNC_LISTENER_EXECUTOR;
        if (config.getAsyncListenerExecutor() != null) {
          _executor = _cache.createCustomization(config.getAsyncListenerExecutor());
        }
        AsyncDispatcher<K> _asyncDispatcher = new AsyncDispatcher<K>(wc, _executor);
        List<CacheEntryCreatedListener<K, V>> cll = new ArrayList<CacheEntryCreatedListener<K, V>>();
        List<CacheEntryUpdatedListener<K, V>> ull = new ArrayList<CacheEntryUpdatedListener<K, V>>();
        List<CacheEntryRemovedListener<K, V>> rll = new ArrayList<CacheEntryRemovedListener<K, V>>();
        List<CacheEntryExpiredListener<K, V>> ell = new ArrayList<CacheEntryExpiredListener<K, V>>();
        List<CacheEntryEvictedListener<K, V>> evl = new ArrayList<CacheEntryEvictedListener<K, V>>();
        for (CustomizationSupplier<CacheEntryOperationListener<K, V>> f : config.getAsyncListeners()) {
          CacheEntryOperationListener<K, V> el = (CacheEntryOperationListener<K, V>) bc.createCustomization(f);
          if (el instanceof CacheEntryCreatedListener) {
            cll.add((CacheEntryCreatedListener) el);
          }
          if (el instanceof CacheEntryUpdatedListener) {
            ull.add((CacheEntryUpdatedListener) el);
          }
          if (el instanceof CacheEntryRemovedListener) {
            rll.add((CacheEntryRemovedListener) el);
          }
          if (el instanceof CacheEntryExpiredListener) {
            ell.add((CacheEntryExpiredListener) el);
          }
          if (el instanceof CacheEntryEvictedListener) {
            evl.add((CacheEntryEvictedListener) el);
          }
        }
        for (CacheEntryCreatedListener l : cll) {
          _syncCreatedListeners.add(new AsyncCreatedListener<K, V>(_asyncDispatcher, l));
        }
        for (CacheEntryUpdatedListener l : ull) {
          _syncUpdatedListeners.add(new AsyncUpdatedListener<K, V>(_asyncDispatcher, l));
        }
        for (CacheEntryRemovedListener l : rll) {
          _syncRemovedListeners.add(new AsyncRemovedListener<K, V>(_asyncDispatcher, l));
        }
        for (CacheEntryExpiredListener l : ell) {
          _syncExpiredListeners.add(new AsyncExpiredListener<K, V>(_asyncDispatcher, l));
        }
        for (CacheEntryExpiredListener l : _expiredListeners) {
          _syncExpiredListeners.add(new AsyncExpiredListener<K, V>(_asyncDispatcher, l));
        }
        for (CacheEntryEvictedListener l : evl) {
          _syncEvictedListeners.add(new AsyncEvictedListener<K, V>(_asyncDispatcher, l));
        }
      }
      if (!_syncCreatedListeners.isEmpty()) {
        wc.syncEntryCreatedListeners = _syncCreatedListeners.toArray(new CacheEntryCreatedListener[0]);
      }
      if (!_syncUpdatedListeners.isEmpty()) {
        wc.syncEntryUpdatedListeners = _syncUpdatedListeners.toArray(new CacheEntryUpdatedListener[0]);
      }
      if (!_syncRemovedListeners.isEmpty()) {
        wc.syncEntryRemovedListeners = _syncRemovedListeners.toArray(new CacheEntryRemovedListener[0]);
      }
      if (!_syncExpiredListeners.isEmpty()) {
        wc.syncEntryExpiredListeners = _syncExpiredListeners.toArray(new CacheEntryExpiredListener[0]);
      }
      if (!_syncEvictedListeners.isEmpty()) {
        wc.syncEntryEvictedListeners = _syncEvictedListeners.toArray(new CacheEntryEvictedListener[0]);
      }
      bc.eviction = constructEviction(bc, wc, config);
      TimingHandler rh = TimingHandler.of(_timeReference, config);
      bc.setTiming(rh);
      wc.init();
    } else {
      TimingHandler rh = TimingHandler.of(_timeReference, config);
      bc.setTiming(rh);
       bc.eviction = constructEviction(bc, HeapCacheListener.NO_OPERATION, config);
      bc.init();
    }
    manager.sendCreatedEvent(_cache, config);
    return _cache;
  }
27321
public synchronized void pushCacheEntry(CacheEntry cacheEntry, DCache cache) {
        BatchUpdateList bul = getUpdateList(cache);
        bul.pushCacheEntryEvents.add(cacheEntry);
    }
170969
protected void refreshItem(CacheItem item, Cache cache) throws Exception {
        CacheLoader loader = item.getLoader();
        Object[] loaderParams = item.getLoaderParams();

        if (loader == null) {
            throw new InternalCacheEngineException("No cache loader for " + getScopeAndKeyString(item));
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Refreshing " + getScopeAndKeyString(item));
        }

        Object newValue = loader.load(loaderParams);
        if (newValue != null) {
            cache.put(item.getScope(), item.getKey(), newValue, item.getTicksToExpire(), item.getTicksToRefresh(),
                      item.getLoader(), item.getLoaderParams());
        } else {
            // If newValue returned is null, remove the item from the cache
            cache.remove(item.getScope(), item.getKey());
        }
    }
1231174
public final Cache2kBuilder<K,V> addAsyncListener(CacheEntryOperationListener<K,V> listener) {
    config().getAsyncListeners().add(wrapCustomizationInstance(listener));
    return this;
  }
532092
private static LottieTask<LottieComposition> cache(
          @Nullable final String cacheKey, Callable<LottieResult<LottieComposition>> callable) {
    final LottieComposition cachedComposition = cacheKey == null ? null : LottieCompositionCache.getInstance().get(cacheKey);
    if (cachedComposition != null) {
      return new LottieTask<>(new Callable<LottieResult<LottieComposition>>() {
        @Override
        public LottieResult<LottieComposition> call() {
          return new LottieResult<>(cachedComposition);
        }
      });
    }
    if (cacheKey != null && taskCache.containsKey(cacheKey)) {
      return taskCache.get(cacheKey);
    }

    LottieTask<LottieComposition> task = new LottieTask<>(callable);
    task.addListener(new LottieListener<LottieComposition>() {
      @Override public void onResult(LottieComposition result) {
        if (cacheKey != null) {
          LottieCompositionCache.getInstance().put(cacheKey, result);
        }
        taskCache.remove(cacheKey);
      }
    });
    task.addFailureListener(new LottieListener<Throwable>() {
      @Override public void onResult(Throwable result) {
        taskCache.remove(cacheKey);
      }
    });
    taskCache.put(cacheKey, task);
    return task;
  }
386957
@Override
   public void cacheStarting(ComponentRegistry cr, Configuration cfg, String cacheName) {
      InternalCacheRegistry icr = cr.getGlobalComponentRegistry().getComponent(InternalCacheRegistry.class);
      if (!icr.isInternalCache(cacheName) || icr.internalCacheHasFlag(cacheName, Flag.QUERYABLE)) {
         AdvancedCache<?, ?> cache = cr.getComponent(Cache.class).getAdvancedCache();
         ClassLoader aggregatedClassLoader = makeAggregatedClassLoader(cr.getGlobalComponentRegistry().getGlobalConfiguration().classLoader());
         SearchIntegrator searchFactory = null;
         boolean isIndexed = cfg.indexing().index().isEnabled();
         if (isIndexed) {
            setBooleanQueryMaxClauseCount();

            cr.registerComponent(new ShardAllocationManagerImpl(), ShardAllocatorManager.class);
            searchFactory = createSearchIntegrator(cfg.indexing(), cr, aggregatedClassLoader);

            KeyTransformationHandler keyTransformationHandler = new KeyTransformationHandler(aggregatedClassLoader);
            cr.registerComponent(keyTransformationHandler, KeyTransformationHandler.class);

            createQueryInterceptorIfNeeded(cr.getComponent(BasicComponentRegistry.class), cfg, cache, searchFactory, keyTransformationHandler);
            addCacheDependencyIfNeeded(cacheName, cache.getCacheManager(), cfg.indexing());

            cr.registerComponent(new QueryBox(), QueryBox.class);
         }

         registerMatcher(cr, searchFactory, aggregatedClassLoader);

         cr.registerComponent(new EmbeddedQueryEngine(cache, isIndexed), EmbeddedQueryEngine.class);
      }
   }
1259225
private void put(T item) {
        HashMap<String,Object> keys;

        if( item == null ) {
            throw new NullPointerException("Multi caches may not have null values.");
        }
        keys = getKeys(item);
        synchronized( this ) {
            for( String key : caches.keySet() ) {
                ConcurrentCache<Object,T> cache = caches.get(key);
                Object ob = keys.get(key);

                if( ob instanceof BigDecimal ) {
                    ob = ((BigDecimal)ob).longValue();
                }
                cache.put(ob, item);
            }
        }
    }