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(ThreadFactory threadFactory) 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the provided ThreadFactory to create a new thread when needed.

Usage

From source file:kymr.github.io.training.scheduler.SchedulerEx1.java

public static void main(String[] args) {
    Publisher<Integer> pub = sub -> {
        sub.onSubscribe(new Subscription() {
            @Override/*w  w w.  j  a va 2  s  .  c  om*/
            public void request(long n) {
                log.debug("request()");
                sub.onNext(1);
                sub.onNext(2);
                sub.onNext(3);
                sub.onNext(4);
                sub.onNext(5);
                sub.onComplete();
            }

            @Override
            public void cancel() {

            }
        });
    };

    Publisher<Integer> subOnPub = sub -> {
        ExecutorService es = Executors.newSingleThreadExecutor(new CustomizableThreadFactory() {
            @Override
            public String getThreadNamePrefix() {
                return "subOn-";
            }
        });

        pub.subscribe(new Subscriber<Integer>() {
            @Override
            public void onSubscribe(Subscription s) {
                es.execute(() -> sub.onSubscribe(s));
            }

            @Override
            public void onNext(Integer integer) {
                sub.onNext(integer);
            }

            @Override
            public void onError(Throwable t) {
                sub.onError(t);
                es.shutdown();
            }

            @Override
            public void onComplete() {
                sub.onComplete();
                es.shutdown();
            }
        });
    };

    /*Publisher<Integer> subOnPub = sub -> {
       ExecutorService es = Executors.newSingleThreadExecutor(new CustomizableThreadFactory() {
    @Override
    public String getThreadNamePrefix() {
       return "subOn-";
    }
       });
            
       es.execute(() -> pub.subscribe(sub));
    };
    */
    Publisher<Integer> pubOnPub = sub -> {
        subOnPub.subscribe(new Subscriber<Integer>() {
            ExecutorService es = Executors.newSingleThreadExecutor(new CustomizableThreadFactory() {
                @Override
                public String getThreadNamePrefix() {
                    return "pubOn-";
                }
            });

            @Override
            public void onSubscribe(Subscription s) {
                sub.onSubscribe(s);
            }

            @Override
            public void onNext(Integer integer) {
                es.execute(() -> sub.onNext(integer));
            }

            @Override
            public void onError(Throwable t) {
                es.execute(() -> sub.onError(t));
                es.shutdown();
            }

            @Override
            public void onComplete() {
                es.execute(() -> sub.onComplete());
                es.shutdown();
            }
        });
    };

    pubOnPub.subscribe(new Subscriber<Integer>() {
        @Override
        public void onSubscribe(Subscription s) {
            log.debug("onSubscribe");
            s.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Integer integer) {
            log.debug("onNext : {}", integer);
        }

        @Override
        public void onError(Throwable t) {
            log.debug("onError : {}", t);
        }

        @Override
        public void onComplete() {
            log.debug("onComplete");
        }
    });

    log.debug("exit");
}

From source file:io.bitsquare.seednode.SeedNodeMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("SeedNodeMain").setDaemon(true)
            .build();//w  ww  .j  ava 2 s.co  m
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_seednode");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(SeedNodeMain.class.getClassLoader());

    new SeedNodeMain().execute(args);
}

From source file:io.bitsquare.statistics.StatisticsMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Statistics").setDaemon(true)
            .build();//from www .  j  ava 2 s . c  o  m
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_statistics");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(StatisticsMain.class.getClassLoader());

    new StatisticsMain().execute(args);
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java

