Example usage for java.util.concurrent ScheduledThreadPoolExecutor ScheduledThreadPoolExecutor

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

Introduction

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

Prototype

public ScheduledThreadPoolExecutor(int corePoolSize) 

Source Link

Document

Creates a new ScheduledThreadPoolExecutor with the given core pool size.

Usage

From source file:org.mule.util.store.MonitoredObjectStoreWrapper.java

@Override
public void initialise() throws InitialisationException {
    if (name == null) {
        name = UUID.getUUID();/*w  w w  .ja  v  a  2 s .c  om*/
    }

    if (expirationInterval <= 0) {
        throw new IllegalArgumentException(CoreMessages
                .propertyHasInvalidValue("expirationInterval", new Integer(expirationInterval)).toString());
    }

    if (scheduler == null) {
        this.scheduler = new ScheduledThreadPoolExecutor(1);
        scheduler.setThreadFactory(
                new DaemonThreadFactory(name + "-Monitor", context.getExecutionClassLoader()));
        scheduler.scheduleWithFixedDelay(this, 0, expirationInterval, TimeUnit.MILLISECONDS);
    }
}

From source file:org.red5.server.stream.PlaylistSubscriberStream.java

/**
 * Return the executor to use./*from  w w w.j  a  va  2s .  c o m*/
 * 
 * @return the executor
 */
public ScheduledThreadPoolExecutor getExecutor() {
    if (executor == null) {
        synchronized (this) {
            if (executor == null) {
                // Default executor
                executor = new ScheduledThreadPoolExecutor(16);
            }
        }
    }
    return executor;
}

From source file:org.rifidi.edge.sensors.sessions.AbstractIPSensorSession.java

