Example usage for java.util.concurrent RejectedExecutionHandler RejectedExecutionHandler

List of usage examples for java.util.concurrent RejectedExecutionHandler RejectedExecutionHandler

Introduction

In this page you can find the example usage for java.util.concurrent RejectedExecutionHandler RejectedExecutionHandler.

Prototype

RejectedExecutionHandler

Source Link

Usage

From source file:org.janusgraph.TestBed.java

/**
 * @param args//from  w w  w  . jav a  2 s.  com
 * @throws java.io.IOException
 */
public static void main(String[] args) throws Exception {
    Method method = TestBed.class.getMethod("getInt", int.class, int.class);
    AnnotatedType rt = method.getAnnotatedReturnType();
    System.out.println(rt.getType());
    System.out.println(rt.getAnnotations().length);
    System.out.println(method.getAnnotations().length);
    for (int i = 0; i < method.getAnnotations().length; i++) {
        System.out.println(method.getAnnotations()[i]);
    }

    //        String[] s = {"a","b","c","d","e","f","g","h","i","x","u"};
    //        int len = s.length;
    //        Random random = new Random();
    //
    //        Context c = new Context(new ObserverManager(),Observer.NO_OP);
    //        //Warmup
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long before = System.nanoTime();
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long total = System.nanoTime()-before;
    //        System.out.println("Total time: " + total/1000000);

    System.exit(0);

    final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1, new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            r.run();
        }
    });
    ScheduledFuture future = exe.scheduleWithFixedDelay(new Runnable() {
        AtomicInteger atomicInt = new AtomicInteger(0);

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    exe.submit(new Runnable() {

                        private final int number = atomicInt.incrementAndGet();

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(150);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(number);
                        }
                    });
                    System.out.println("Submitted: " + i);
                    //                    doSomethingExpensive(20);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 0, 1, TimeUnit.SECONDS);
    Thread.sleep(10000);
    //        future.get(1,TimeUnit.SECONDS);
    System.out.println("Cancel: " + future.cancel(false));
    System.out.println("Done: " + future.isDone());
    exe.shutdown();
    //        Thread.sleep(2000);
    System.out.println("Terminate: " + exe.awaitTermination(5, TimeUnit.SECONDS));
    System.out.println("DONE");
    NonBlockingHashMapLong<String> id1 = new NonBlockingHashMapLong<String>(128);
    ConcurrentHashMap<Long, String> id2 = new ConcurrentHashMap<Long, String>(128, 0.75f, 2);

}

From source file:org.polymap.core.runtime.UnboundPoolExecutor.java

public static ExecutorService newInstance() {
    final int procs = Runtime.getRuntime().availableProcessors();
    final int maxThreads = procs * MAX_THREADS_PER_PROC;

    // thread factory
    ThreadFactory threadFactory = new ThreadFactory() {
        volatile int threadNumber = 0;

        public Thread newThread(Runnable r) {
            String prefix = "polymap-";
            Thread t = new Thread(r, prefix + threadNumber++);
            t.setDaemon(false);//ww w. ja va  2 s. c  o m
            t.setPriority(DEFAULT_THREAD_PRIORITY);
            return t;
        }
    };

    // thread pool
    ThreadPoolExecutor executor = new ThreadPoolExecutor(procs, maxThreads, 180L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), threadFactory);

    // rejected? -> wait and try again
    executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        Random rand = new Random();

        public void rejectedExecution(Runnable r, ThreadPoolExecutor _executor) {
            do {
                try {
                    Thread.sleep(rand.nextInt(1000) + 100);
                } catch (InterruptedException e) {
                }
            } while (_executor.getActiveCount() >= maxThreads);

            _executor.execute(r);
        }
    });

    //executor.allowCoreThreadTimeOut( true );        
    return executor;
}

From source file:com.kurento.kmf.content.internal.ContentApiExecutorService.java

/**
 * Post constructor method; instantiate thread pool.
 * // w  ww .j  ava2s  . c  o m
 * @throws Exception
 *             Error in the creation of the thread pool
 */
@PostConstruct
public void afterPropertiesSet() throws Exception {
    executor = new ThreadPoolExecutor(config.getPoolCoreSize(), config.getPoolMaxSize(),
            config.getPoolExecutionTimeout(), TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(config.getPoolMaxQueueSize()), new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    ((RejectableRunnable) r).onExecutionRejected();
                }
            });
}

From source file:com.kurento.kmf.thrift.internal.ThriftInterfaceExecutorService.java

/**
 * Post constructor method; instantiate thread pool.
 * //w ww .ja  v  a 2s  . com
 * @throws Exception
 *             Error in the creation of the thread pool
 */