public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();

    // Most of the following defaults should be changed in
    // the --conf or "conf.properties" file
    String sqlURL = null;/*from  w  w  w  .  jav a2s. com*/
    String sqlUser = null;
    String sqlPass = null;
    String sqlDb = null;
    String sqlHost = "127.0.0.1";
    String backupDirStr = null;
    String laterThanStr = "";
    String fullBackupPathStr = null;
    String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak";
    String fullBackupDatePatternStr = "yyyyMMddHHmm";
    String sqlProcessUser = null;
    String logBackupPatternStr = "(.*)\\.trn";
    String logBackupDatePatternStr = "yyyyMMddHHmmss";

    boolean doFullRestore = false;
    Boolean useLogFileLastMode = null;
    Boolean monitorLogBackupDir = null;

    options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build());

    options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build());

    options.addOption(Option.builder().longOpt("restore-full")
            .desc("Restore the full backup before continuing.").build());

    options.addOption(Option.builder().longOpt("use-lastmod")
            .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build());

    options.addOption(Option.builder().longOpt("monitor-backup-dir")
            .desc("Monitor the backup directory for new log backups, and apply them.").build());

    CommandLine line = null;
    try {
        try {
            line = parser.parse(options, args);
        } catch (ParseException ex) {
            throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()),
                    ex);
        }

        String confFile = null;

        // Process the command line arguments
        Iterator cmdI = line.iterator();
        while (cmdI.hasNext()) {
            Option currOpt = (Option) cmdI.next();
            String currOptName = currOpt.getLongOpt();

            switch (currOptName) {
            case "conf":
                // Parse the configuration file
                confFile = currOpt.getValue();
                break;

            case "laterthan":
                // "Later Than" file date filter
                laterThanStr = currOpt.getValue();
                break;

            case "restore-full":
                // Do a full backup restore before restoring logs
                doFullRestore = true;
                break;

            case "monitor-backup-dir":
                // Monitor the backup directory for new logs
                monitorLogBackupDir = true;
                break;

            case "use-lastmod":
                // Use the last-modified date on Log Backup files for sorting/filtering
                useLogFileLastMode = true;
                break;
            }
        }

        Properties confProperties = null;

        if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) {
            throw new MSSQLApplyLogException(
                    "Missing or unreadable configuration file.  Please specify --conf");
        } else {
            // Process the conf.properties file
            confProperties = new Properties();
            try {
                confProperties.load(Files.newBufferedReader(Paths.get(confFile)));
            } catch (IOException ex) {
                throw new MSSQLApplyLogException("Error loading properties file", ex);
            }

            sqlURL = confProperties.getProperty("sqlURL", "");
            sqlUser = confProperties.getProperty("sqlUser", "");
            sqlPass = confProperties.getProperty("sqlPass", "");
            sqlDb = confProperties.getProperty("sqlDb", "");
            sqlHost = confProperties.getProperty("sqlHost", "");
            backupDirStr = confProperties.getProperty("backupDir", "");

            if (StringUtils.isBlank(laterThanStr)) {
                laterThanStr = confProperties.getProperty("laterThan", "");
            }

            fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr);
            fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr);
            fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern",
                    fullBackupDatePatternStr);
            sqlProcessUser = confProperties.getProperty("sqlProcessUser", "");

            logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr);
            logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern",
                    logBackupDatePatternStr);

            if (useLogFileLastMode == null) {
                String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false");
                useLogFileLastMode = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr)));
            }

            if (monitorLogBackupDir == null) {
                String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false");
                monitorLogBackupDir = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr)));
            }
        }
    } catch (MSSQLApplyLogException ex) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.append(String.format("Error : '%s'\n\n", ex.getMessage()));

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ",
                    "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options,
                    0, 2, " All Rights Reserved.", true);

            System.out.println(sw.toString());
        } catch (IOException iex) {
            LOGGER.debug("Error processing usage", iex);
        }

        System.exit(1);
    }

    MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr,
            fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr,
            logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser,
            useLogFileLastMode, doFullRestore, monitorLogBackupDir);

    MSSQLApplyLog logProc = MSSQLApplyLog.from(config);

    BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build();

    ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory);

    Future<Integer> currRunTask = mainThreadExe.submit(logProc);

    mainThreadExe.shutdown();

    Integer resp = 0;
    try {
        resp = currRunTask.get();
    } catch (InterruptedException ex) {
        LOGGER.error("Application 'main' thread was interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("Application 'main' thread execution error", ex);
    } finally {
        // If main leaves for any reason, shutdown all threads
        mainThreadExe.shutdownNow();
    }

    System.exit(resp);
}

From source file:Main.java

/**
 * Wrapper over newSingleThreadExecutor.
 *//* ww  w  .  j a va 2s .c  o  m*/
public static ExecutorService newDaemonSingleThreadExecutor(String threadName) {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(threadName).build();
    return Executors.newSingleThreadExecutor(threadFactory);
}

From source file:Main.java

public static ExecutorService createEventsOrderedDeliveryExecutor() {
    return Executors.newSingleThreadExecutor(new ThreadFactory() {
        private AtomicInteger cnt = new AtomicInteger(0);

        @Override/* w w w  .j av a2s .  c  o m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "Ordered Events Thread-" + cnt.incrementAndGet());
            t.setDaemon(true);
            // XXX perhaps set uncaught exception handler here according to resilience strategy
            return t;
        }
    });
}

From source file:Main.java

public static ExecutorService newSingleThreadExecutor(String processName) {
    return Executors.newSingleThreadExecutor(newThreadFactory(processName));
}

From source file:Main.java

/**
 * Instantiates a new single threaded executor whose thread has the specified name.
 *
 * @param threadName The name of the thread.
 * @return The executor.//w w  w.j  a va  2  s  .c  om
 */
public static ExecutorService newSingleThreadExecutor(final String threadName) {
    return Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, threadName);
        }
    });
}

From source file:Main.java

public static ExecutorService newSingleThreadExecutor(String name) {
    return Executors.newSingleThreadExecutor(newNamedThreadFactory(name));
}

From source file:Main.java

public static ExecutorService newSingleThreadExecutor(String processName, boolean isDaemon) {
    return Executors.newSingleThreadExecutor(newThreadFactory(processName, isDaemon));
}