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:com.meltmedia.cadmium.core.worker.ConfigCoordinatedWorkerImpl.java

public ConfigCoordinatedWorkerImpl() {
    pool = Executors.newSingleThreadExecutor();
    listener = this;
}

From source file:com.meltmedia.cadmium.core.history.HistoryManagerTest.java

@Before
public void setupForTest() throws Exception {
    File testDir = new File("./target/history-test");
    testDirectory = testDir.getAbsoluteFile().getAbsolutePath();

    if (!testDir.exists()) {
        testDir.mkdirs();/*w ww  . j a  v  a2 s . c o m*/
    }

    historyFile = new File(testDir, HistoryManager.HISTORY_FILE_NAME);

    if (!historyFile.exists() || historyFile.canWrite()) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(historyFile, false);
            writer.write(INIT_HISTORY_CONTENT);
            writer.flush();
        } catch (Exception e) {
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    manager = new HistoryManager(testDirectory, Executors.newSingleThreadExecutor(), mock(EventQueue.class));
}

From source file:com.qubole.rubix.hadoop2.hadoop2CM.Hadoop2ClusterManager.java

@Override
public void initialize(Configuration conf) {
    super.initialize(conf);
    yconf = new YarnConfiguration();
    this.address = yconf.get(addressConf, address);
    this.serverAddress = address.substring(0, address.indexOf(":"));
    this.serverPort = Integer.parseInt(address.substring(address.indexOf(":") + 1));

    ExecutorService executor = Executors.newSingleThreadExecutor();
    nodesCache = CacheBuilder.newBuilder().refreshAfterWrite(getNodeRefreshTime(), TimeUnit.SECONDS)
            .build(CacheLoader.asyncReloading(new CacheLoader<String, List<String>>() {
                @Override/* w  w w .j  a  v  a 2 s.c  o  m*/
                public List<String> load(String s) throws Exception {
                    if (!isMaster) {
                        // First time all nodes start assuming themselves as master and down the line figure out their role
                        // Next time onwards, only master will be fetching the list of nodes
                        return ImmutableList.of();
                    }
                    try {
                        StringBuffer response = new StringBuffer();
                        URL obj = getNodeURL();
                        HttpURLConnection httpcon = (HttpURLConnection) obj.openConnection();
                        httpcon.setRequestMethod("GET");
                        log.debug("Sending 'GET' request to URL: " + obj.toString());
                        int responseCode = httpcon.getResponseCode();
                        if (responseCode == HttpURLConnection.HTTP_OK) {
                            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(httpcon.getInputStream()));
                            String inputLine;
                            while ((inputLine = in.readLine()) != null) {
                                response.append(inputLine);
                            }
                            in.close();
                            httpcon.disconnect();
                        } else {
                            log.info("/ws/v1/cluster/nodes failed due to " + responseCode
                                    + ". Setting this node as worker.");
                            isMaster = false;
                            httpcon.disconnect();
                            return ImmutableList.of();
                        }
                        Gson gson = new Gson();
                        Type type = new TypeToken<Nodes>() {
                        }.getType();
                        Nodes nodes = gson.fromJson(response.toString(), type);
                        List<Elements> allNodes = nodes.getNodes().getNode();
                        Set<String> hosts = new HashSet<>();

                        for (Elements node : allNodes) {
                            String state = node.getState();
                            log.debug("Hostname: " + node.getNodeHostName() + "State: " + state);
                            //keep only healthy data nodes
                            if (state.equalsIgnoreCase("Running") || state.equalsIgnoreCase("New")
                                    || state.equalsIgnoreCase("Rebooted")) {
                                hosts.add(node.getNodeHostName());
                            }
                        }

                        if (hosts.isEmpty()) {
                            throw new Exception("No healthy data nodes found.");
                        }

                        List<String> hostList = Lists.newArrayList(hosts.toArray(new String[0]));
                        Collections.sort(hostList);
                        log.debug("Hostlist: " + hostList.toString());
                        return hostList;
                    } catch (Exception e) {
                        throw Throwables.propagate(e);
                    }
                }
            }, executor));
}

From source file:it.drwolf.ridire.session.async.IndexerService.java

