Cache threadpool since context is
        recreated for each request
501385
def instance(cls, size):
        
        if not getattr(cls, "_instance", None):
            cls._instance = {}
        if size not in cls._instance:
            cls._instance[size] = ThreadPool(size)
        return cls._instance[size]
468386
def cached(namespace=None, service="memory", debug=False):
    
    _service = getattr(debris.services, service)
    def wrapper(_f):
        @functools.wraps(_f)
        def _stash(self, *a, **k):
            if debug is False:
                # this request is cacheable
                try:
                    self.finish(_service.get(namespace))
                except LookupError:
                    _replace_finish(self, namespace, _service)
                    # get the result of this request
                    _f(self, *a, **k)
                return
            # request is not cacheable
            _f(self, *a, **k)
        return _stash
    return wrapper
607362
public synchronized ExecutorService getBatchThreadPool() {
    if (batchThreadPool == null) {
      batchThreadPool = Executors
          .newCachedThreadPool(ThreadUtil.getThreadFactory(BATCH_POOL_THREAD_NAME_PATTERN, true));
    }
    return batchThreadPool;
  }
770704
def connection_from_context(self, request_context):
        
        scheme = request_context['scheme'].lower()
        pool_key_constructor = self.key_fn_by_scheme[scheme]
        pool_key = pool_key_constructor(request_context)

        return self.connection_from_pool_key(pool_key, request_context=request_context)
78289
def cache(*args, **kwargs):
    
    ## only one argument ?
    if len(args) == 1 and len(kwargs) == 0 and \
           (callable(args[0]) or \
            isinstance(args[0], tuple(SUPPORTED_DECORATOR.keys()))):
        return _cache_w_args(args[0])
    return lambda f: _cache_w_args(f, *args, **kwargs)
1187563
def cached(cls, timeout=60, cache_none=False):
        
        return CachedModel(cls=cls, timeout=timeout, cache_none=cache_none)
248219
public void clearCache(CacheInvocationContext<CacheRemove> context) {
        HystrixCacheKeyGenerator defaultCacheKeyGenerator = HystrixCacheKeyGenerator.getInstance();
        String cacheName = context.getCacheAnnotation().commandKey();
        HystrixGeneratedCacheKey hystrixGeneratedCacheKey =
                defaultCacheKeyGenerator.generateCacheKey(context);
        String key = hystrixGeneratedCacheKey.getCacheKey();
        HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey(cacheName),
                HystrixConcurrencyStrategyDefault.getInstance()).clear(key);
    }
