Example usage for java.util.concurrent Executors newSingleThreadExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadExecutor

Introduction

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

Prototype

public static ExecutorService newSingleThreadExecutor() 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue.

Usage

From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java

/**
 * The main method.//from w ww . j a  v  a  2s  . c om
 *
 * @param args
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(String[] args) throws Exception {

    HydrographMain hydrographMain = new HydrographMain();
    final Timer timer = new Timer();
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        Session session = null;
        boolean isExecutionTracking = false;
        String[] argsList = args;
        List<String> argumentList = new ArrayList<String>(Arrays.asList(args));
        final String jobId = hydrographMain.getJobId(argumentList);

        getLogLevel(argumentList).ifPresent(x -> {
            if (!x.equalsIgnoreCase(String.valueOf(logger.getLevel()))) {
                setLoglevel(x);
            } else {
                Optional.empty();
            }

        });

        logger.info("Argument List: " + argumentList.toString());

        String trackingClientSocketPort = hydrographMain.getTrackingClientSocketPort(argumentList);

        if (argumentList.contains(Constants.IS_TRACKING_ENABLE)) {
            int index = argumentList.indexOf(Constants.IS_TRACKING_ENABLE);
            isExecutionTracking = Boolean.valueOf(argsList[index + 1]);
            argumentList = removeItemFromIndex(index, argumentList);
        }

        if (argumentList.contains(Constants.TRACKING_CLIENT_SOCKET_PORT)) {
            int index = argumentList.indexOf(Constants.TRACKING_CLIENT_SOCKET_PORT);
            argumentList = removeItemFromIndex(index, argumentList);
        }

        argsList = argumentList.toArray(new String[argumentList.size()]);

        logger.debug("Execution tracking enabled - " + isExecutionTracking);
        logger.info("Tracking Client Port: " + trackingClientSocketPort);

        /**
         * Start new thread to run job
         */
        final HydrographService execution = new HydrographService();

        FutureTask task = hydrographMain.executeGraph(latch, jobId, argsList, execution, isExecutionTracking);

        hydrographMain.executorService = Executors.newSingleThreadExecutor();
        hydrographMain.executorService.submit(task);

        if (isExecutionTracking) {
            //If tracking is enabled, start to post execution tracking status.
            final HydrographEngineCommunicatorSocket socket = new HydrographEngineCommunicatorSocket(execution);
            session = hydrographMain.connectToServer(socket, jobId, trackingClientSocketPort);
            hydrographMain.sendExecutionTrackingStatus(latch, session, jobId, timer, execution, socket);
        }

        //waiting for execute graph thread 
        task.get();

    } catch (Exception exp) {
        logger.info("Getting exception from HydrographMain");
        throw new RuntimeException(exp);
    } finally {
        //cleanup threads --> executor thread and timer thread 
        logger.info("HydrographMain releasing resources");
        if (!hydrographMain.executorService.isShutdown() && !hydrographMain.executorService.isTerminated()) {
            hydrographMain.executorService.shutdown();
        }
        timer.cancel();

    }
}

From source file:net.sf.mpaxs.test.ImpaxsExecution.java

/**
 *
 * @param args//  w w  w  .  j  a v  a  2  s.  c  om
 */