@Create
public void init() {
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    this.completionService = new ExecutorCompletionService<IndexingResult>(executorService);
}

From source file:uk.gov.nationalarchives.discovery.taxonomy.batch.actor.worker.CategorisationWorkerRunner.java

@Override
public void run(String... args) {
    Executors.newSingleThreadExecutor().submit(() -> {
        trackDeadLetters();/*from w  ww  .ja  v  a 2 s . c o m*/

        String supervisorAddress = "akka.tcp://supervisor@" + supervisorHostname + ":" + supervisorPort
                + "/user/supervisorActor";
        ActorRef worker = actorSystem.actorOf(Props.create(CategorisationWorkerActor.class, supervisorAddress,
                categoriserService, luceneHelperTools, categoryRepository), "workerActor");

        try {
            Thread.sleep(2000);
        } catch (Exception e) {
            //do nothing
        }

        if (this.startEpic) {
            ActorSelection supervisorReference = actorSystem.actorSelection(supervisorAddress);
            if (afterDocNumber == null) {
                supervisorReference.tell(new CategoriseAllDocumentsEpic(), worker);
            } else {
                supervisorReference.tell(new CategoriseAllDocumentsEpic(this.afterDocNumber), worker);
            }
        }
    });

}

From source file:jp.co.brilliantservice.android.ric.command.HttpController.java

public HttpController(ProjectFile project, Activity context, String server) {
    super(project, null);
    this.context = context;
    this.exec = Executors.newSingleThreadExecutor();
    this.out = adapter;
    this.server = server;
}

From source file:com.android.settings.security.SecurityFeatureProviderImpl.java

/** Update preferences with data from associated tiles. */
public void updatePreferences(final Context context, final PreferenceScreen preferenceScreen,
        final DashboardCategory dashboardCategory) {
    if (preferenceScreen == null) {
        return;/*  ww w .j  a v  a2  s .  c o  m*/
    }
    int tilesCount = (dashboardCategory != null) ? dashboardCategory.getTilesCount() : 0;
    if (tilesCount == 0) {
        return;
    }

    initPreferences(context, preferenceScreen, dashboardCategory);

    // Fetching the summary and icon from the provider introduces latency, so do this on a
    // separate thread.
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            updatePreferencesToRunOnWorkerThread(context, preferenceScreen, dashboardCategory);
        }
    });
}

From source file:mamo.vanillaVotifier.VotifierServer.java

