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:Main.java

public static void main(String[] args) throws Exception {

    ExecutorService ex = Executors.newSingleThreadExecutor();

    Future<Integer> future =
            // This Lambda evaluated to Callable<Integer>
            ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10));

    System.out.println("Randomized value: " + future.get());

}

From source file:Main.java

public static void main(String[] args) {
    Runnable badTask = () -> {
        throw new RuntimeException("Throwing exception  from  task execution...");
    };/*from   w w  w.  j a v  a 2  s.  c  o m*/

    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(badTask);
    exec.shutdown();
}

From source file:Main.java

public static void main(String[] args) throws InterruptedException, ExecutionException {

    ExecutorService ex = Executors.newSingleThreadExecutor();

    Future<Integer> future =
            // This Lambda evaluated to Callable<Integer>
            ex.submit(() -> ThreadLocalRandom.current().nextInt(1, 10));

    System.out.println("Randomized value: " + future.get());

}

From source file:Main.java

public static void main(String[] args) {
    Callable<Object> badTask = () -> {
        throw new RuntimeException("Throwing exception from task execution...");
    };/*from w  w w. j av a  2s  .c o m*/
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Future submittedTask = exec.submit(badTask);
    try {
        Object result = submittedTask.get();
    } catch (ExecutionException e) {
        System.out.println(e.getMessage());
        System.out.println(e.getCause().getMessage());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    exec.shutdown();
}

From source file:example.rhino.DynamicScopesWithHandlebars.java

public static void main(String[] args) {
    Context cx = Context.enter();
    try {/*  w w w  .j a  v a2s  .c  o  m*/
        String source = handlebars();
        Script script = cx.compileString(source, "handlebars", 1, null);

        System.out.println("Running the script in a single thread");
        runScripts(cx, script, Executors.newSingleThreadExecutor());

        int nThreads = Runtime.getRuntime().availableProcessors();
        System.out.format("Running the script in %d thread\n", nThreads);

        runScripts(cx, script, Executors.newFixedThreadPool(nThreads));

    } catch (IOException e) {
        System.err.println("No handlebars file found");
    } finally {
        Context.exit();
    }
}

From source file:com.level3.hiper.dyconn.be.Main.java

public static void main(String... args) {

    try {//from  w  w w  .j av  a2s .co m
        String bootstrap = "/dyconn-be-toml.cfg";
        CommandLineParser parser = new DefaultParser();
        Options options = new Options();
        options.addOption("c", "config-file", true, "configuration for hapi dyconn module");
        try {
            CommandLine line = parser.parse(options, args);
            if (line.hasOption("config-file")) {
                bootstrap = line.getOptionValue("config-file");
            }
        } catch (ParseException ex) {
            log.error("command line", ex);
            return;
        }

        // read config file
        log.info("loading configuration");
        Config.instance().initialize(bootstrap);

        // initialize queue subsystem
        log.info("initializing messaging");
        Broker.instance().initialize();

        // initilaize persistence
        log.info("starting exector");
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new MsgReceiver());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.barchart.udt.AppServer.java

public static void main(final String[] args) throws IOException {

    int port = 9000;

    if (args.length > 1) {
        System.out.println("usage: appserver [server_port]");
        return;//  w  ww .jav a  2  s.  c o m
    }

    if (args.length == 1) {
        port = Integer.parseInt(args[0]);
    }

    final NetServerSocketUDT acceptorSocket = new NetServerSocketUDT();
    acceptorSocket.bind(new InetSocketAddress(getLocalHost(), port), 256);

    System.out.printf("server is ready at port: %d\n", port);
    System.out.println("server is ready");
    while (true) {

        final Socket clientSocket = acceptorSocket.accept();

        // Start the read ahead background task
        Executors.newSingleThreadExecutor().submit(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                return clientTask(clientSocket);
            }
        });
    }
}

From source file:org.jboss.aerogear.sync.server.netty.JsonPatchSyncServer.java

