Example usage for org.springframework.core.task TaskExecutor execute

List of usage examples for org.springframework.core.task TaskExecutor execute

Introduction

In this page you can find the example usage for org.springframework.core.task TaskExecutor execute.

Prototype

@Override
void execute(Runnable task);

Source Link

Document

Execute the given task .

Usage

From source file:io.dyn.core.Tasks.java

public static void execute(Runnable r, TaskExecutor te) {
    if (null != te && te != CURRENT_EXECUTOR.get()) {
        te.execute(r);
    } else {// ww  w.  j a v a2s. c  om
        r.run();
    }
}

From source file:org.eclipse.gemini.blueprint.extender.internal.activator.LifecycleManager.java

/**
 * Context creation is a potentially long-running activity (certainly more than we want to do on the synchronous
 * event callback).//  ww  w  .j  av  a 2s.c o  m
 * 
 * <p/> Based on our configuration, the context can be started on the same thread or on a different one.
 * 
 * <p/> Kick off a background activity to create an application context for the given bundle if needed.
 * 
 * <b>Note:</b> Make sure to do the fastest filtering first to avoid slow-downs on platforms with a big number of
 * plugins and wiring (i.e. Eclipse platform).
 * 
 * @param bundle
 */
protected void maybeCreateApplicationContextFor(Bundle bundle) {

    boolean debug = log.isDebugEnabled();
    String bundleString = "[" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]";

    final Long bundleId = new Long(bundle.getBundleId());

    if (managedContexts.containsKey(bundleId)) {
        if (debug) {
            log.debug("Bundle " + bundleString + " is already managed; ignoring...");
        }
        return;
    }

    if (!versionMatcher.matchVersion(bundle)) {
        return;
    }

    BundleContext localBundleContext = OsgiBundleUtils.getBundleContext(bundle);

    // initialize context
    final DelegatedExecutionOsgiBundleApplicationContext localApplicationContext;

    if (debug)
        log.debug("Inspecting bundle " + bundleString);

    try {
        localApplicationContext = contextCreator.createApplicationContext(localBundleContext);
    } catch (Exception ex) {
        log.error("Cannot create application context for bundle " + bundleString, ex);
        return;
    }

    if (localApplicationContext == null) {
        log.debug("No application context created for bundle " + bundleString);
        return;
    }

    if (typeChecker != null) {
        if (!typeChecker.isTypeCompatible(localBundleContext)) {
            log.info("Bundle " + OsgiStringUtils.nullSafeName(bundle) + " is not type compatible with extender "
                    + OsgiStringUtils.nullSafeName(bundleContext.getBundle()) + "; ignoring bundle...");
            return;
        }
    }

    log.debug("Bundle " + OsgiStringUtils.nullSafeName(bundle) + " is type compatible with extender "
            + OsgiStringUtils.nullSafeName(bundleContext.getBundle()) + "; processing bundle...");

    // create a dedicated hook for this application context
    BeanFactoryPostProcessor processingHook = new OsgiBeanFactoryPostProcessorAdapter(localBundleContext,
            postProcessors);

    // add in the post processors
    localApplicationContext.addBeanFactoryPostProcessor(processingHook);

    // add the context to the tracker
    managedContexts.put(bundleId, localApplicationContext);

    localApplicationContext.setDelegatedEventMulticaster(multicaster);

    ApplicationContextConfiguration config = contextConfigurationFactory.createConfiguration(bundle);

    final boolean asynch = config.isCreateAsynchronously();

    // create refresh runnable
    Runnable contextRefresh = new Runnable() {

        public void run() {
            // post refresh events are caught through events
            if (log.isTraceEnabled()) {
                log.trace("Calling pre-refresh on processor " + processor);
            }
            processor.preProcessRefresh(localApplicationContext);
            localApplicationContext.refresh();
        }
    };

    // executor used for creating the appCtx
    // chosen based on the sync/async configuration
    TaskExecutor executor = null;

    String creationType;

    // synch/asynch context creation
    if (asynch) {
        // for the async stuff use the executor
        executor = taskExecutor;
        creationType = "Asynchronous";
    } else {
        // for the sync stuff, use this thread
        executor = sameThreadTaskExecutor;
        creationType = "Synchronous";
    }

    if (debug) {
        log.debug(creationType + " context creation for bundle " + bundleString);
    }

    // wait/no wait for dependencies behaviour
    if (config.isWaitForDependencies()) {
        DependencyWaiterApplicationContextExecutor appCtxExecutor = new DependencyWaiterApplicationContextExecutor(
                localApplicationContext, !asynch, extenderConfiguration.getDependencyFactories());

        long timeout;
        // check whether a timeout has been defined

        if (config.isTimeoutDeclared()) {
            timeout = config.getTimeout();
            if (debug)
                log.debug("Setting bundle-defined, wait-for-dependencies/graceperiod timeout value=" + timeout
                        + " ms, for bundle " + bundleString);

        } else {
            timeout = extenderConfiguration.getDependencyWaitTime();
            if (debug)
                log.debug("Setting globally defined wait-for-dependencies/graceperiod timeout value=" + timeout
                        + " ms, for bundle " + bundleString);
        }

        appCtxExecutor.setTimeout(timeout);
        appCtxExecutor.setWatchdog(timer);
        appCtxExecutor.setTaskExecutor(executor);
        appCtxExecutor.setMonitoringCounter(contextsStarted);
        // set events publisher
        appCtxExecutor.setDelegatedMulticaster(this.multicaster);

        contextsStarted.increment();
    } else {
        // do nothing; by default contexts do not wait for services.
    }

    executor.execute(contextRefresh);
}

