Example usage for java.util.concurrent ThreadPoolExecutor getQueue

List of usage examples for java.util.concurrent ThreadPoolExecutor getQueue

Introduction

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

Prototype

public BlockingQueue<Runnable> getQueue() 

Source Link

Document

Returns the task queue used by this executor.

Usage

From source file:org.springframework.integration.util.CallerBlocksPolicy.java

@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    if (!executor.isShutdown()) {
        try {/*  ww  w.j  a v  a  2s .c  o m*/
            BlockingQueue<Runnable> queue = executor.getQueue();
            if (logger.isDebugEnabled()) {
                logger.debug("Attempting to queue task execution for " + this.maxWait + " milliseconds");
            }
            if (!queue.offer(r, this.maxWait, TimeUnit.MILLISECONDS)) {
                throw new RejectedExecutionException("Max wait time expired to queue task");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Task execution queued");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RejectedExecutionException("Interrupted", e);
        }
    } else {
        throw new RejectedExecutionException("Executor has been shut down");
    }
}

From source file:com.stgmastek.birt.report.ReportService.java

public int getCurrentPendingQueueSize() {
    if (!isDestroyed()) {
        if (service instanceof ThreadPoolExecutor) {
            ThreadPoolExecutor executor = (ThreadPoolExecutor) service;
            return executor.getQueue().size();
        }// www.ja v  a 2  s.com
    }
    return -1;
}

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;/* w w  w.  j  a  v  a 2 s  . c  om*/
    }

    //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:io.kahu.hawaii.util.call.dispatch.HawaiiRejectedExecutionHandler.java

@Override
public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
    /*/*from ww w. j a v a  2  s. com*/
     * This does the actual put into the queue. Once the max threads have
     * been reached, the tasks will then queue up.
     */
    try {
        executor.getQueue().add(task);
    } catch (IllegalStateException e) {
        try {
            ((HawaiiExecutorImpl) executor).rejectTask();
            if (delegate != null) {
                delegate.rejectedExecution(task, executor);
            }
        } finally {
            logManager.info(CoreLoggers.SERVER,
                    "Rejected '" + task + "' since the pool and queue size has been exceeded.");
            throw new RejectedExecutionException();
        }

    }
}

From source file:com.l2jfree.gameserver.ThreadPoolManager.java

private int getTaskCount(ThreadPoolExecutor tp) {
    return tp.getQueue().size() + tp.getActiveCount();
}

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 {/* ww w.j ava2  s.  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);

    }
}

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

@Override
public void runDraw(final GISDisplay display) throws NullPointerException {
    final double zoom = display.getZoomLevel();

    GeoEnvelope env = display.getBounds();
    //get tiled for zoom and bounds
    final TMSLayer tmsLayer = (TMSLayer) mLayer;
    final List<TileItem> tiles = tmsLayer.getTielsForBounds(display, env, zoom);

    int threadCount = tmsLayer.getMaxThreadCount();
    if (threadCount > 0)
        mDrawThreadPool = new ThreadPoolExecutor(threadCount, threadCount, KEEP_ALIVE_TIME,
                KEEP_ALIVE_TIME_UNIT, new LinkedBlockingQueue<Runnable>(), new RejectedExecutionHandler() {
                    @Override/*from w w  w.j a va 2 s.  c  om*/
                    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 (null == mDrawThreadPool) {
        tmsLayer.onDrawFinished(tmsLayer.getId(), 1);
        return;
    }

    if (tiles.size() == 0) {
        tmsLayer.onDrawFinished(tmsLayer.getId(), 1);
        return;
    }

    for (int i = 0; i < tiles.size(); ++i) {
        final TileItem tile = tiles.get(i);
        mDrawThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

                final Bitmap bmp = tmsLayer.getBitmap(tile);
                if (bmp != null) {
                    display.drawTile(bmp, tile.getPoint(), mRasterPaint);
                }

                float percent = 1;
                synchronized (mLayer) {
                    if (mDrawThreadPool.getTaskCount() > 1)
                        percent = (float) (mDrawThreadPool.getCompletedTaskCount() + 1)
                                / mDrawThreadPool.getTaskCount();
                    tmsLayer.onDrawFinished(tmsLayer.getId(), percent);
                }
                //Log.d(TAG, "percent: " + percent + " complete: " + mDrawThreadPool.getCompletedTaskCount() + " task count: " + mDrawThreadPool.getTaskCount());
            }
        });
    }
}

From source file:net.darkmist.clf.Main.java