@PostConstruct
public void afterPropertiesSet() throws Exception {
    executor = new ThreadPoolExecutor(config.getPoolCoreSize(), config.getPoolMaxSize(),
            config.getPoolExecutionTimeout(), TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(config.getPoolMaxQueueSize()), new RejectedExecutionHandler() {

                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor exec) {
                    log.warn("Execution is blocked because the thread bounds and queue capacities are reached");
                }
            });
}

From source file:com.nextgis.maplib.display.SimpleFeatureRenderer.java

@Override
public void runDraw(final GISDisplay display) {
    GeoEnvelope env = display.getBounds();
    final VectorLayer vectorLayer = (VectorLayer) mLayer;
    GeoEnvelope layerEnv = vectorLayer.getExtents();

    if (!env.intersects(layerEnv)) {
        vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
        return;// ww w  .  j  av a 2s.  c o  m
    }

    //add drawing routine
    final List<VectorCacheItem> cache = vectorLayer.getVectorCache();

    //TODO: more than one thread for drawing (divide the geometry cache array on several parts)
    //TODO: think about display syncronization in drawing points/lines/polygons

    mDrawThreadPool = new ThreadPoolExecutor(1, 1, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT,
            new LinkedBlockingQueue<Runnable>(), new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    try {
                        executor.getQueue().put(r);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        //throw new RuntimeException("Interrupted while submitting task", e);
                    }
                }
            });

    if (cache.size() == 0) {
        vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
        return;
    }

    mDrawThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

            for (int i = 0; i < cache.size(); i++) {
                VectorCacheItem item = cache.get(i);

                GeoGeometry geometry = item.getGeoGeometry();
                mStyle.onDraw(geometry, display);

                synchronized (mLayer) {
                    float percent = (float) i / cache.size();
                    vectorLayer.onDrawFinished(vectorLayer.getId(), percent);
                }

                vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
                //Log.d(TAG, "percent: " + percent + " complete: " + mDrawThreadPool.getCompletedTaskCount() + " task count: " + mDrawThreadPool.getTaskCount());
            }
        }
    });
}

From source file:com.taobao.tddl.common.sync.RowBasedReplicater.java

public void init() {
    /**//from w w w  .  java  2 s .com
     * CallerRunsPolicy: execute
     */
    replicationExecutor = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(workQueueSize), new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * LogDiscardPolicy
     */
    deleteSyncLogExecutor = new ThreadPoolExecutor(1, 2, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(10), new RejectedExecutionHandler() {
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    logger.warn("A DeleteSyncLogTask discarded");
                }
            });
    updateSyncLogExecutor = new ThreadPoolExecutor(1, 2, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(10), new RejectedExecutionHandler() {
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    logger.warn("A UpdateSyncLogTask discarded");
                }
            });

    /**
     * 
     */
    final BucketTaker<RowBasedReplicationContext> deleteBucketTaker = new BucketTaker<RowBasedReplicationContext>(
            deleteSyncLogExecutor) {
        @Override
        public Runnable createTakeAwayTask(Collection<RowBasedReplicationContext> list) {
            return new DeleteSyncLogTask(list);
        }

    };
    final BucketTaker<RowBasedReplicationContext> updateBucketTaker = new BucketTaker<RowBasedReplicationContext>(
            updateSyncLogExecutor) {

        @Override
        public Runnable createTakeAwayTask(Collection<RowBasedReplicationContext> list) {
            return new UpdateSyncLogTask(list);
        }

    };
    deleteBucketSwitcher = new NoStrictBucketSwitcher<RowBasedReplicationContext>(deleteBucketTaker,
            DEFAULT_BATCH_DELETE_SIZE);
    updateBucketSwitcher = new NoStrictBucketSwitcher<RowBasedReplicationContext>(updateBucketTaker,
            DEFAULT_BATCH_UPDATE_SIZE);

    TDDLMBeanServer.registerMBean(this, "Replicater"); //JMX
}

From source file:org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder.java

/**
 * @deprecated This method is only used from configuration modules and thus callers of it
 *             should use service injection to make the executor configurable.
 *//*from   w  w  w  .jav  a2  s .c  o m*/