From source file:org.eclipse.gemini.blueprint.extender.internal.util.concurrent.RunnableTimedExecution.java

public static boolean execute(Runnable task, long waitTime, TaskExecutor taskExecutor) {
    Assert.notNull(task);//from   w w  w. j a  va 2s  .  c o m

    Counter counter = new Counter("counter for task: " + task);
    Runnable wrapper = new MonitoredRunnable(task, counter);

    boolean internallyManaged = false;

    if (taskExecutor == null) {
        taskExecutor = new SimpleTaskExecutor();
        internallyManaged = true;
    }

    counter.increment();

    taskExecutor.execute(wrapper);

    if (counter.waitForZero(waitTime)) {
        log.error(task + " did not finish in " + waitTime
                + "ms; consider taking a snapshot and then shutdown the VM in case the thread still hangs");

        //log.error("Current Thread dump***\n" + ThreadDump.dumpThreads());

        if (internallyManaged) {
            try {
                ((DisposableBean) taskExecutor).destroy();
            } catch (Exception e) {
                log.error("Exception thrown while destroying internally managed thread executor", e);
            }
        }
        return true;
    }

    return false;
}

From source file:org.springframework.osgi.extender.internal.activator.ContextLoaderListener.java

/**
 * Context creation is a potentially long-running activity (certainly more
 * than we want to do on the synchronous event callback).
 * /*from ww w .jav  a 2  s . c o m*/
 * <p/>Based on our configuration, the context can be started on the same
 * thread or on a different one.
 * 
 * <p/> Kick off a background activity to create an application context for
 * the given bundle if needed.
 * 
 * <b>Note:</b> Make sure to do the fastest filtering first to avoid
 * slowdowns on platforms with a big number of plugins and wiring (i.e.
 * Eclipse platform).
 * 
 * @param bundle
 */
