Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2003-2010 Terracotta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 
 package net.sf.ehcache.constructs.nonstop;
 
 
Class used by NonStopCache for executing tasks within a timeout limit.

Author(s):
Abhishek Sanoujam
 
 public class NonStopCacheExecutorService {

    
Default number of threads in the thread pool
 
     public static final int DEFAULT_THREAD_POOL_SIZE = 10;

    
Counter used for maintaining number of threads created by default ThreadFactory
 
     protected static final AtomicInteger DEFAULT_FACTORY_COUNT = new AtomicInteger();
 
     private final ExecutorService executorService;
     private final AtomicInteger attachedCachesCount = new AtomicInteger();
     private final DisposeListener disposeListener;
 
     // shutdown executor service when all attached caches are dispose'd -- by default true
     private volatile boolean shutdownWhenNoCachesAttached = true;

    
Default constructor, uses DEFAULT_THREAD_POOL_SIZE number of threads in the pool
 
     public NonStopCacheExecutorService() {
         this();
     }

    
Constructor accepting the maximum number of threads that can be present in the thread pool

Parameters:
threadPoolSize
 
     public NonStopCacheExecutorService(final int threadPoolSize) {
         this(threadPoolSizenew ThreadFactory() {
 
             private final AtomicInteger counter = new AtomicInteger();
 
             public Thread newThread(final Runnable runnable) {
                 Thread thread = new Thread(runnable"Default " + NonStopCacheExecutorService.class.getName() + "-"
                         + .incrementAndGet() + " Executor Thread-" + .incrementAndGet());
                 thread.setDaemon(true);
                 return thread;
             }
         });
     }

    
Constructor accepting a java.util.concurrent.ThreadFactory that will be used to create threads for the pool

Parameters:
threadFactory
 
     public NonStopCacheExecutorService(final ThreadFactory threadFactory) {
         this(threadFactory);
     }

    
Constructor accepting both number of threads and the thread factory to be used

Parameters:
threadPoolSize
threadFactory
    public NonStopCacheExecutorService(final int threadPoolSizefinal ThreadFactory threadFactory) {
        // keepAlive time and maxPoolSize is ignored (does not have any effect) as we are using an unbounded work queue
        this(new ThreadPoolExecutor(threadPoolSizethreadPoolSize..,
                new LinkedBlockingQueue<Runnable>(), threadFactory));
    }

    
This constructor is private as executorService's are shut down when all associated caches are disposed. Accepting executorServices from outside and shutting it down may hamper other app tasks scheduled using same executor service.

Parameters:
executorService
    private NonStopCacheExecutorService(final ExecutorService executorService) {
        if (executorService == null) {
            throw new IllegalArgumentException("ExecutorService cannot be null");
        }
        this. = executorService;
        this. = new DisposeListener();
    }

    
Execute a java.util.concurrent.Callable task with timeout. If the task does not complete within the timeout specified, throws a java.util.concurrent.TimeoutException

Parameters:
<V>
callable
timeoutValueInMillis
Returns:
the return value from the callable
Throws:
java.util.concurrent.TimeoutException
net.sf.ehcache.CacheException
java.lang.InterruptedException
    public <V> V execute(final Callable<V> callablefinal long timeoutValueInMillisthrows TimeoutExceptionCacheException,
            InterruptedException {
        int attempt = 0;
        V result = null;
        long startTime = System.currentTimeMillis();
        while (true) {
            try {
                attempt++;
                result = .submit(callable).get(timeoutValueInMillis.);
                break;
            } catch (InterruptedException e) {
                // XXX: do something here?
                throw e;
            } catch (RejectedExecutionException e) {
                // if the executor rejects (too many tasks executing), try until timed out
                long now = System.currentTimeMillis();
                if (now - startTime > timeoutValueInMillis) {
                    throw new TaskNotSubmittedTimeoutException(attempt);
                } else {
                    continue;
                }
            } catch (ExecutionException e) {
                throw new CacheException(e.getCause());
            } catch (TimeoutException e) {
                // rethrow timeout exception
                throw e;
            }
        }
        return result;
    }

    
Associates a cache with this NonStopCacheExecutorService. The thread pool in NonStopCacheExecutorService shuts down once all the net.sf.ehcache.Ehcache's associated with this NonStopCacheExecutorService are disposed

Parameters:
cache
    public void attachCache(Ehcache cache) {
    }
    private void attachedCacheDisposed() {
            .shutdown();
        }
    }

    
Set whether to shutdown or not the thread pool when all associated net.sf.ehcache.Ehcache's are disposed. By default its true

Parameters:
shutdownWhenNoCachesAttached if true, shuts down the thread pool when no cache is associated with this NonStopCacheExecutorService
    public void setShutdownWhenNoCachesAttached(boolean shutdownWhenNoCachesAttached) {
        this. = shutdownWhenNoCachesAttached;
    }

    
package protected method -- used for testing only

Returns:
        return this.;
    }

    
Private listener class for Cache.dispose()

Author(s):
Abhishek Sanoujam
    private class DisposeListener implements CacheEventListener {

        
Call back to the NonStopCacheExecutorService that cache has disposed
        public void dispose() {
            attachedCacheDisposed();
        }
        @Override
        
. Throws CloneNotSupportedException
        public Object clone() throws CloneNotSupportedException {
            super.clone();
            throw new CloneNotSupportedException();
        }

        
no-op
        public void notifyElementEvicted(Ehcache cacheElement element) {
            // no-op
        }

        
no-op
        public void notifyElementExpired(Ehcache cacheElement element) {
            // no-op
        }

        
no-op
        public void notifyElementPut(Ehcache cacheElement elementthrows CacheException {
            // no-op
        }

        
no-op
        public void notifyElementRemoved(Ehcache cacheElement elementthrows CacheException {
            // no-op
        }

        
no-op
        public void notifyElementUpdated(Ehcache cacheElement elementthrows CacheException {
            // no-op
        }

        
no-op
        public void notifyRemoveAll(Ehcache cache) {
            // no-op
        }
    }
New to GrepCode? Check out our FAQ X