@Deprecated
public static synchronized ListeningExecutorService getDefaultNotificationExecutor() {

    if (NOTIFICATION_EXECUTOR == null) {
        int queueSize = MAX_NOTIFICATION_QUEUE_SIZE;
        final String queueValue = System.getProperty(NOTIFICATION_QUEUE_SIZE_PROPERTY);
        if (StringUtils.isNotBlank(queueValue)) {
            try {
                queueSize = Integer.parseInt(queueValue);
                logger.trace("Queue size was set to {}", queueSize);
            } catch (final NumberFormatException e) {
                logger.warn("Cannot parse {} as set by {}, using default {}", queueValue,
                        NOTIFICATION_QUEUE_SIZE_PROPERTY, queueSize);
            }
        }

        // Overriding the queue:
        // ThreadPoolExecutor would not create new threads if the queue is not full, thus adding
        // occurs in RejectedExecutionHandler.
        // This impl saturates threadpool first, then queue. When both are full caller will get blocked.
        final BlockingQueue<Runnable> delegate = new LinkedBlockingQueue<>(queueSize);
        final BlockingQueue<Runnable> queue = new ForwardingBlockingQueue<Runnable>() {
            @Override
            protected BlockingQueue<Runnable> delegate() {
                return delegate;
            }

            @Override
            public boolean offer(final Runnable r) {
                // ThreadPoolExecutor will spawn a new thread after core size is reached only
                // if the queue.offer returns false.
                return false;
            }
        };

        final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true)
                .setNameFormat("md-sal-binding-notification-%d").build();

        final ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_NOTIFICATION_THREADS,
                MAX_NOTIFICATION_THREADS, NOTIFICATION_THREAD_LIFE, TimeUnit.SECONDS, queue, factory,
                new RejectedExecutionHandler() {
                    // if the max threads are met, then it will raise a rejectedExecution. We then push to the queue.
                    @Override
                    public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
                        try {
                            executor.getQueue().put(r);
                        } catch (final InterruptedException e) {
                            throw new RejectedExecutionException("Interrupted while waiting on the queue", e);
                        }
                    }
                });

        NOTIFICATION_EXECUTOR = MoreExecutors.listeningDecorator(executor);
    }

    return NOTIFICATION_EXECUTOR;
}

From source file:com.haulmont.cuba.core.app.ClusterManager.java

@PostConstruct
protected void init() {
    int nThreads = clusterConfig.getClusterMessageSendingThreadPoolSize();
    executor = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(clusterConfig.getClusterMessageSendingQueueCapacity()),
            new ThreadFactoryBuilder().setNameFormat("ClusterManagerMessageSender-%d").build(),
            new RejectedExecutionHandler() {
                @Override//from  w  ww.j  a v a2 s .  c  o m
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    SendMessageRunnable sendMessageRunnable = (SendMessageRunnable) r;
                    log.info("Queue capacity is exceeded. Message: {}: {}",
                            sendMessageRunnable.message.getClass(), sendMessageRunnable.message);
                }
            });
}

From source file:org.polymap.core.runtime.PolymapThreadPoolExecutor.java

public PolymapThreadPoolExecutor(int minPoolSize, int maxPoolSize, int keepAliveSecs, BlockingQueue queue) {
    super(minPoolSize, maxPoolSize, keepAliveSecs, TimeUnit.SECONDS, queue);

    // thread factory
    setThreadFactory(this);

    // rejected? -> wait and try again
    setRejectedExecutionHandler(new RejectedExecutionHandler() {
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //log.warn( "Unable to queue task: " + r );
            // wait (a long time) and try again (until StackOverflow)
            synchronized (queueFull) {
                queueFull.set(true);/*  ww  w  .  j  a v a  2  s.c om*/
                try {
                    queueFull.wait(1000);
                } catch (InterruptedException e) {
                }
            }
            executor.execute(r);
        }
    });

}

From source file:org.wso2.carbon.device.mgt.input.adapter.http.HTTPEventAdapter.java

@Override
public void init(InputEventAdapterListener eventAdaptorListener) throws InputEventAdapterException {
    this.eventAdaptorListener = eventAdaptorListener;

    //ThreadPoolExecutor will be assigned  if it is null
    if (executorService == null) {
        int minThread;
        int maxThread;
        long defaultKeepAliveTime;
        int jobQueueSize;

        //If global properties are available those will be assigned else constant values will be assigned
        if (globalProperties.get(HTTPEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) {
            minThread = Integer.parseInt(
                    globalProperties.get(HTTPEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME));
        } else {//from w ww.  jav a2s  .c  om
            minThread = HTTPEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE;
        }

        if (globalProperties.get(HTTPEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) {
            maxThread = Integer.parseInt(
                    globalProperties.get(HTTPEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME));
        } else {
            maxThread = HTTPEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE;
        }

        if (globalProperties.get(HTTPEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME) != null) {
            defaultKeepAliveTime = Integer
                    .parseInt(globalProperties.get(HTTPEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME));
        } else {
            defaultKeepAliveTime = HTTPEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_IN_MILLS;
        }

        if (globalProperties.get(HTTPEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) {
            jobQueueSize = Integer.parseInt(
                    globalProperties.get(HTTPEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME));
        } else {
            jobQueueSize = HTTPEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE;
        }

        RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                try {
                    executor.getQueue().put(r);
                } catch (InterruptedException e) {
                    log.error("Exception while adding event to executor queue : " + e.getMessage(), e);
                }
            }

        };

        executorService = new ThreadPoolExecutor(minThread, maxThread, defaultKeepAliveTime,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(jobQueueSize),
                rejectedExecutionHandler);

    }
}