@Override
protected void _connect() throws IOException {
    if ((getStatus() == SessionStatus.PROCESSING || getStatus() == SessionStatus.CREATED
            || getStatus() == SessionStatus.LOGGINGIN || getStatus() == SessionStatus.CLOSED)
            && connecting.compareAndSet(false, true)) {
        try {//w  w  w .  jav  a  2  s.c o m
            setStatus(SessionStatus.CONNECTING);
            //fix for abandoned sockets
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                }
            }
            socket = null;
            // if an executor exists, execute it (delete the executor :))
            if (processing.get()) {
                if (!processing.compareAndSet(true, false)) {
                    logger.warn("Killed a non active executor. That should not happen. ");
                }
                // TODO: better would be to have a method in
                // AbstractSensorSession that handles the shutdown of the
                // executor
                executor.shutdownNow();
                executor = null;
                resetCommands();
            }
            // check if somebody is currently reading
            if (readThread != null) {
                readThread.interrupt();
                try {
                    logger.debug("Killing read thread.");
                    readThread.join();
                    readThread = null;
                } catch (InterruptedException e1) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
            // check if somebody is currently writing
            if (writeThread != null) {
                writeThread.interrupt();
                try {
                    logger.debug("Killing write thread.");
                    writeThread.join();
                    writeThread = null;
                } catch (InterruptedException e1) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
            executor = new ScheduledThreadPoolExecutor(1);
            // try to open the socket
            logger.info("Attempting to connect to : " + host + ":" + port);

            // begin reconnect loop. We have an atomic boolean that should
            // be true as long as we are in the loop
            if (!reconnectLoop.compareAndSet(false, true)) {
                logger.warn("atomic boolean for recconnect " + "loop was already true.");
            }
            try {
                // reconnect loop. try to connect maxConAteempts number of
                // times, unless maxConAttempts is -1, in which case try
                // forever.
                for (int connCount = 0; connCount < maxConAttempts || maxConAttempts == -1; connCount++) {

                    try {
                        socket = new Socket(host, port);
                        if (logger.isDebugEnabled()) {
                            logger.info("Socket connection successful to " + this.host + ":" + this.port);
                        }
                        break;
                    } catch (IOException e) {
                        // do nothing
                    }

                    // print info message the first time
                    if (logger.isInfoEnabled() && connCount == 0) {
                        logger.info("Session " + this.getID() + " on " + this.getSensor().getID()
                                + " Starting reconnect attempts to " + this.host + ":" + this.port);
                    }

                    // wait for a specified number of ms or for a notify
                    // call
                    try {
                        synchronized (reconnectLoop) {
                            reconnectLoop.wait(this.reconnectionInterval);
                        }
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                    if (!reconnectLoop.get())
                        break;
                }
            } finally {
                reconnectLoop.compareAndSet(true, false);
            }

            // no socket, we are screwed
            if (socket == null) {
                // revert
                setStatus(SessionStatus.CREATED);
                connecting.compareAndSet(true, false);
                throw new IOException("Unable to reach reader.");
            }

            readThread = new Thread(new ReadThread(socket.getInputStream(), getMessageParsingStrategyFactory(),
                    getMessageProcessingStrategyFactory()));
            writeThread = new Thread(new WriteThread(socket.getOutputStream(), writeQueue));
            readThread.start();
            writeThread.start();
            setStatus(SessionStatus.LOGGINGIN);
            // do the logical connect
            try {
                if (!onConnect()) {
                    onConnectFailed();
                    return;
                }
            } catch (IOException e) {
                logger.warn("Unable to connect during login: " + e);
                connecting.compareAndSet(true, false);
                connect();
            }
            logger.info("Session " + this.getID() + " on " + this.getSensor().getID()
                    + " connected successfully to  " + this.host + ":" + this.port);

            // TODO: paramaterize the keepalive frequency
            submit(getKeepAliveCommand(), 10L, TimeUnit.SECONDS);

            // create thread that checks if the write thread dies and
            // restart it
            connectionGuardian = new ConnectionGaurdian();
            connectionGuardian.start();
            setStatus(SessionStatus.PROCESSING);
            if (!processing.compareAndSet(false, true)) {
                logger.warn("Executor was already active! ");
            }
        } finally {
            connecting.compareAndSet(true, false);
        }
    }
}

From source file:com.xconns.peerdevicenet.core.CoreAPI.java

@TargetApi(5)
@Override/*from  w  w  w  . j a v  a 2  s.c  o m*/
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    Log.d(TAG, "RouterService onCreate()");

    timer = new ScheduledThreadPoolExecutor(1);

    linkMgr = new TransportManager(this, linkHandler);
    linkMgr.onResume();

    mMyDeviceInfo = new DeviceInfo();

    //loc wifi
    myWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mywifilock");
    myWifiLock.acquire();

    // init tcp connector
    mTCPConn = new TCPConnector(this);

    // notify others router is up by send ACTION_ROUTER_UP
    // eg. start remote intent service here
    Intent startupSignal = new Intent(Router.Intent.ACTION_ROUTER_UP);
    startService(startupSignal);

    // add notification and start service at foreground
    /*Notification notification = new Notification(R.drawable.router_icon,
    getText(R.string.router_notif_ticker),
    System.currentTimeMillis());*/
    // Instantiate a Builder object.
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(getText(R.string.router_notif_title))
            .setTicker(getText(R.string.router_notif_ticker))
            .setContentText(getText(R.string.router_notif_message)).setSmallIcon(R.drawable.router_icon);
    //
    Intent notificationIntent = new Intent(Router.Intent.ACTION_CONNECTOR);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    builder.setContentIntent(pendingIntent);

    // using id of ticker text as notif id
    startForeground(R.string.router_notif_ticker, builder.build());

}

From source file:com.aol.advertising.qiao.util.cache.PersistentMap.java

public void init() throws Exception {
    this.dbConfig = database.getConfig();
    this.dbEnvironment = database.getEnvironment();
    this.databaseName = database.getDatabaseName();
    this.isTransactional = dbConfig.getTransactional();
    this.cacheMode = dbConfig.getCacheMode();

    if (highWaterMark > 0 && lowWaterMark == 0)
        this.lowWaterMark = (int) Math.round(0.9 * highWaterMark);

    this.itemCount = new AtomicInteger(super.size()); // init count

    _openSecondaryIndexes();/*w  w  w.j  a v a 2  s  .  c  o m*/

    if (timer == null)
        timer = new ScheduledThreadPoolExecutor(1);

    enableReaping(reapingInitDelaySecs, reapingIntervalSecs);

}

From source file:org.mule.util.store.MuleObjectStoreManager.java