1306232
def _enable_thread_pool(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        if self.enable_thread_pool and hasattr(self, 'thread_pool'):
            future = self.thread_pool.submit(func, *args, **kwargs)
            is_async = kwargs.get('is_async')
            if is_async is None or not is_async:
                timeout = kwargs.get('timeout')
                if timeout is None:
                    timeout = 2
                try:
                    result = future.result(timeout=timeout)
                except TimeoutError as e:
                    self.logger.exception(e)
                    result = None
                return result
            return future
        else:
            return func(*args, **kwargs)

    return wrapper
620643
public void processRequest(RequestContext context) throws Exception {
        if (processorIterator.hasNext()){
            RequestSecurityProcessor processor = processorIterator.next();

            logger.debug("Executing processor {}", processor);

            processor.processRequest(context, this);
        }
    }
758523
def cachedmethod(cache, key=keys.hashkey, lock=None):
    
    def decorator(method):
        if lock is None:
            def wrapper(self, *args, **kwargs):
                c = cache(self)
                if c is None:
                    return method(self, *args, **kwargs)
                k = key(*args, **kwargs)
                try:
                    return c[k]
                except KeyError:
                    pass  # key not found
                v = method(self, *args, **kwargs)
                try:
                    c[k] = v
                except ValueError:
                    pass  # value too large
                return v
        else:
            def wrapper(self, *args, **kwargs):
                c = cache(self)
                if c is None:
                    return method(self, *args, **kwargs)
                k = key(*args, **kwargs)
                try:
                    with lock(self):
                        return c[k]
                except KeyError:
                    pass  # key not found
                v = method(self, *args, **kwargs)
                try:
                    with lock(self):
                        c[k] = v
                except ValueError:
                    pass  # value too large
                return v
        return _update_wrapper(wrapper, method)
    return decorator
1368636
def do_api_calls_update_cache(self):
        '''  '''
        zones = self.parse_env_zones()
        data = self.group_instances(zones)
        self.cache.write_to_cache(data)
        self.inventory = data
176607
def clear_query_caches_for_current_thread
      ActiveRecord::Base.connection_handlers.each_value do |handler|
        handler.connection_pool_list.each do |pool|
          pool.connection.clear_query_cache if pool.active_connection?
        end
      end
    end
1149446
def map(self, method: str, *args, _threaded: bool = True, **kwargs
           ) -> "AttrIndexedDict":
        ""

        work = lambda item: getattr(item, method)(*args, **kwargs)

        if _threaded:
            pool = ThreadPool(int(config.CFG["GENERAL"]["parallel_requests"]))

            try:
                pool.map(work, self.data.values())
            except KeyboardInterrupt:
                LOG.warning("CTRL-C caught, finishing current tasks...")
                pool.terminate()
            else:
                pool.close()

            pool.join()
            return self

        for item in self.data.values():
            work(item)
        return self
979177
def iter_context_results(context, batch_size=10, task_cache=None):
    """"""

    for futures in iget_batches(context.task_ids, batch_size=batch_size):
        for key, future in futures:
            task = future.get_result()

            if task_cache is not None:
                task_cache[key.id()] = task

            yield key.id(), task
1143687
public V getCachedObject(TaskRequest req, TaskResponse res, K key, Factory<K, V> factory) {
        final CacheMode cacheMode = CacheMode.valueOf((String) this.cacheModelPhrase.evaluate(req, res));
        
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Getting cached object for '" + key + "' using cache mode " + cacheMode + " and factory " + factory);
        }
        
        //Load the cache only if cache-all is enabled
        final ConcurrentMap<Tuple<Serializable, K>, Object> cache;
        final Tuple<Serializable, K> compoundCacheKey;
        switch (cacheMode) {
            case NONE: {
                return factory.createObject(key);
            }
            
            default:
            case ONE: {
                cache = null;
                compoundCacheKey = null;
            }
            break;
            
            case ALL: {
                cache = (ConcurrentMap<Tuple<Serializable, K>, Object>) this.cachePhrase.evaluate(req, res);
                final Serializable cacheNamespace = factory.getCacheNamespace(key);
                compoundCacheKey = new Tuple<Serializable, K>(cacheNamespace, key);
            }
            break;
        }
        
        //Determine the object to synchronize around
        final Object syncTarget = factory.getMutex(key);

        //get or create & cache the target object
        V instance = null;
        synchronized (syncTarget) {
            //Get the object from the local variables if no cache is available
            if (cache == null) {
                //Try for a thread-local instance first
                if (this.compareKeys(key, this.threadKeyHolder.get())) {
                    instance = this.threadInstanceHolder.get();
                }
                //Next try for a singleton instance
                else if (this.compareKeys(key, this.key)) {
                    instance = this.instance;
                } 
            }
            //Look in the passed cache for the instance
            else {
                final Object object = cache.get(compoundCacheKey);
                
                //If the cached object is a ThreadLocal use it for the instance
                if (object instanceof ThreadLocal<?>) {
                    instance = ((ThreadLocal<V>) object).get();
                }
                //If not assume it is the instance 
                else {
                    instance = (V) object;
                }
            }
            
            //If no instance was found create and cache one
            if (instance == null) {
                instance = factory.createObject(key);
                final boolean threadSafe = factory.isThreadSafe(key, instance);
                
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Cache miss for '" + key + "' created '" + instance + "' threadSafe=" + threadSafe);
                }
                
                //If no cache is available store the instance in the local variables
                if (cache == null) {
                    if (threadSafe) {
                        this.instance = instance;
                        this.key = key;
                    }
                    else {
                        this.threadInstanceHolder.set(instance);
                        this.threadKeyHolder.set(key);
                    }
                }
                //Cache available store there
                else {
                    if (threadSafe) {
                        cache.put(compoundCacheKey, instance);
                    }
                    else {
                        ThreadLocal<V> threadInstanceHolder = (ThreadLocal<V>)cache.get(compoundCacheKey);
                        if (threadInstanceHolder == null) {
                            threadInstanceHolder = new ThreadLocal<V>();
                            
                            while (true) {
                                Object existing = cache.putIfAbsent(compoundCacheKey, threadInstanceHolder);
                                if (existing == null) {
                                    //nothing existed for that key, put was successful
                                    break;
                                }
                                
                                if (existing instanceof ThreadLocal) {
                                    //Existing ThreadLocal, just use it
                                    threadInstanceHolder = (ThreadLocal)existing;
                                    break;
                                }
                                
                                //something other than a ThreadLocal already exists, try replacing with the ThreadLocal
                                final boolean replaced = cache.replace(compoundCacheKey, threadInstanceHolder, existing);
                                if (replaced) {
                                    //Replace worked!
                                    break;
                                }
                                
                                //Replace didn't work, try the whole process again, yay non-blocking!
                            }
                            
                            if (cache instanceof EvictionAwareCache) {
                                ((EvictionAwareCache) cache).registerCacheEvictionListener(ThreadLocalCacheEvictionListener.INSTANCE);
                            }
                        }

                        threadInstanceHolder.set(instance);
                    }
                }
            }
            else if (this.logger.isDebugEnabled()) {
                this.logger.debug("Cache hit for '" + key + "' using '" + instance + "'");
            }
        }
        
        return instance;
    }
481435
private static <T> ThreadContext<T> getCurrentThreadContext(ThreadContext<T> threadContext)
    {
        return ((ThreadContextImpl<T>) threadContext).get();
    }
336000
function (context, next) {
        if (context.options.force || !context.cached.template) {
            this._tasksQueue.push(Processor._models.task(
                context.cached._id, context.pathname, context.cached, !context.options.wait ? null :
                    function (err, cached) {
                        if (err) return next(err);
                        context.cached = cached;
                        next(null);
                    }
            ));
            if (!context.options.wait)
                next(null);
        }
        else next(null);
    }