public static void main(final String... args) throws Exception {
    final String configFile = args.length == 0 ? DEFAULT_CONFIG : args[0];
    final StandaloneConfig config = ConfigReader.parse(configFile);
    final EventLoopGroup bossGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup();

    final JsonPatchServerSynchronizer synchronizer = new JsonPatchServerSynchronizer();
    final ServerInMemoryDataStore<JsonNode, JsonPatchEdit> dataStore = new ServerInMemoryDataStore<JsonNode, JsonPatchEdit>();
    final ServerSyncEngine<JsonNode, JsonPatchEdit> syncEngine = new ServerSyncEngine<JsonNode, JsonPatchEdit>(
            synchronizer, dataStore);//from   ww w . j a  va 2  s.c om
    final DiffSyncHandler<JsonNode, JsonPatchEdit> diffSyncHandler = new DiffSyncHandler<JsonNode, JsonPatchEdit>(
            syncEngine);
    try {
        final ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder(), new HttpObjectAggregator(65536),
                                new HttpResponseEncoder(), new WebSocketServerProtocolHandler("/sync"),
                                diffSyncHandler);
                    }
                });
        if (config.isGcmEnabled()) {
            sb.handler(new GcmHandler<JsonNode, JsonPatchEdit>(config, syncEngine,
                    Executors.newSingleThreadExecutor()));
        }

        final Channel ch = sb.bind(config.host(), config.port()).sync().channel();
        logger.info("JsonPatchSyncServer bound to {}:{}", config.host(), config.port());

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.jboss.aerogear.sync.server.netty.JsonMergePatchSyncServer.java

public static void main(final String... args) throws Exception {
    final String configFile = args.length == 0 ? DEFAULT_CONFIG : args[0];
    final StandaloneConfig config = ConfigReader.parse(configFile);
    final EventLoopGroup bossGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup();

    final JsonMergePatchServerSynchronizer synchronizer = new JsonMergePatchServerSynchronizer();
    final ServerInMemoryDataStore<JsonNode, JsonMergePatchEdit> dataStore = new ServerInMemoryDataStore<JsonNode, JsonMergePatchEdit>();
    final ServerSyncEngine<JsonNode, JsonMergePatchEdit> syncEngine = new ServerSyncEngine<JsonNode, JsonMergePatchEdit>(
            synchronizer, dataStore);//from   www . j a va2  s.com
    final DiffSyncHandler<JsonNode, JsonMergePatchEdit> diffSyncHandler = new DiffSyncHandler<JsonNode, JsonMergePatchEdit>(
            syncEngine);
    try {
        final ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder(), new HttpObjectAggregator(65536),
                                new HttpResponseEncoder(), new WebSocketServerProtocolHandler("/sync"),
                                diffSyncHandler);
                    }
                });
        if (config.isGcmEnabled()) {
            sb.handler(new GcmHandler<JsonNode, JsonMergePatchEdit>(config, syncEngine,
                    Executors.newSingleThreadExecutor()));
        }

        final Channel ch = sb.bind(config.host(), config.port()).sync().channel();
        logger.info("JsonMergePatchSyncServer bound to {}:{}", config.host(), config.port());

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.spotify.heroic.HeroicShell.java

public static void main(String[] args) throws IOException {
    HeroicLogging.configure();//from   w w  w . ja v a  2s .  co  m

    Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
        try {
            log.error("Uncaught exception in thread {}, exiting...", t, e);
        } finally {
            System.exit(1);
        }
    });

    final Parameters params = new Parameters();
    final CmdLineParser parser = setupParser(params);
    final ParsedArguments parsed = ParsedArguments.parse(args);

    try {
        parser.parseArgument(parsed.primary);
    } catch (CmdLineException e) {
        log.error("Argument error", e);
        System.exit(1);
        return;
    }

    if (params.help()) {
        parser.printUsage(System.out);
        System.out.println();
        HeroicModules.printAllUsage(System.out, "-P");
        System.exit(0);
        return;
    }

    final AsyncFramework async = TinyAsync.builder().executor(Executors.newSingleThreadExecutor()).build();

    if (parsed.child.isEmpty()) {
        final CoreInterface bridge;

        try {
            bridge = setupCoreBridge(params, async);
        } catch (Exception e) {
            log.error("Failed to setup core bridge", e);
            System.exit(1);
            return;
        }
        try {
            interactive(params, bridge);
        } catch (Exception e) {
            log.error("Error when running shell", e);
            System.exit(1);
        }
        System.exit(0);
        return;
    }

    final HeroicCore.Builder builder = setupBuilder(params);

    try {
        standalone(parsed.child, builder);
    } catch (Exception e) {
        log.error("Failed to run standalone task", e);
    }

    System.exit(0);
}