001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.impl;
018
019import java.util.Map;
020import java.util.concurrent.CompletableFuture;
021
022import org.apache.camel.AsyncCallback;
023import org.apache.camel.AsyncProcessor;
024import org.apache.camel.AsyncProducerCallback;
025import org.apache.camel.CamelContext;
026import org.apache.camel.Endpoint;
027import org.apache.camel.Exchange;
028import org.apache.camel.ExchangePattern;
029import org.apache.camel.FailedToCreateProducerException;
030import org.apache.camel.Processor;
031import org.apache.camel.Producer;
032import org.apache.camel.ProducerCallback;
033import org.apache.camel.ServicePoolAware;
034import org.apache.camel.processor.CamelInternalProcessor;
035import org.apache.camel.processor.SharedCamelInternalProcessor;
036import org.apache.camel.spi.EndpointUtilizationStatistics;
037import org.apache.camel.spi.ServicePool;
038import org.apache.camel.support.ServiceSupport;
039import org.apache.camel.util.AsyncProcessorConverterHelper;
040import org.apache.camel.util.CamelContextHelper;
041import org.apache.camel.util.EventHelper;
042import org.apache.camel.util.LRUCache;
043import org.apache.camel.util.LRUCacheFactory;
044import org.apache.camel.util.ServiceHelper;
045import org.apache.camel.util.StopWatch;
046import org.slf4j.Logger;
047import org.slf4j.LoggerFactory;
048
049/**
050 * Cache containing created {@link Producer}.
051 *
052 * @version
053 */
054public class ProducerCache extends ServiceSupport {
055    private static final Logger LOG = LoggerFactory.getLogger(ProducerCache.class);
056
057    private final CamelContext camelContext;
058    private final ServicePool<Endpoint, Producer> pool;
059    private final Map<String, Producer> producers;
060    private final Object source;
061    private final SharedCamelInternalProcessor internalProcessor;
062
063    private EndpointUtilizationStatistics statistics;
064    private boolean eventNotifierEnabled = true;
065    private boolean extendedStatistics;
066    private int maxCacheSize;
067    private boolean stopServicePool;
068
069    public ProducerCache(Object source, CamelContext camelContext) {
070        this(source, camelContext, CamelContextHelper.getMaximumCachePoolSize(camelContext));
071    }
072
073    public ProducerCache(Object source, CamelContext camelContext, int cacheSize) {
074        this(source, camelContext, null, createLRUCache(cacheSize));
075    }
076
077    public ProducerCache(Object source, CamelContext camelContext, Map<String, Producer> cache) {
078        this(source, camelContext, null, cache);
079    }
080
081    public ProducerCache(Object source, CamelContext camelContext, ServicePool<Endpoint, Producer> producerServicePool, Map<String, Producer> cache) {
082        this.source = source;
083        this.camelContext = camelContext;
084        if (producerServicePool == null) {
085            // use shared producer pool which lifecycle is managed by CamelContext
086            this.pool = camelContext.getProducerServicePool();
087            this.stopServicePool = false;
088        } else {
089            this.pool = producerServicePool;
090            this.stopServicePool = true;
091        }
092        this.producers = cache;
093        if (producers instanceof LRUCache) {
094            maxCacheSize = ((LRUCache) producers).getMaxCacheSize();
095        }
096
097        // only if JMX is enabled
098        if (camelContext.getManagementStrategy().getManagementAgent() != null) {
099            this.extendedStatistics = camelContext.getManagementStrategy().getManagementAgent().getStatisticsLevel().isExtended();
100        } else {
101            this.extendedStatistics = false;
102        }
103
104        // internal processor used for sending
105        internalProcessor = new SharedCamelInternalProcessor(new CamelInternalProcessor.UnitOfWorkProcessorAdvice(null));
106    }
107
108    public boolean isEventNotifierEnabled() {
109        return eventNotifierEnabled;
110    }
111
112    /**
113     * Whether {@link org.apache.camel.spi.EventNotifier} is enabled
114     */
115    public void setEventNotifierEnabled(boolean eventNotifierEnabled) {
116        this.eventNotifierEnabled = eventNotifierEnabled;
117    }
118
119    public boolean isExtendedStatistics() {
120        return extendedStatistics;
121    }
122
123    /**
124     * Whether extended JMX statistics is enabled for {@link org.apache.camel.spi.EndpointUtilizationStatistics}
125     */
126    public void setExtendedStatistics(boolean extendedStatistics) {
127        this.extendedStatistics = extendedStatistics;
128    }
129
130    /**
131     * Creates the {@link LRUCache} to be used.
132     * <p/>
133     * This implementation returns a {@link LRUCache} instance.
134
135     * @param cacheSize the cache size
136     * @return the cache
137     */
138    @SuppressWarnings("unchecked")
139    protected static Map<String, Producer> createLRUCache(int cacheSize) {
140        // Use a regular cache as we want to ensure that the lifecycle of the producers
141        // being cache is properly handled, such as they are stopped when being evicted
142        // or when this cache is stopped. This is needed as some producers requires to
143        // be stopped so they can shutdown internal resources that otherwise may cause leaks
144        return LRUCacheFactory.newLRUCache(cacheSize);
145    }
146
147    public CamelContext getCamelContext() {
148        return camelContext;
149    }
150
151    /**
152     * Gets the source which uses this cache
153     *
154     * @return the source
155     */
156    public Object getSource() {
157        return source;
158    }
159
160    /**
161     * Acquires a pooled producer which you <b>must</b> release back again after usage using the
162     * {@link #releaseProducer(org.apache.camel.Endpoint, org.apache.camel.Producer)} method.
163     *
164     * @param endpoint the endpoint
165     * @return the producer
166     */
167    public Producer acquireProducer(Endpoint endpoint) {
168        return doGetProducer(endpoint, true);
169    }
170
171    /**
172     * Releases an acquired producer back after usage.
173     *
174     * @param endpoint the endpoint
175     * @param producer the producer to release
176     * @throws Exception can be thrown if error stopping producer if that was needed.
177     */
178    public void releaseProducer(Endpoint endpoint, Producer producer) throws Exception {
179        if (producer instanceof ServicePoolAware) {
180            // release back to the pool
181            pool.release(endpoint, producer);
182        } else if (!producer.isSingleton()) {
183            // stop and shutdown non-singleton producers as we should not leak resources
184            ServiceHelper.stopAndShutdownService(producer);
185        }
186    }
187
188    /**
189     * Starts the {@link Producer} to be used for sending to the given endpoint
190     * <p/>
191     * This can be used to early start the {@link Producer} to ensure it can be created,
192     * such as when Camel is started. This allows to fail fast in case the {@link Producer}
193     * could not be started.
194     *
195     * @param endpoint the endpoint to send the exchange to
196     * @throws Exception is thrown if failed to create or start the {@link Producer}
197     */
198    public void startProducer(Endpoint endpoint) throws Exception {
199        Producer producer = acquireProducer(endpoint);
200        releaseProducer(endpoint, producer);
201    }
202
203    /**
204     * Sends the exchange to the given endpoint.
205     * <p>
206     * This method will <b>not</b> throw an exception. If processing of the given
207     * Exchange failed then the exception is stored on the provided Exchange
208     *
209     * @param endpoint the endpoint to send the exchange to
210     * @param exchange the exchange to send
211     */
212    public void send(Endpoint endpoint, Exchange exchange) {
213        sendExchange(endpoint, null, null, null, exchange);
214    }
215
216    /**
217     * Sends an exchange to an endpoint using a supplied
218     * {@link Processor} to populate the exchange
219     * <p>
220     * This method will <b>not</b> throw an exception. If processing of the given
221     * Exchange failed then the exception is stored on the return Exchange
222     *
223     * @param endpoint the endpoint to send the exchange to
224     * @param processor the transformer used to populate the new exchange
225     * @throws org.apache.camel.CamelExecutionException is thrown if sending failed
226     * @return the exchange
227     */
228    public Exchange send(Endpoint endpoint, Processor processor) {
229        return sendExchange(endpoint, null, processor, null, null);
230    }
231
232    /**
233     * Sends an exchange to an endpoint using a supplied
234     * {@link Processor} to populate the exchange
235     * <p>
236     * This method will <b>not</b> throw an exception. If processing of the given
237     * Exchange failed then the exception is stored on the return Exchange
238     *
239     * @param endpoint the endpoint to send the exchange to
240     * @param pattern the message {@link ExchangePattern} such as
241     *   {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut}
242     * @param processor the transformer used to populate the new exchange
243     * @return the exchange
244     */
245    public Exchange send(Endpoint endpoint, ExchangePattern pattern, Processor processor) {
246        return sendExchange(endpoint, pattern, processor, null, null);
247    }
248
249    /**
250     * Sends an exchange to an endpoint using a supplied
251     * {@link Processor} to populate the exchange
252     * <p>
253     * This method will <b>not</b> throw an exception. If processing of the given
254     * Exchange failed then the exception is stored on the return Exchange
255     *
256     * @param endpoint the endpoint to send the exchange to
257     * @param pattern the message {@link ExchangePattern} such as
258     *   {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut}
259     * @param processor the transformer used to populate the new exchange
260     * @param resultProcessor a processor to process the exchange when the send is complete.
261     * @return the exchange
262     */
263    public Exchange send(Endpoint endpoint, ExchangePattern pattern, Processor processor, Processor resultProcessor) {
264        return sendExchange(endpoint, pattern, processor, resultProcessor, null);
265    }
266
267    /**
268     * Asynchronously sends an exchange to an endpoint using a supplied
269     * {@link Processor} to populate the exchange
270     * <p>
271     * This method will <b>neither</b> throw an exception <b>nor</b> complete future exceptionally.
272     * If processing of the given Exchange failed then the exception is stored on the return Exchange
273     *
274     * @param endpoint        the endpoint to send the exchange to
275     * @param pattern         the message {@link ExchangePattern} such as
276     *                        {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut}
277     * @param processor       the transformer used to populate the new exchange
278     * @param resultProcessor a processor to process the exchange when the send is complete.
279     * @param future          the preexisting future to complete when processing is done or null if to create new one
280     * @return future that completes with exchange when processing is done. Either passed into future parameter
281     *              or new one if parameter was null
282     */
283    public CompletableFuture<Exchange> asyncSend(Endpoint endpoint, ExchangePattern pattern, Processor processor, Processor resultProcessor,
284                                                 CompletableFuture<Exchange> future) {
285        return asyncSendExchange(endpoint, pattern, processor, resultProcessor, null, future);
286    }
287
288    /**
289     * Asynchronously sends an exchange to an endpoint using a supplied
290     * {@link Processor} to populate the exchange
291     * <p>
292     * This method will <b>neither</b> throw an exception <b>nor</b> complete future exceptionally.
293     * If processing of the given Exchange failed then the exception is stored on the return Exchange
294     *
295     * @param endpoint        the endpoint to send the exchange to
296     * @param pattern         the message {@link ExchangePattern} such as
297     *                        {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut}
298     * @param processor       the transformer used to populate the new exchange
299     * @param resultProcessor a processor to process the exchange when the send is complete.
300     * @param exchange        an exchange to use in processing. Exchange will be created if parameter is null.
301     * @param future          the preexisting future to complete when processing is done or null if to create new one
302     * @return future that completes with exchange when processing is done. Either passed into future parameter
303     *              or new one if parameter was null
304     */
305    public CompletableFuture<Exchange> asyncSendExchange(final Endpoint endpoint, ExchangePattern pattern,
306                                                         final Processor processor, final Processor resultProcessor, Exchange exchange,
307                                                         CompletableFuture<Exchange> future) {
308        AsyncCallbackToCompletableFutureAdapter<Exchange> futureAdapter = new AsyncCallbackToCompletableFutureAdapter<>(future, exchange);
309        doInAsyncProducer(endpoint, exchange, pattern, futureAdapter,
310            (producer, asyncProducer, innerExchange, exchangePattern, producerCallback) -> {
311                if (innerExchange == null) {
312                    innerExchange = pattern != null
313                            ? producer.getEndpoint().createExchange(pattern)
314                            : producer.getEndpoint().createExchange();
315                    futureAdapter.setResult(innerExchange);
316                }
317
318                if (processor != null) {
319                    // lets populate using the processor callback
320                    AsyncProcessor asyncProcessor = AsyncProcessorConverterHelper.convert(processor);
321                    try {
322                        final Exchange finalExchange = innerExchange;
323                        asyncProcessor.process(innerExchange,
324                            doneSync -> asyncDispatchExchange(endpoint, producer, resultProcessor,
325                                    finalExchange, producerCallback));
326                        return false;
327                    } catch (Throwable e) {
328                        // populate failed so return
329                        innerExchange.setException(e);
330                        producerCallback.done(true);
331                        return true;
332                    }
333                }
334
335                return asyncDispatchExchange(endpoint, producer, resultProcessor, innerExchange, producerCallback);
336            });
337        return futureAdapter.getFuture();
338    }
339
340    /**
341     * Sends an exchange to an endpoint using a supplied callback, using the synchronous processing.
342     * <p/>
343     * If an exception was thrown during processing, it would be set on the given Exchange
344     *
345     * @param endpoint  the endpoint to send the exchange to
346     * @param exchange  the exchange, can be <tt>null</tt> if so then create a new exchange from the producer
347     * @param pattern   the exchange pattern, can be <tt>null</tt>
348     * @param callback  the callback
349     * @return the response from the callback
350     * @see #doInAsyncProducer(org.apache.camel.Endpoint, org.apache.camel.Exchange, org.apache.camel.ExchangePattern, org.apache.camel.AsyncCallback, org.apache.camel.AsyncProducerCallback)
351     */
352    public <T> T doInProducer(Endpoint endpoint, Exchange exchange, ExchangePattern pattern, ProducerCallback<T> callback) {
353        T answer = null;
354
355        // get the producer and we do not mind if its pooled as we can handle returning it back to the pool
356        Producer producer = acquireProducer(endpoint);
357
358        if (producer == null) {
359            if (isStopped()) {
360                LOG.warn("Ignoring exchange sent after processor is stopped: {}", exchange);
361                return null;
362            } else {
363                throw new IllegalStateException("No producer, this processor has not been started: " + this);
364            }
365        }
366
367        try {
368            // invoke the callback
369            answer = callback.doInProducer(producer, exchange, pattern);
370        } catch (Throwable e) {
371            if (exchange != null) {
372                exchange.setException(e);
373            }
374        } finally {
375            try {
376                releaseProducer(endpoint, producer);
377            } catch (Exception e) {
378                // ignore and continue
379                LOG.warn("Error stopping/shutting down producer: " + producer, e);
380            }
381        }
382
383        return answer;
384    }
385
386    /**
387     * Sends an exchange to an endpoint using a supplied callback supporting the asynchronous routing engine.
388     * <p/>
389     * If an exception was thrown during processing, it would be set on the given Exchange
390     *
391     * @param endpoint         the endpoint to send the exchange to
392     * @param exchange         the exchange, can be <tt>null</tt> if so then create a new exchange from the producer
393     * @param pattern          the exchange pattern, can be <tt>null</tt>
394     * @param callback         the asynchronous callback
395     * @param producerCallback the producer template callback to be executed
396     * @return (doneSync) <tt>true</tt> to continue execute synchronously, <tt>false</tt> to continue being executed asynchronously
397     */
398    public boolean doInAsyncProducer(final Endpoint endpoint, final Exchange exchange, final ExchangePattern pattern,
399                                     final AsyncCallback callback, final AsyncProducerCallback producerCallback) {
400
401        Producer target;
402        try {
403            // get the producer and we do not mind if its pooled as we can handle returning it back to the pool
404            target = acquireProducer(endpoint);
405
406            if (target == null) {
407                if (isStopped()) {
408                    LOG.warn("Ignoring exchange sent after processor is stopped: {}", exchange);
409                    callback.done(true);
410                    return true;
411                } else {
412                    exchange.setException(new IllegalStateException("No producer, this processor has not been started: " + this));
413                    callback.done(true);
414                    return true;
415                }
416            }
417        } catch (Throwable e) {
418            exchange.setException(e);
419            callback.done(true);
420            return true;
421        }
422
423        final Producer producer = target;
424
425        try {
426            StopWatch sw = null;
427            if (eventNotifierEnabled && exchange != null) {
428                boolean sending = EventHelper.notifyExchangeSending(exchange.getContext(), exchange, endpoint);
429                if (sending) {
430                    sw = new StopWatch();
431                }
432            }
433
434            // record timing for sending the exchange using the producer
435            final StopWatch watch = sw;
436
437            // invoke the callback
438            AsyncProcessor asyncProcessor = AsyncProcessorConverterHelper.convert(producer);
439            return producerCallback.doInAsyncProducer(producer, asyncProcessor, exchange, pattern, doneSync -> {
440                try {
441                    if (eventNotifierEnabled && watch != null) {
442                        long timeTaken = watch.taken();
443                        // emit event that the exchange was sent to the endpoint
444                        EventHelper.notifyExchangeSent(exchange.getContext(), exchange, endpoint, timeTaken);
445                    }
446                    try {
447                        releaseProducer(endpoint, producer);
448                    } catch (Exception e) {
449                        // ignore and continue
450                        LOG.warn("Error stopping/shutting down producer: " + producer, e);
451                    }
452                } finally {
453                    callback.done(doneSync);
454                }
455            });
456        } catch (Throwable e) {
457            // ensure exceptions is caught and set on the exchange
458            if (exchange != null) {
459                exchange.setException(e);
460            }
461            callback.done(true);
462            return true;
463        }
464    }
465
466    protected boolean asyncDispatchExchange(final Endpoint endpoint, Producer producer,
467                                            final Processor resultProcessor, Exchange exchange, AsyncCallback callback) {
468        // now lets dispatch
469        LOG.debug(">>>> {} {}", endpoint, exchange);
470
471        // set property which endpoint we send to
472        exchange.setProperty(Exchange.TO_ENDPOINT, endpoint.getEndpointUri());
473
474        // send the exchange using the processor
475        try {
476            if (eventNotifierEnabled) {
477                callback = new EventNotifierCallback(callback, exchange, endpoint);
478            }
479            AsyncProcessor target = prepareProducer(producer);
480            // invoke the asynchronous method
481            return internalProcessor.process(exchange, callback, target, resultProcessor);
482        } catch (Throwable e) {
483            // ensure exceptions is caught and set on the exchange
484            exchange.setException(e);
485            callback.done(true);
486            return true;
487        }
488
489    }
490
491    protected Exchange sendExchange(final Endpoint endpoint, ExchangePattern pattern,
492                                    final Processor processor, final Processor resultProcessor, Exchange exchange) {
493        return doInProducer(endpoint, exchange, pattern, new ProducerCallback<Exchange>() {
494            public Exchange doInProducer(Producer producer, Exchange exchange, ExchangePattern pattern) {
495                if (exchange == null) {
496                    exchange = pattern != null ? producer.getEndpoint().createExchange(pattern) : producer.getEndpoint().createExchange();
497                }
498
499                if (processor != null) {
500                    // lets populate using the processor callback
501                    try {
502                        processor.process(exchange);
503                    } catch (Throwable e) {
504                        // populate failed so return
505                        exchange.setException(e);
506                        return exchange;
507                    }
508                }
509
510                // now lets dispatch
511                LOG.debug(">>>> {} {}", endpoint, exchange);
512
513                // set property which endpoint we send to
514                exchange.setProperty(Exchange.TO_ENDPOINT, endpoint.getEndpointUri());
515
516                // send the exchange using the processor
517                StopWatch watch = null;
518                try {
519                    if (eventNotifierEnabled) {
520                        boolean sending = EventHelper.notifyExchangeSending(exchange.getContext(), exchange, endpoint);
521                        if (sending) {
522                            watch = new StopWatch();
523                        }
524                    }
525
526                    AsyncProcessor target = prepareProducer(producer);
527                    // invoke the synchronous method
528                    internalProcessor.process(exchange, target, resultProcessor);
529
530                } catch (Throwable e) {
531                    // ensure exceptions is caught and set on the exchange
532                    exchange.setException(e);
533                } finally {
534                    // emit event that the exchange was sent to the endpoint
535                    if (eventNotifierEnabled && watch != null) {
536                        long timeTaken = watch.taken();
537                        EventHelper.notifyExchangeSent(exchange.getContext(), exchange, endpoint, timeTaken);
538                    }
539                }
540                return exchange;
541            }
542        });
543    }
544
545    protected AsyncProcessor prepareProducer(Producer producer) {
546        return AsyncProcessorConverterHelper.convert(producer);
547    }
548
549    protected synchronized Producer doGetProducer(Endpoint endpoint, boolean pooled) {
550        String key = endpoint.getEndpointUri();
551        Producer answer = producers.get(key);
552        if (pooled && answer == null) {
553            // try acquire from connection pool
554            answer = pool.acquire(endpoint);
555        }
556
557        if (answer == null) {
558            // create a new producer
559            try {
560                answer = endpoint.createProducer();
561                // add as service to CamelContext so its managed via JMX
562                boolean add = answer.isSingleton() || answer instanceof ServicePoolAware;
563                if (add) {
564                    // (false => we and handling the lifecycle of the producer in this cache)
565                    getCamelContext().addService(answer, false);
566                } else {
567                    // fallback and start producer manually
568                    ServiceHelper.startService(answer);
569                }
570            } catch (Throwable e) {
571                throw new FailedToCreateProducerException(endpoint, e);
572            }
573
574            // add producer to cache or pool if applicable
575            if (pooled && answer instanceof ServicePoolAware) {
576                LOG.debug("Adding to producer service pool with key: {} for producer: {}", endpoint, answer);
577                answer = pool.addAndAcquire(endpoint, answer);
578            } else if (answer.isSingleton()) {
579                LOG.debug("Adding to producer cache with key: {} for producer: {}", endpoint, answer);
580                producers.put(key, answer);
581            }
582        }
583
584        if (answer != null) {
585            // record statistics
586            if (extendedStatistics) {
587                statistics.onHit(key);
588            }
589        }
590
591        return answer;
592    }
593
594    protected void doStart() throws Exception {
595        if (extendedStatistics) {
596            int max = maxCacheSize == 0 ? CamelContextHelper.getMaximumCachePoolSize(camelContext) : maxCacheSize;
597            statistics = new DefaultEndpointUtilizationStatistics(max);
598        }
599
600        ServiceHelper.startServices(producers.values());
601        ServiceHelper.startServices(statistics, pool);
602    }
603
604    protected void doStop() throws Exception {
605        // when stopping we intend to shutdown
606        ServiceHelper.stopAndShutdownService(statistics);
607        if (stopServicePool) {
608            ServiceHelper.stopAndShutdownService(pool);
609        }
610        try {
611            ServiceHelper.stopAndShutdownServices(producers.values());
612        } finally {
613            // ensure producers are removed, and also from JMX
614            for (Producer producer : producers.values()) {
615                getCamelContext().removeService(producer);
616            }
617        }
618        producers.clear();
619        if (statistics != null) {
620            statistics.clear();
621        }
622    }
623
624    /**
625     * Returns the current size of the cache
626     *
627     * @return the current size
628     */
629    public int size() {
630        int size = producers.size();
631        size += pool.size();
632
633        LOG.trace("size = {}", size);
634        return size;
635    }
636
637    /**
638     * Gets the maximum cache size (capacity).
639     * <p/>
640     * Will return <tt>-1</tt> if it cannot determine this if a custom cache was used.
641     *
642     * @return the capacity
643     */
644    public int getCapacity() {
645        int capacity = -1;
646        if (producers instanceof LRUCache) {
647            LRUCache<String, Producer> cache = (LRUCache<String, Producer>) producers;
648            capacity = cache.getMaxCacheSize();
649        }
650        return capacity;
651    }
652
653    /**
654     * Gets the cache hits statistic
655     * <p/>
656     * Will return <tt>-1</tt> if it cannot determine this if a custom cache was used.
657     *
658     * @return the hits
659     */
660    public long getHits() {
661        long hits = -1;
662        if (producers instanceof LRUCache) {
663            LRUCache<String, Producer> cache = (LRUCache<String, Producer>) producers;
664            hits = cache.getHits();
665        }
666        return hits;
667    }
668
669    /**
670     * Gets the cache misses statistic
671     * <p/>
672     * Will return <tt>-1</tt> if it cannot determine this if a custom cache was used.
673     *
674     * @return the misses
675     */
676    public long getMisses() {
677        long misses = -1;
678        if (producers instanceof LRUCache) {
679            LRUCache<String, Producer> cache = (LRUCache<String, Producer>) producers;
680            misses = cache.getMisses();
681        }
682        return misses;
683    }
684
685    /**
686     * Gets the cache evicted statistic
687     * <p/>
688     * Will return <tt>-1</tt> if it cannot determine this if a custom cache was used.
689     *
690     * @return the evicted
691     */
692    public long getEvicted() {
693        long evicted = -1;
694        if (producers instanceof LRUCache) {
695            LRUCache<String, Producer> cache = (LRUCache<String, Producer>) producers;
696            evicted = cache.getEvicted();
697        }
698        return evicted;
699    }
700
701    /**
702     * Resets the cache statistics
703     */
704    public void resetCacheStatistics() {
705        if (producers instanceof LRUCache) {
706            LRUCache<String, Producer> cache = (LRUCache<String, Producer>) producers;
707            cache.resetStatistics();
708        }
709        if (statistics != null) {
710            statistics.clear();
711        }
712    }
713
714    /**
715     * Purges this cache
716     */
717    public synchronized void purge() {
718        producers.clear();
719        pool.purge();
720        if (statistics != null) {
721            statistics.clear();
722        }
723    }
724
725    /**
726     * Cleanup the cache (purging stale entries)
727     */
728    public void cleanUp() {
729        if (producers instanceof LRUCache) {
730            LRUCache<String, Producer> cache = (LRUCache<String, Producer>) producers;
731            cache.cleanUp();
732        }
733    }
734
735    public EndpointUtilizationStatistics getEndpointUtilizationStatistics() {
736        return statistics;
737    }
738
739    @Override
740    public String toString() {
741        return "ProducerCache for source: " + source + ", capacity: " + getCapacity();
742    }
743
744}