@Override
public void initialise() throws InitialisationException {
    scheduler = new ScheduledThreadPoolExecutor(1);
    scheduler.setThreadFactory(/*from w  ww.  ja  v  a2 s . c o m*/
            new DaemonThreadFactory("ObjectStoreManager-Monitor", this.getClass().getClassLoader()));
}

From source file:org.rifidi.edge.readerplugin.llrp.LLRPReaderSession.java

/**
 * This logic executes as soon as a socket is established to initialize the
 * connection. It occurs before any commands are scheduled
 *///ww  w  .  ja  v a 2  s  . c o m
private void onConnect() {
    logger.info(">>>>>>>>>>>>>>>>>>>LLRP Session " + this.getID() + " on sensor " + this.getSensor().getID()
            + " attempting to log in to " + host + ":" + port);
    setStatus(SessionStatus.LOGGINGIN);
    executor = new ScheduledThreadPoolExecutor(1);

    try {
        SET_READER_CONFIG config = createSetReaderConfig();
        config.setMessageID(new UnsignedInteger(messageID++));

        SET_READER_CONFIG_RESPONSE config_response = (SET_READER_CONFIG_RESPONSE) connection.transact(config);

        // modified by limg00n

        //---------------
        StatusCode sc = config_response.getLLRPStatus().getStatusCode();
        if (sc.intValue() != StatusCode.M_Success) {
            if (config_response.getLLRPStatus().getStatusCode().toInteger() != 0) {
                try {
                    logger.error("Problem with SET_READER_CONFIG: \n" + config_response.toXMLString());
                } catch (InvalidLLRPMessageException e) {
                    logger.warn("Cannot print XML for " + "SET_READER_CONFIG_RESPONSE");
                }
            }
        }

        if (!processing.compareAndSet(false, true)) {
            logger.warn("Executor was already active! ");
        }
        submit(getTimeoutCommand(), 10, TimeUnit.SECONDS);
        setStatus(SessionStatus.PROCESSING);

    } catch (TimeoutException e) {
        logger.error(e.getMessage());
        disconnect();
    } catch (ClassCastException ex) {
        logger.error(ex.getMessage());
        disconnect();
    }

}

From source file:org.kei.android.phone.cellhistory.activities.CellHistoryPagerActivity.java

@Override
protected void onResume() {
    preferences = false;//ww w  .ja  v  a2s . c  o m
    app.getNfyHelper().hide();
    setTransformer();
    if (prefs.getBoolean(PreferencesUI.PREFS_KEY_KEEP_SCREEN, PreferencesUI.PREFS_DEFAULT_KEEP_SCREEN))
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    else
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);

    if (prefs.getBoolean(PreferencesGeolocation.PREFS_KEY_LOCATE,
            PreferencesGeolocation.PREFS_DEFAULT_LOCATE)) {
        startService(new Intent(this, ProviderService.class));
        if (prefs.getBoolean(PreferencesGeolocation.PREFS_KEY_GPS, PreferencesGeolocation.PREFS_DEFAULT_GPS))
            startService(new Intent(this, GpsService.class));
        else
            stopService(new Intent(this, GpsService.class));
    } else {
        stopService(new Intent(this, ProviderService.class));
        stopService(new Intent(this, GpsService.class));
    }
    execUpdateUI = new ScheduledThreadPoolExecutor(1);
    execUpdateUI.scheduleWithFixedDelay(uiTask, 0L, Integer.parseInt(
            prefs.getString(PreferencesTimers.PREFS_KEY_TIMERS_UI, PreferencesTimers.PREFS_DEFAULT_TIMERS_UI)),
            TimeUnit.MILLISECONDS);
    super.onResume();
}

From source file:org.hawkular.alerter.prometheus.PrometheusAlerter.java