protected void maybeCreateApplicationContextFor(Bundle bundle) {

    boolean debug = log.isDebugEnabled();
    String bundleString = "[" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]";

    final Long bundleId = new Long(bundle.getBundleId());

    if (managedContexts.containsKey(bundleId)) {
        if (debug) {
            log.debug("Bundle " + bundleString + " is already managed; ignoring...");
        }
        return;
    }

    if (!ConfigUtils.matchExtenderVersionRange(bundle, extenderVersion)) {
        if (debug)
            log.debug("Bundle " + bundleString + " expects an extender w/ version["
                    + OsgiBundleUtils.getHeaderAsVersion(bundle, ConfigUtils.EXTENDER_VERSION)
                    + "] which does not match current extender w/ version[" + extenderVersion
                    + "]; skipping bundle from context creation");
        return;
    }

    BundleContext localBundleContext = OsgiBundleUtils.getBundleContext(bundle);

    if (debug)
        log.debug("Scanning bundle " + bundleString + " for configurations...");

    // initialize context
    final DelegatedExecutionOsgiBundleApplicationContext localApplicationContext;

    if (debug)
        log.debug("Creating an application context for bundle " + bundleString);

    try {
        localApplicationContext = contextCreator.createApplicationContext(localBundleContext);
    } catch (Exception ex) {
        log.error("Cannot create application context for bundle " + bundleString, ex);
        return;
    }

    if (localApplicationContext == null) {
        log.debug("No application context created for bundle " + bundleString);
        if (multicaster != null) {
            multicaster.multicastEvent(
                    new OsgiBundleContextRefreshedEvent(new OsgiBundleXmlWebApplicationContext(), bundle));
        }
        return;
    }

    // create a dedicated hook for this application context
    BeanFactoryPostProcessor processingHook = new OsgiBeanFactoryPostProcessorAdapter(localBundleContext,
            postProcessors);

    // add in the post processors
    localApplicationContext.addBeanFactoryPostProcessor(processingHook);

    // add the context to the tracker
    managedContexts.put(bundleId, localApplicationContext);

    localApplicationContext.setDelegatedEventMulticaster(multicaster);

    // create refresh runnable
    Runnable contextRefresh = new Runnable() {

        public void run() {
            localApplicationContext.refresh();
        }
    };

    // executor used for creating the appCtx
    // chosen based on the sync/async configuration
    TaskExecutor executor = null;

    ApplicationContextConfiguration config = new ApplicationContextConfiguration(bundle);

    String creationType;

    // synch/asynch context creation
    if (config.isCreateAsynchronously()) {
        // for the async stuff use the executor
        executor = taskExecutor;
        creationType = "Asynchronous";
    } else {
        // for the sync stuff, use this thread
        executor = sameThreadTaskExecutor;
        creationType = "Synchronous";
    }

    if (debug) {
        log.debug(creationType + " context creation for bundle " + bundleString);
    }

    // wait/no wait for dependencies behaviour
    if (config.isWaitForDependencies()) {
        DependencyWaiterApplicationContextExecutor appCtxExecutor = new DependencyWaiterApplicationContextExecutor(
                localApplicationContext, !config.isCreateAsynchronously(),
                extenderConfiguration.getDependencyFactories());

        long timeout;
        // check whether a timeout has been defined

        if (ConfigUtils.isDirectiveDefined(bundle.getHeaders(), ConfigUtils.DIRECTIVE_TIMEOUT)) {
            timeout = config.getTimeout();
            if (debug)
                log.debug("Setting bundle-defined, wait-for-dependencies timeout value=" + timeout
                        + " ms, for bundle " + bundleString);

        } else {
            timeout = extenderConfiguration.getDependencyWaitTime();
            if (debug)
                log.debug("Setting globally defined wait-for-dependencies timeout value=" + timeout
                        + " ms, for bundle " + bundleString);
        }

        appCtxExecutor.setTimeout(config.getTimeout());

        appCtxExecutor.setWatchdog(timer);
        appCtxExecutor.setTaskExecutor(executor);
        appCtxExecutor.setMonitoringCounter(contextsStarted);
        // set events publisher
        appCtxExecutor.setDelegatedMulticaster(this.multicaster);

        contextsStarted.increment();
    } else {
        // do nothing; by default contexts do not wait for services.
    }

    executor.execute(contextRefresh);
}

From source file:org.springframework.osgi.extender.internal.activator.LifecycleManager.java

/**
 * Context creation is a potentially long-running activity (certainly more than we want to do on the synchronous
 * event callback).//from w w  w .  j a va 2  s  . c o  m
 * 
 * <p/> Based on our configuration, the context can be started on the same thread or on a different one.
 * 
 * <p/> Kick off a background activity to create an application context for the given bundle if needed.
 * 
 * <b>Note:</b> Make sure to do the fastest filtering first to avoid slow-downs on platforms with a big number of
 * plugins and wiring (i.e. Eclipse platform).
 * 
 * @param bundle
 */