private void handleFiles(String fileNames[], int off, int len) {
    DirTraverser traverser;// w  ww . j ava  2  s  .  co m
    Queue<File> files;
    ExecutorService executor;

    // convert fileNames to Files and put them in a Queue
    files = Util.newQueue(Util.getStringToFileConverter(), fileNames, off, len);
    //executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    executor = MoreExecutors.newCurrentThreadPool();

    traverser = new DirTraverser(files, new ExecutorFileHandler(executor, this));

    // let her rip
    traverser.run();

    // all done traversing... shutdown the executor
    executor.shutdown();
    // and wait for it
    while (!executor.isTerminated()) {
        try {
            executor.awaitTermination(STATUS_TIME, STATUS_UNIT);
        } catch (InterruptedException e) {
            logger.warn("Ignoring InterruptedException until thread pool executor stops", e);
        }
        if (logger.isDebugEnabled() && executor instanceof ThreadPoolExecutor) {
            ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
            logger.debug("ThreadPool size=" + pool.getPoolSize() + " active=" + pool.getActiveCount()
                    + " queue=" + pool.getQueue().size());
        }
    }
    executor = null;
    logger.debug("handleFiles done...");
}

From source file:com.dianping.dpsf.jmx.DpsfResponsorMonitor.java

@MBeanMeta(ignore = true)
public int getWaitTaskInQueue(int port) {
    ThreadPoolExecutor threadPool = getThreadPool(port);
    return threadPool != null ? threadPool.getQueue().size() : -1;
}

From source file:com.nextgis.maplibui.service.TileDownloadService.java

private void download(DownloadTask task) {
    MapBase map = MapBase.getInstance();
    if (null == map)
        return;/*from  ww  w . j  ava2 s . c  om*/

    ILayer layer = map.getLayerByPathName(task.getLayerPathName());
    if (null != layer && layer instanceof RemoteTMSLayer) { // process only tms layers
        final RemoteTMSLayer tmsLayer = (RemoteTMSLayer) layer;
        String notifyTitle = getString(R.string.download_tiles);

        mBuilder.setWhen(System.currentTimeMillis()).setContentTitle(notifyTitle);
        mNotifyManager.notify(TILE_DOWNLOAD_NOTIFICATION_ID, mBuilder.build());

        final List<TileItem> tiles = new LinkedList<>();
        int zoomCount = task.getZoomTo() + 1 - task.getZoomFrom();
        for (int zoom = task.getZoomFrom(); zoom < task.getZoomTo() + 1; zoom++) {
            tiles.addAll(MapUtil.getTileItems(task.getEnvelope(), zoom, tmsLayer.getTMSType()));

            if (mCanceled)
                break;

            mBuilder.setProgress(zoomCount, zoom, false).setContentText(getString(R.string.form_tiles_list));
            mNotifyManager.notify(TILE_DOWNLOAD_NOTIFICATION_ID, mBuilder.build());

            if (tiles.size() > Constants.MAX_TILES_COUNT)
                break;
        }

        int threadCount = DRAWING_SEPARATE_THREADS;
        int coreCount = Runtime.getRuntime().availableProcessors();

        // FIXME more than 1 pool size causing strange behaviour on 6.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            coreCount = 1;

        mThreadPool = new ThreadPoolExecutor(coreCount, threadCount, 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);
                        }
                    }
                });

        int tilesSize = tiles.size();
        List<Future> futures = new ArrayList<>(tilesSize);

        for (int i = 0; i < tilesSize; ++i) {
            if (mCanceled)
                break;

            final TileItem tile = tiles.get(i);
            futures.add(mThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    android.os.Process.setThreadPriority(Constants.DEFAULT_DRAW_THREAD_PRIORITY);
                    tmsLayer.downloadTile(tile);
                }
            }));
        }

        //in separate thread

        // wait for download ending
        int nStep = futures.size() / Constants.DRAW_NOTIFY_STEP_PERCENT;
        if (nStep == 0)
            nStep = 1;

        for (int i = 0, futuresSize = futures.size(); i < futuresSize; i++) {
            if (mCanceled)
                break;

            try {
                Future future = futures.get(i);
                future.get(); // wait for task ending

                if (i % nStep == 0) {
                    mBuilder.setProgress(futuresSize, i, false)
                            .setContentText(getString(R.string.processing) + " " + tmsLayer.getName());
                    // Displays the progress bar for the first time.
                    mNotifyManager.notify(TILE_DOWNLOAD_NOTIFICATION_ID, mBuilder.build());
                }

            } catch (CancellationException | InterruptedException e) {
                //e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}