private synchronized void update() {
    log.debug("Refreshing External Prometheus Triggers!");
    try {/*from w  w  w  .  j  a  va 2s  . co m*/
        if (expressionExecutor == null) {
            expressionExecutor = new ScheduledThreadPoolExecutor(
                    Integer.valueOf(defaultProperties.get(THREAD_POOL_SIZE)));
        }

        Set<ExternalCondition> activeConditions = new HashSet<>();
        log.debugf("Found [%d] active External Prometheus Triggers!", activeTriggers.size());

        // for each trigger look for Prometheus Conditions and start running them
        Collection<Condition> conditions = null;
        for (Trigger trigger : activeTriggers.values()) {
            try {
                conditions = definitions.getTriggerConditions(trigger.getTenantId(), trigger.getId(), null);
                log.debugf("Checking [%s] Conditions for external Prometheus trigger [%s]", conditions.size(),
                        trigger.getName());
            } catch (Exception e) {
                log.error("Failed to fetch Conditions when scheduling prometheus conditions for " + trigger, e);
                continue;
            }
            for (Condition condition : conditions) {
                if (condition instanceof ExternalCondition) {
                    ExternalCondition externalCondition = (ExternalCondition) condition;
                    if (ALERTER_ID.equals(externalCondition.getAlerterId())) {
                        log.debugf("Found Prometheus ExternalCondition %s", externalCondition);
                        activeConditions.add(externalCondition);
                        if (expressionFutures.containsKey(externalCondition)) {
                            log.debugf("Skipping, already evaluating %s", externalCondition);

                        } else {
                            try {
                                // start the job. TODO: Do we need a delay for any reason?
                                log.debugf("Adding runner for %s", externalCondition);

                                Map<String, String> properties = new HashMap<>(defaultProperties);
                                if (trigger.getContext().containsKey(CONTEXT_URL)) {
                                    properties.put(URL, trigger.getContext().get(CONTEXT_URL));
                                }
                                String frequency = trigger.getContext().containsKey(CONTEXT_FREQUENCY)
                                        ? trigger.getContext().get(CONTEXT_FREQUENCY)
                                        : CONTEXT_FREQUENCY_DEFAULT;

                                ExpressionRunner runner = new ExpressionRunner(alerts, properties,
                                        externalCondition);
                                expressionFutures.put(externalCondition, expressionExecutor.scheduleAtFixedRate(
                                        runner, 0L, Long.valueOf(frequency), TimeUnit.SECONDS));
                            } catch (Exception e) {
                                log.error("Failed to schedule expression for Prometheus condition "
                                        + externalCondition, e);
                            }
                        }
                    }
                }
            }
        }

        // cancel obsolete expressions
        Set<ExternalCondition> temp = new HashSet<>();
        for (Map.Entry<ExternalCondition, ScheduledFuture<?>> me : expressionFutures.entrySet()) {
            ExternalCondition ec = me.getKey();
            if (!activeConditions.contains(ec)) {
                log.debugf("Canceling evaluation of obsolete External Prometheus Condition %s", ec);

                me.getValue().cancel(true);
                temp.add(ec);
            }
        }
        expressionFutures.keySet().removeAll(temp);
        temp.clear();

    } catch (Exception e) {
        log.error("Failed to fetch Triggers for scheduling Prometheus conditions.", e);
    }
}

From source file:org.apache.falcon.service.FeedSLAMonitoringService.java

@Override
public void init() throws FalconException {
    String uri = StartupProperties.get().getProperty("feed.sla.service.store.uri");
    storePath = new Path(uri);
    filePath = new Path(storePath, "feedSLAMonitoringService");
    fileSystem = initializeFileSystem();

    String freq = StartupProperties.get().getProperty("feed.sla.serialization.frequency.millis", ONE_HOUR);
    serializationFrequencyMillis = Integer.valueOf(freq);

    freq = StartupProperties.get().getProperty("feed.sla.statusCheck.frequency.seconds", "600");
    statusCheckFrequencySeconds = Integer.valueOf(freq);

    freq = StartupProperties.get().getProperty("feed.sla.lookAheadWindow.millis", "900000");
    lookAheadWindowMillis = Integer.valueOf(freq);

    String size = StartupProperties.get().getProperty("feed.sla.queue.size", "288");
    queueSize = Integer.valueOf(size);

    try {//w  ww.j  a v a  2 s  .  c o  m
        if (fileSystem.exists(filePath)) {
            deserialize(filePath);
        } else {
            LOG.debug("No old state exists at: {}, Initializing a clean state.", filePath.toString());
            initializeService();
        }
    } catch (IOException e) {
        throw new FalconException("Couldn't check the existence of " + filePath, e);
    }
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    executor.scheduleWithFixedDelay(new Monitor(), 0, statusCheckFrequencySeconds, TimeUnit.SECONDS);
}