protected void maybeCreateApplicationContextFor(Bundle bundle) {

    boolean debug = log.isDebugEnabled();
    String bundleString = "[" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]";

    final Long bundleId = new Long(bundle.getBundleId());

    if (managedContexts.containsKey(bundleId)) {
        if (debug) {
            log.debug("Bundle " + bundleString + " is already managed; ignoring...");
        }
        return;
    }

    if (!versionMatcher.matchVersion(bundle)) {
        return;
    }

    BundleContext localBundleContext = OsgiBundleUtils.getBundleContext(bundle);

    // initialize context
    final DelegatedExecutionOsgiBundleApplicationContext localApplicationContext;

    if (debug)
        log.debug("Inspecting bundle " + bundleString);

    try {
        localApplicationContext = contextCreator.createApplicationContext(localBundleContext);
    } catch (Exception ex) {
        log.error("Cannot create application context for bundle " + bundleString, ex);
        return;
    }

    if (localApplicationContext == null) {
        log.debug("No application context created for bundle " + bundleString);
        return;
    }

    if (typeChecker != null) {
        if (!typeChecker.isTypeCompatible(localBundleContext)) {
            log.info("Bundle " + OsgiStringUtils.nullSafeName(bundle) + " is not type compatible with extender "
                    + OsgiStringUtils.nullSafeName(bundleContext.getBundle()) + "; ignoring bundle...");
            return;
        }
    }

    log.debug("Bundle " + OsgiStringUtils.nullSafeName(bundle) + " is type compatible with extender "
            + OsgiStringUtils.nullSafeName(bundleContext.getBundle()) + "; processing bundle...");

    // create a dedicated hook for this application context
    BeanFactoryPostProcessor processingHook = new OsgiBeanFactoryPostProcessorAdapter(localBundleContext,
            postProcessors);

    // add in the post processors
    localApplicationContext.addBeanFactoryPostProcessor(processingHook);

    // add the context to the tracker
    managedContexts.put(bundleId, localApplicationContext);

    localApplicationContext.setDelegatedEventMulticaster(multicaster);

    ApplicationContextConfiguration config = contextConfigurationFactory.createConfiguration(bundle);

    final boolean asynch = config.isCreateAsynchronously();

    // create refresh runnable
    Runnable contextRefresh = new Runnable() {

        public void run() {
            // post refresh events are caught through events
            if (log.isTraceEnabled()) {
                log.trace("Calling pre-refresh on processor " + processor);
            }
            processor.preProcessRefresh(localApplicationContext);
            localApplicationContext.refresh();
        }
    };

    // executor used for creating the appCtx
    // chosen based on the sync/async configuration
    TaskExecutor executor = null;

    String creationType;

    // synch/asynch context creation
    if (asynch) {
        // for the async stuff use the executor
        executor = taskExecutor;
        creationType = "Asynchronous";
    } else {
        // for the sync stuff, use this thread
        executor = sameThreadTaskExecutor;
        creationType = "Synchronous";
    }

    if (debug) {
        log.debug(creationType + " context creation for bundle " + bundleString);
    }

    // wait/no wait for dependencies behaviour
    if (config.isWaitForDependencies()) {
        DependencyWaiterApplicationContextExecutor appCtxExecutor = new DependencyWaiterApplicationContextExecutor(
                localApplicationContext, !asynch, extenderConfiguration.getDependencyFactories());

        long timeout;
        // check whether a timeout has been defined

        if (config.isTimeoutDeclared()) {
            timeout = config.getTimeout();
            if (debug)
                log.debug("Setting bundle-defined, wait-for-dependencies/graceperiod timeout value=" + timeout
                        + " ms, for bundle " + bundleString);

        } else {
            timeout = extenderConfiguration.getDependencyWaitTime();
            if (debug)
                log.debug("Setting globally defined wait-for-dependencies/graceperiod timeout value=" + timeout
                        + " ms, for bundle " + bundleString);
        }

        appCtxExecutor.setTimeout(config.getTimeout());
        appCtxExecutor.setWatchdog(timer);
        appCtxExecutor.setTaskExecutor(executor);
        appCtxExecutor.setMonitoringCounter(contextsStarted);
        // set events publisher
        appCtxExecutor.setDelegatedMulticaster(this.multicaster);

        contextsStarted.increment();
    } else {
        // do nothing; by default contexts do not wait for services.
    }

    executor.execute(contextRefresh);
}

From source file:org.springframework.statemachine.support.DefaultStateMachineExecutor.java

private synchronized void scheduleEventQueueProcessing() {
    TaskExecutor executor = getTaskExecutor();
    if (executor == null) {
        return;// w  w  w.ja v a  2s  .  c  o  m
    }

    // TODO: it'd be nice not to create runnable if
    //       current ref is null, we use atomic reference
    //       to play safe with concurrency
    Runnable task = new Runnable() {
        @Override
        public void run() {
            boolean eventProcessed = false;
            while (processEventQueue()) {
                eventProcessed = true;
                processTriggerQueue();
                while (processDeferList()) {
                    processTriggerQueue();
                }
            }
            if (!eventProcessed) {
                processTriggerQueue();
                while (processDeferList()) {
                    processTriggerQueue();
                }
            }
            taskRef.set(null);
            if (requestTask.getAndSet(false)) {
                scheduleEventQueueProcessing();
            }
        }
    };

    if (taskRef.compareAndSet(null, task)) {
        executor.execute(task);
    } else {
        requestTask.set(true);
    }
}