public synchronized void start() throws IOException {
    if (isRunning()) {
        throw new IllegalStateException("Server is already running!");
    }//from   w  ww. j  ava2s .  c  om
    notifyListeners(new ServerStartingEvent());
    serverSocket = new ServerSocket();
    serverSocket.bind(votifier.getConfig().getInetSocketAddress());
    running = true;
    notifyListeners(new ServerStartedEvent());
    new Thread(new Runnable() {
        @Override
        public void run() {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            while (isRunning()) {
                try {
                    final Socket socket = serverSocket.accept();
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                notifyListeners(new ConnectionEstablishedEvent(socket));
                                socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch.
                                BufferedWriter writer = new BufferedWriter(
                                        new OutputStreamWriter(socket.getOutputStream()));
                                writer.write("VOTIFIER 2.9\n");
                                writer.flush();
                                BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch.
                                byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair()
                                        .getPublic()).getModulus().bitLength() / Byte.SIZE];
                                in.read(request); // IOException: handled by try/catch.
                                notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request)));
                                request = RsaUtils
                                        .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate())
                                        .doFinal(request); // IllegalBlockSizeException: can't happen.
                                String requestString = new String(request);
                                notifyListeners(new DecryptedInputReceivedEvent(socket, requestString));
                                String[] requestArray = requestString.split("\n");
                                if ((requestArray.length == 5 || requestArray.length == 6)
                                        && requestArray[0].equals("VOTE")) {
                                    notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1],
                                            requestArray[2], requestArray[3], requestArray[4])));
                                    for (VoteAction voteAction : votifier.getConfig().getVoteActions()) {
                                        String[] params = new String[4];
                                        try {
                                            for (int i = 0; i < params.length; i++) {
                                                params[i] = SubstitutionUtils.applyRegexReplacements(
                                                        requestArray[i + 1], voteAction.getRegexReplacements());
                                            }
                                        } catch (PatternSyntaxException e) {
                                            notifyListeners(new RegularExpressionPatternErrorException(e));
                                            params = new String[] { requestArray[1], requestArray[2],
                                                    requestArray[3], requestArray[4] };
                                        }
                                        if (voteAction.getCommandSender() instanceof RconCommandSender) {
                                            RconCommandSender commandSender = (RconCommandSender) voteAction
                                                    .getCommandSender();
                                            StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor(
                                                    new SimpleEntry<String, Object>("service-name", params[0]),
                                                    new SimpleEntry<String, Object>("user-name", params[1]),
                                                    new SimpleEntry<String, Object>("address", params[2]),
                                                    new SimpleEntry<String, Object>("timestamp", params[3]));
                                            for (String command : voteAction.getCommands()) {
                                                String theCommand = substitutor.replace(command);
                                                notifyListeners(new SendingRconCommandEvent(
                                                        commandSender.getRconConnection(), theCommand));
                                                try {
                                                    notifyListeners(new RconCommandResponseEvent(
                                                            commandSender.getRconConnection(), commandSender
                                                                    .sendCommand(theCommand).getPayload()));
                                                } catch (Exception e) {
                                                    notifyListeners(new RconExceptionEvent(
                                                            commandSender.getRconConnection(), e));
                                                }
                                            }
                                        }
                                        if (voteAction.getCommandSender() instanceof ShellCommandSender) {
                                            ShellCommandSender commandSender = (ShellCommandSender) voteAction
                                                    .getCommandSender();
                                            HashMap<String, String> environment = new HashMap<String, String>();
                                            environment.put("voteServiceName", params[0]);
                                            environment.put("voteUserName", params[1]);
                                            environment.put("voteAddress", params[2]);
                                            environment.put("voteTimestamp", params[3]);
                                            for (String command : voteAction.getCommands()) {
                                                notifyListeners(new SendingShellCommandEvent(command));
                                                try {
                                                    commandSender.sendCommand(command, environment);
                                                    notifyListeners(new ShellCommandSentEvent());
                                                } catch (Exception e) {
                                                    notifyListeners(new ShellCommandExceptionEvent(e));
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    notifyListeners(new InvalidRequestEvent(socket, requestString));
                                }
                            } catch (SocketTimeoutException e) {
                                notifyListeners(new ReadTimedOutExceptionEvent(socket, e));
                            } catch (BadPaddingException e) {
                                notifyListeners(new DecryptInputExceptionEvent(socket, e));
                            } catch (Exception e) {
                                notifyListeners(new CommunicationExceptionEvent(socket, e));
                            }
                            try {
                                socket.close();
                                notifyListeners(new ConnectionClosedEvent(socket));
                            } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close.
                                notifyListeners(new ConnectionCloseExceptionEvent(socket, e));
                            }
                        }
                    });
                } catch (Exception e) {
                    if (running) { // Show errors only while running, to hide error while stopping.
                        notifyListeners(new ConnectionEstablishExceptionEvent(e));
                    }
                }
            }
            executorService.shutdown();
            if (!executorService.isTerminated()) {
                notifyListeners(new ServerAwaitingTaskCompletionEvent());
                try {
                    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
                } catch (Exception e) {
                    // InterruptedException: can't happen.
                }
            }
            notifyListeners(new ServerStoppedEvent());
        }
    }).start();
}

From source file:org.suren.autotest.web.framework.selenium.action.SeleniumFileUpload.java