public static void main(String[] args) {
    Options options = new Options();
    Option[] optionArray = new Option[] {
            OptionBuilder.withArgName("nhosts").hasArg()
                    .withDescription("Number of hosts for parallel processing").create("n"),
            OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel")
                    .create("m"),
            OptionBuilder.withArgName("runmode").hasArg()
                    .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>")
                    .create("r"), //            OptionBuilder.withArgName("gui").
            //            withDescription("Create gui for distributed execution").create("g")
    };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    int nhosts = 1;
    int mjobs = 10;
    boolean gui = false;
    Mode mode = Mode.ALL;
    try {
        CommandLine cl = gp.parse(options, args);
        if (cl.hasOption("n")) {
            nhosts = Integer.parseInt(cl.getOptionValue("n"));
        }
        if (cl.hasOption("m")) {
            mjobs = Integer.parseInt(cl.getOptionValue("m"));
        }
        if (cl.hasOption("r")) {
            mode = Mode.valueOf(cl.getOptionValue("r"));
        }
        //            if (cl.hasOption("g")) {
        //                gui = true;
        //            }
    } catch (Exception ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }

    String version;
    try {
        version = net.sf.mpaxs.api.Version.getVersion();
        System.out.println("Running mpaxs " + version);
        File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar");
        if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) {
            throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir"));
        }
        final PropertiesConfiguration cfg = new PropertiesConfiguration();
        //set default execution type
        cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA);
        //set location of compute host jar
        cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation);
        //do not exit to console when master server shuts down
        cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false);
        //limit the number of used compute hosts
        cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts);
        cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, "");
        cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui);
        cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true);
        cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500");
        final int maxJobs = mjobs;
        final int maxThreads = nhosts;
        final Mode runMode = mode;
        printMessage("Run mode: " + runMode);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                if (runMode == Mode.ALL || runMode == Mode.LOCAL) {
                    printMessage("Running Within VM Execution");
                    /*
                     * LOCAL within VM execution
                     */
                    WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + lhe.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) {
                    printMessage("Running Distributed Host RMI Execution");
                    /*
                     * Grid Engine (DRMAA API) or local host distributed RMI execution
                     */
                    DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + de.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.exit(0);
            }
        });
    } catch (IOException ex) {
        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Main.java

public static ExecutorService newSingleExecutor() {
    return Executors.newSingleThreadExecutor();
}

From source file:Main.java

public static ExecutorService getSingleThreadExecutor() {
    return Executors.newSingleThreadExecutor();
}

From source file:Main.java

/**
 *   Gets the primary executor for a given object key
 *   Creates a new exector if didn't exist before
 *   Currently returns  an Executor that uses a single worker thread operating off an unbounded queue
 *      therefore tasks (Runnables added via exec.execute()) on the Executor are guaranteed to 
 *      execute sequentially in order, and no more than one task will be active at any given time
 */// w ww  . java 2 s  . c om
public synchronized static Executor getPrimaryExecutor(Object key) {
    Executor exec = obj2exec.get(key);
    if (exec == null) {
        exec = Executors.newSingleThreadExecutor();
        obj2exec.put(key, exec);
    }
    return exec;
}

From source file:Main.java

/**
 * Run the given runnable in a new thread.
 *
 * @param runnable The runnable to run in a new thread.
 *//*from www  .j a  v  a  2  s  .  co  m*/
public static void inNewThread(Runnable runnable) {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.submit(runnable);

    executor.shutdown();
}

From source file:edu.wustl.mir.erl.ihe.xdsi.util.StoreSCU.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    long t1, t2;//w  ww  .  ja  v a  2  s  .  c  o  m
    try {
        CommandLine cl = parseComandLine(args);
        Device device = new Device("storescu");
        Connection conn = new Connection();
        device.addConnection(conn);
        ApplicationEntity ae = new ApplicationEntity("STORESCU");
        device.addApplicationEntity(ae);
        ae.addConnection(conn);
        StoreSCU main = new StoreSCU(ae);
        configureTmpFile(main, cl);
        CLIUtils.configureConnect(main.remote, main.rq, cl);
        CLIUtils.configureBind(conn, ae, cl);
        CLIUtils.configure(conn, cl);
        main.remote.setTlsProtocols(conn.getTlsProtocols());
        main.remote.setTlsCipherSuites(conn.getTlsCipherSuites());
        configureRelatedSOPClass(main, cl);
        main.setAttributes(new Attributes());
        CLIUtils.addAttributes(main.attrs, cl.getOptionValues("s"));
        main.setUIDSuffix(cl.getOptionValue("uid-suffix"));
        main.setPriority(CLIUtils.priorityOf(cl));
        List<String> argList = cl.getArgList();
        boolean echo = argList.isEmpty();
        if (!echo) {
            System.out.println(rb.getString("scanning"));
            t1 = System.currentTimeMillis();
            main.scanFiles(argList);
            t2 = System.currentTimeMillis();
            int n = main.filesScanned;
            System.out.println();
            if (n == 0)
                return;
            System.out.println(
                    MessageFormat.format(rb.getString("scanned"), n, (t2 - t1) / 1000F, (t2 - t1) / n));
        }
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        device.setExecutor(executorService);
        device.setScheduledExecutor(scheduledExecutorService);
        try {
            t1 = System.currentTimeMillis();
            main.open();
            t2 = System.currentTimeMillis();
            System.out
                    .println(MessageFormat.format(rb.getString("connected"), main.as.getRemoteAET(), t2 - t1));
            if (echo)
                main.echo();
            else {
                t1 = System.currentTimeMillis();
                main.sendFiles();
                t2 = System.currentTimeMillis();
            }
        } finally {
            main.close();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
        }
        if (main.filesScanned > 0) {
            float s = (t2 - t1) / 1000F;
            float mb = main.totalSize / 1048576F;
            System.out.println(MessageFormat.format(rb.getString("sent"), main.filesSent, mb, s, mb / s));
        }
    } catch (ParseException e) {
        System.err.println("storescu: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("storescu: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:gov.nih.nci.integration.caaers.invoker.CaAERSServiceInvocationStrategyFactory.java

private static synchronized void init(final String[] caaersLibLocation, final String... caaersConfig) {
    final ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(
            Executors.newSingleThreadExecutor());

    ecs.submit(new Callable<Boolean>() {

        @Override//from  ww w.ja  va  2  s . c  o  m
        public Boolean call() throws MalformedURLException, BeansException {
            final CustomClasspathXmlApplicationContext ctx = new CustomClasspathXmlApplicationContext(
                    caaersLibLocation, caaersConfig);
            caaersRegistrationServiceInvocationStrategy = (ServiceInvocationStrategy) ctx
                    .getBean("caAersRegistrationServiceInvocationStrategy");
            caaersUpdateRegistrationServiceInvocationStrategy = (ServiceInvocationStrategy) ctx
                    .getBean("caAersUpdateRegistrationServiceInvocationStrategy");
            caaersAdverseEventServiceInvocationStrategy = (ServiceInvocationStrategy) ctx
                    .getBean("caAersAdverseEventServiceInvocationStrategy");
            return Boolean.TRUE;
        }
    });

    try {
        initStatus = ecs.take().get();
        // CHECKSTYLE:OFF
    } catch (Exception e) { // NOPMD
        LOG.error("CaAERSServiceInvocationStrategyFactory.Exception inside init(). ", e);
        initStatus = Boolean.FALSE;
    }
}

From source file:org.springside.samples.quickservice.functional.TaskRestServiceTest.java

@BeforeClass
public static void start() throws Exception {
    Future<ConfigurableApplicationContext> future = Executors.newSingleThreadExecutor()
            .submit(new Callable<ConfigurableApplicationContext>() {
                @Override//  www.ja  va  2  s .c  o m
                public ConfigurableApplicationContext call() throws Exception {
                    return SpringApplication.run(QuickServiceApplication.class);
                }
            });
    context = future.get(60, TimeUnit.SECONDS);
}

From source file:Main.java

/**
 * <p>inokeInOtherThread</p>
 *
 * @param callable a Callable object.//  ww w.j  av a  2 s .  co m
 * @return a T object.
 *
 * @throws ExecutionException   if any.
 * @throws InterruptedException if any.
 */
@Nullable
public static <T> T inokeInOtherThread(@Nonnull Callable<T> callable)
        throws ExecutionException, InterruptedException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        Future<T> future = executor.submit(callable);
        return future.get();
    } finally {
        executor.shutdown();
    }
}