@Override
public boolean upload(Element element, final File file) {
    WebElement webEle = findElement(element);
    if (webEle != null) {
        logger.info("File upload, element is already found.");
        ExecutorService executor = Executors.newSingleThreadExecutor();

        final AutoItCmd autoItCmd = new AutoItCmd();
        try {//from   w w  w  .ja v a  2 s. c o m
            Future<?> future = executor.submit(new Runnable() {

                @Override
                public void run() {
                    try {
                        autoItCmd.execFileChoose(file);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            synchronized (autoItCmd) {
                autoItCmd.wait();
            }

            click(element);

            if (!future.isDone()) {
                future.get(30, TimeUnit.SECONDS);
            }

            return true;
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            logger.error("File uplod error.", e);
            e.printStackTrace();
        } finally {
            autoItCmd.close();
            executor.shutdown();
        }
    } else {
        logger.error("Can not found element, when prepare to upload file.");
    }

    return false;
}

From source file:com.canoo.dolphin.client.ClientContextFactory.java

/**
 * Create a {@link ClientContext} based on the given configuration. This method doesn't block and returns a
 * {@link CompletableFuture} to receive its result. If the {@link ClientContext} can't be created the
 * {@link CompletableFuture#get()} will throw a {@link ClientInitializationException}.
 *
 * @param clientConfiguration the configuration
 * @return the future// ww w  .j  a  va  2  s  . co m
 */
public static CompletableFuture<ClientContext> connect(final ClientConfiguration clientConfiguration) {
    Assert.requireNonNull(clientConfiguration, "clientConfiguration");
    final CompletableFuture<ClientContext> result = new CompletableFuture<>();

    Level openDolphinLogLevel = clientConfiguration.getDolphinLogLevel();
    Logger openDolphinLogger = Logger.getLogger("org.opendolphin");
    openDolphinLogger.setLevel(openDolphinLogLevel);

    Executors.newSingleThreadExecutor().execute(() -> {
        try {
            final ForwardableCallback<DolphinRemotingException> remotingErrorHandler = new ForwardableCallback<>();
            final ClientDolphin clientDolphin = new ClientDolphin();
            clientDolphin.setClientModelStore(new ClientModelStore(clientDolphin));
            final HttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
            final ClientConnector clientConnector = new DolphinPlatformHttpClientConnector(clientDolphin,
                    new OptimizedJsonCodec(), httpClient, clientConfiguration.getServerEndpoint(),
                    remotingErrorHandler, clientConfiguration.getUiThreadHandler());
            clientDolphin.setClientConnector(clientConnector);
            final DolphinCommandHandler dolphinCommandHandler = new DolphinCommandHandler(clientDolphin);
            final EventDispatcher dispatcher = new ClientEventDispatcher(clientDolphin);
            final BeanRepository beanRepository = new BeanRepositoryImpl(clientDolphin, dispatcher);
            final Converters converters = new Converters(beanRepository);
            final PresentationModelBuilderFactory builderFactory = new ClientPresentationModelBuilderFactory(
                    clientDolphin);
            final ClassRepository classRepository = new ClassRepositoryImpl(clientDolphin, converters,
                    builderFactory);
            final ListMapper listMapper = new ListMapperImpl(clientDolphin, classRepository, beanRepository,
                    builderFactory, dispatcher);
            final BeanBuilder beanBuilder = new ClientBeanBuilderImpl(classRepository, beanRepository,
                    listMapper, builderFactory, dispatcher);
            final ClientPlatformBeanRepository platformBeanRepository = new ClientPlatformBeanRepository(
                    clientDolphin, beanRepository, dispatcher, converters);
            final ClientBeanManagerImpl clientBeanManager = new ClientBeanManagerImpl(beanRepository,
                    beanBuilder, clientDolphin);
            final ControllerProxyFactory controllerProxyFactory = new ControllerProxyFactoryImpl(
                    platformBeanRepository, dolphinCommandHandler, clientDolphin);
            final ClientContext clientContext = new ClientContextImpl(clientConfiguration, clientDolphin,
                    controllerProxyFactory, dolphinCommandHandler, platformBeanRepository, clientBeanManager,
                    remotingErrorHandler);
            clientDolphin.startPushListening(PlatformConstants.POLL_EVENT_BUS_COMMAND_NAME,
                    PlatformConstants.RELEASE_EVENT_BUS_COMMAND_NAME);
            clientConfiguration.getUiThreadHandler()
                    .executeInsideUiThread(() -> result.complete(clientContext));
        } catch (Exception e) {
            result.obtrudeException(new ClientInitializationException("Can not connect to server!", e));
            throw new ClientInitializationException(e);
        }
    });
    return result;
}