List of usage examples for java.util.concurrent Executors newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
From source file:am.roadpolice.roadpolice.alarm.AlarmReceiver.java
@Override public void onReceive(Context context, Intent intent) { if (context == null || intent == null) { Logger.error("AlarmReceiver", "onReceive(Context " + (context == null ? "null," : ",") + " Intent " + (intent == null ? "null)" : ")")); return;/*from w ww . j ava 2 s . co m*/ } // Set Context mContext = context; // Get shared preferences. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); // Check internet availability and only in that case start actions. final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); final String action = intent.getAction(); // Catch Network change state. if (!TextUtils.isEmpty(action) && action.equals("android.net.conn.CONNECTIVITY_CHANGE")) { // If internet connection established if (isConnected) { // If didn't missed last update of data due to network issues do nothing, // otherwise proceed with data updating. final boolean missUpdateDueToNetworkIssue = sp .getBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, false); if (!missUpdateDueToNetworkIssue) return; } // If user switch off Internet connection do not proceed. else return; } // Check Boot state. else if (!TextUtils.isEmpty(action) && action.equals("android.intent.action.BOOT_COMPLETED")) { // Get stored alarm time. final long nextAlarmTime = PreferenceUtils.getDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, -1); if (nextAlarmTime != -1) { // Set new alarm, as after reboot alarm was switched off. if (mAlarmManager == null) mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent alarmIntent = new Intent(context, AlarmReceiver.class); if (mAlarmIntent == null) mAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0); // Enable boot receiver ComponentName receiver = new ComponentName(context, AlarmReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); final int ui = DialogSettings.getUpdateInterval(context); AlarmType type = ui == DialogSettings.DAILY ? AlarmType.DAILY : ui == DialogSettings.WEEKLY ? AlarmType.WEEKLY : AlarmType.MONTHLY; mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, nextAlarmTime, type.getValue(), mAlarmIntent); } return; } // When alarm rise we appears in the block below. else { Logger.beep(); Logger.beep(); Logger.beep(); // Calculating next alarm time. final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); final int updateInterval = DialogSettings.getUpdateInterval(context); if (updateInterval == DialogSettings.DAILY) calendar.add(Calendar.DATE, 1); else if (updateInterval == DialogSettings.WEEKLY) calendar.add(Calendar.DATE, 7); else if (updateInterval == DialogSettings.MONTHLY) calendar.add(Calendar.MONTH, 1); else Logger.error("AlarmReceiver", "Unknown Update Interval."); // Next alarm time. final long nextAlarmTimeInMillis = calendar.getTimeInMillis(); // Store next alarm time for further use. PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, nextAlarmTimeInMillis); } if (!isConnected) { Logger.debug("AlarmReceiver", "No Internet connection, while receiving Alarm message"); // If no internet connecting schedule data update, as soon // as internet connection will be available. SharedPreferences.Editor ed = sp.edit(); ed.putBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, true); ed.apply(); return; } final String cerNum = sp.getString(MainActivity.CER_NUMBER, MainActivity.EMPTY_STRING); final String regNum = sp.getString(MainActivity.REG_NUMBER, MainActivity.EMPTY_STRING); final boolean login = sp.getBoolean(MainActivity.AUTO_LOGIN, false); if (!login) { // If no auto login user detected. Logger.debug("AlarmReceiver", "Why we enter this case if no auto login users detected?"); // Remove alarm. AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE); return; } if (TextUtils.isEmpty(cerNum) || TextUtils.isEmpty(regNum)) { Logger.debug("AlarmReceiver", "Why we enter this case if both data are null or empty?"); // Remove alarm. AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE); // Remove auto login. SharedPreferences.Editor ed = sp.edit(); ed.putBoolean(MainActivity.AUTO_LOGIN, false); ed.apply(); return; } // Start downloading data from internet. Submitter submitter = new Submitter(cerNum, regNum, this); submitter.executeOnExecutor(Executors.newSingleThreadExecutor()); }
From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java
@Test public void testProduceStringRecordsMultiplePartitions() throws StageException, InterruptedException { CountDownLatch startProducing = new CountDownLatch(1); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(new ProducerRunnable(TOPIC2, MULTIPLE_PARTITIONS, producer, startProducing, DataType.TEXT, null, -1, null)); KafkaConfigBean conf = new KafkaConfigBean(); conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI(); conf.topic = TOPIC2;/* w w w . j a v a2 s .co m*/ conf.consumerGroup = CONSUMER_GROUP; conf.zookeeperConnect = zkConnect; conf.maxBatchSize = 9; conf.maxWaitTime = 5000; conf.kafkaConsumerConfigs = null; conf.produceSingleRecordPerMessage = false; conf.dataFormat = DataFormat.TEXT; conf.dataFormatConfig.charset = "UTF-8"; conf.dataFormatConfig.removeCtrlChars = false; conf.dataFormatConfig.textMaxLineLen = 4096; SourceRunner sourceRunner = new SourceRunner.Builder(StandaloneKafkaSource.class, createSource(conf)) .addOutputLane("lane").build(); sourceRunner.runInit(); startProducing.countDown(); List<Record> records = new ArrayList<>(); StageRunner.Output output = getOutputAndRecords(sourceRunner, 9, "lane", records); shutDownExecutorService(executorService); String newOffset = output.getNewOffset(); Assert.assertNull(newOffset); Assert.assertEquals(9, records.size()); for (int i = 0; i < records.size(); i++) { Assert.assertNotNull(records.get(i).get("/text").getValueAsString()); Assert.assertTrue(!records.get(i).get("/text").getValueAsString().isEmpty()); Assert.assertEquals(sdcKafkaTestUtil.generateTestData(DataType.TEXT, null), records.get(i).get("/text").getValueAsString()); } sourceRunner.runDestroy(); }
From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java
/** * /*from ww w . j a v a2s .com*/ */ private void stopContainer() { try { if (container != null) { logger.info("Stopping Tomcat..."); // stopping Tomcat may block, so we need to do it in another // thread and join. final ExecutorService executor = Executors.newSingleThreadExecutor(); try { Future future = executor.submit(new Runnable() { public void run() { try { container.stop(); container = null; logger.info("Tomcat has been stopped."); } catch (LifecycleException e) { logger.severe(ExceptionUtils.getFullStackTrace(e)); } } }); future.get(TOMCAT_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS); } finally { executor.shutdownNow(); } } } catch (Exception e) { logger.severe(ExceptionUtils.getFullStackTrace(e)); } }
From source file:com.jivesoftware.os.amza.sync.deployable.AmzaSyncMain.java
public void run(String[] args) throws Exception { ServiceStartupHealthCheck serviceStartupHealthCheck = new ServiceStartupHealthCheck(); try {/*from ww w .ja va 2 s .c om*/ final Deployable deployable = new Deployable(args); InstanceConfig instanceConfig = deployable.config(InstanceConfig.class); HealthFactory.initialize(deployable::config, new DeployableHealthCheckRegistry(deployable)); deployable.addManageInjectables(HasUI.class, new HasUI(Arrays.asList(new UI("Sync", "main", "/ui")))); deployable.addHealthCheck(new GCPauseHealthChecker( deployable.config(GCPauseHealthChecker.GCPauseHealthCheckerConfig.class))); deployable.addHealthCheck(new GCLoadHealthChecker( deployable.config(GCLoadHealthChecker.GCLoadHealthCheckerConfig.class))); deployable.addHealthCheck(new SystemCpuHealthChecker( deployable.config(SystemCpuHealthChecker.SystemCpuHealthCheckerConfig.class))); deployable.addHealthCheck(new LoadAverageHealthChecker( deployable.config(LoadAverageHealthChecker.LoadAverageHealthCheckerConfig.class))); deployable.addHealthCheck(new FileDescriptorCountHealthChecker(deployable .config(FileDescriptorCountHealthChecker.FileDescriptorCountHealthCheckerConfig.class))); deployable.addHealthCheck(serviceStartupHealthCheck); deployable.addErrorHealthChecks(deployable.config(ErrorHealthCheckConfig.class)); deployable.addManageInjectables(FullyOnlineVersion.class, (FullyOnlineVersion) () -> { if (serviceStartupHealthCheck.startupHasSucceeded()) { return instanceConfig.getVersion(); } else { return null; } }); deployable.buildManageServer().start(); HttpDeliveryClientHealthProvider clientHealthProvider = new HttpDeliveryClientHealthProvider( instanceConfig.getInstanceKey(), HttpRequestHelperUtils.buildRequestHelper(false, false, null, instanceConfig.getRoutesHost(), instanceConfig.getRoutesPort()), instanceConfig.getConnectionsHealth(), 5_000, 100); TenantRoutingProvider tenantRoutingProvider = deployable.getTenantRoutingProvider(); TenantsServiceConnectionDescriptorProvider syncDescriptorProvider = tenantRoutingProvider .getConnections(instanceConfig.getServiceName(), "main", 10_000); // TODO config TenantRoutingHttpClientInitializer<String> tenantRoutingHttpClientInitializer = deployable .getTenantRoutingHttpClientInitializer(); TenantAwareHttpClient<String> amzaClient = tenantRoutingHttpClientInitializer .builder(deployable.getTenantRoutingProvider().getConnections("amza", "main", 10_000), // TODO config clientHealthProvider) .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).socketTimeoutInMillis(60_000).build(); // TODO expose to conf deployable.addHealthCheck(new TenantAwareHttpClientHealthCheck("amzaClient", amzaClient)); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); AmzaSyncConfig syncConfig = deployable.config(AmzaSyncConfig.class); TailAtScaleStrategy tailAtScaleStrategy = new TailAtScaleStrategy( deployable.newBoundedExecutor(1024, "tas"), 100, // TODO config 95, // TODO config 1000 // TODO config ); AmzaInterner amzaInterner = new AmzaInterner(); AmzaClientProvider<HttpClient, HttpClientException> amzaClientProvider = new AmzaClientProvider<>( new HttpPartitionClientFactory(), new HttpPartitionHostsProvider(amzaClient, tailAtScaleStrategy, mapper), new RingHostHttpClientProvider(amzaClient), deployable.newBoundedExecutor(syncConfig.getAmzaCallerThreadPoolSize(), "amza-client"), syncConfig.getAmzaAwaitLeaderElectionForNMillis(), -1, -1); TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl( new ConstantWriterIdProvider(instanceConfig.getInstanceName()), new SnowflakeIdPacker(), new JiveEpochTimestampProvider()); AmzaClientAquariumProvider amzaClientAquariumProvider = new AmzaClientAquariumProvider( new AquariumStats(), instanceConfig.getServiceName(), amzaClientProvider, orderIdProvider, new Member(instanceConfig.getInstanceKey().getBytes(StandardCharsets.UTF_8)), count -> { ConnectionDescriptors descriptors = syncDescriptorProvider.getConnections(""); int ringSize = descriptors.getConnectionDescriptors().size(); return count > ringSize / 2; }, () -> { Set<Member> members = Sets.newHashSet(); ConnectionDescriptors descriptors = syncDescriptorProvider.getConnections(""); for (ConnectionDescriptor connectionDescriptor : descriptors.getConnectionDescriptors()) { members.add(new Member(connectionDescriptor.getInstanceDescriptor().instanceKey .getBytes(StandardCharsets.UTF_8))); } return members; }, 128, //TODO config 128, //TODO config 5_000L, //TODO config 100L, //TODO config 60_000L, //TODO config 10_000L, //TODO config Executors.newSingleThreadExecutor(), 100L, //TODO config 1_000L, //TODO config 10_000L, //TODO config syncConfig.getAquariumUseSolutionLog()); ObjectMapper miruSyncMapper = new ObjectMapper(); miruSyncMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); miruSyncMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); AmzaMarshaller<String> stringMarshaller = new AmzaMarshaller<String>() { @Override public String fromBytes(byte[] bytes) throws Exception { return new String(bytes, StandardCharsets.UTF_8); } @Override public byte[] toBytes(String value) throws Exception { return value == null ? null : value.getBytes(StandardCharsets.UTF_8); } }; AmzaMarshaller<AmzaSyncSenderConfig> amzaSyncSenderConfigMarshaller = new AmzaMarshaller<AmzaSyncSenderConfig>() { @Override public AmzaSyncSenderConfig fromBytes(byte[] bytes) throws Exception { return mapper.readValue(bytes, AmzaSyncSenderConfig.class); } @Override public byte[] toBytes(AmzaSyncSenderConfig value) throws Exception { return mapper.writeValueAsBytes(value); } }; AmzaSyncSenderMap senderConfigStorage = new AmzaSyncSenderMap(amzaClientProvider, "amza-sync-sender-config", new PartitionProperties(Durability.fsync_async, 0, 0, 0, 0, 0, 0, 0, 0, false, Consistency.leader_quorum, true, true, false, RowType.snappy_primary, "lab", -1, null, -1, -1), stringMarshaller, amzaSyncSenderConfigMarshaller); AmzaMarshaller<AmzaSyncPartitionTuple> tupleMarshaller = new AmzaMarshaller<AmzaSyncPartitionTuple>() { @Override public AmzaSyncPartitionTuple fromBytes(byte[] bytes) throws Exception { return AmzaSyncPartitionTuple.fromBytes(bytes, 0, amzaInterner); } @Override public byte[] toBytes(AmzaSyncPartitionTuple value) throws Exception { return AmzaSyncPartitionTuple.toBytes(value); } }; AmzaMarshaller<AmzaSyncPartitionConfig> partitionConfigMarshaller = new AmzaMarshaller<AmzaSyncPartitionConfig>() { @Override public AmzaSyncPartitionConfig fromBytes(byte[] bytes) throws Exception { return mapper.readValue(bytes, AmzaSyncPartitionConfig.class); } @Override public byte[] toBytes(AmzaSyncPartitionConfig value) throws Exception { return mapper.writeValueAsBytes(value); } }; AmzaSyncPartitionConfigStorage syncPartitionConfigStorage = new AmzaSyncPartitionConfigStorage( amzaClientProvider, "amza-sync-partitions-config-", new PartitionProperties(Durability.fsync_async, 0, 0, 0, 0, 0, 0, 0, 0, false, Consistency.leader_quorum, true, true, false, RowType.snappy_primary, "lab", -1, null, -1, -1), tupleMarshaller, partitionConfigMarshaller); AmzaSyncStats stats = new AmzaSyncStats(); AmzaSyncReceiver syncReceiver = new AmzaSyncReceiver(amzaClientProvider, syncConfig.getSyncReceiverUseSolutionLog()); AmzaSyncSenders syncSenders = null; if (syncConfig.getSyncSenderEnabled()) { ScheduledExecutorService executorService = Executors .newScheduledThreadPool(syncConfig.getSyncSendersThreadCount()); syncSenders = new AmzaSyncSenders(stats, syncConfig, syncReceiver, executorService, amzaClientProvider, amzaClientAquariumProvider, amzaInterner, mapper, orderIdProvider, senderConfigStorage, syncPartitionConfigStorage, 30_000); // TODO config } amzaClientAquariumProvider.start(); if (syncSenders != null) { syncSenders.start(); } SoyRendererConfig rendererConfig = deployable.config(SoyRendererConfig.class); File staticResourceDir = new File(System.getProperty("user.dir")); System.out.println("Static resources rooted at " + staticResourceDir.getAbsolutePath()); Resource sourceTree = new Resource(staticResourceDir) .addResourcePath(rendererConfig.getPathToStaticResources()).setDirectoryListingAllowed(false) .setContext("/ui/static"); deployable.addResource(sourceTree); SoyRenderer renderer = new SoyRendererInitializer().initialize(rendererConfig); AmzaSyncUIService amzaSyncUIService = new AmzaSyncUIServiceInitializer().initialize(renderer, syncSenders, stats, syncConfig.getSyncSenderEnabled(), syncConfig.getSyncReceiverEnabled(), mapper); deployable.addEndpoints(LoadBalancerHealthCheckEndpoints.class); deployable.addNoAuth("/health/check"); if (instanceConfig.getMainServiceAuthEnabled()) { if (syncConfig.getSyncReceiverEnabled()) { AmzaSyncOAuthValidatorConfig oAuthValidatorConfig = deployable .config(AmzaSyncOAuthValidatorConfig.class); AuthValidator<OAuth1Signature, OAuth1Request> syncOAuthValidator = new AmzaSyncOAuthValidatorInitializer() .initialize(oAuthValidatorConfig); deployable.addCustomOAuth(syncOAuthValidator, "/api/*"); } deployable.addRouteOAuth("/amza/*", "/api/*"); deployable.addSessionAuth("/ui/*", "/amza/*", "/api/*"); } else { deployable.addNoAuth("/amza/*", "/api/*"); deployable.addSessionAuth("/ui/*"); } deployable.addEndpoints(AmzaSyncEndpoints.class); deployable.addInjectables(AmzaInterner.class, amzaInterner); if (syncSenders != null) { deployable.addInjectables(AmzaSyncSenders.class, syncSenders); } deployable.addEndpoints(AmzaSyncUIEndpoints.class); deployable.addInjectables(AmzaSyncUIService.class, amzaSyncUIService); if (syncConfig.getSyncReceiverEnabled()) { deployable.addEndpoints(AmzaSyncApiEndpoints.class); deployable.addInjectables(AmzaSyncReceiver.class, syncReceiver); } deployable.addInjectables(ObjectMapper.class, mapper); deployable.addInjectables(AmzaSyncSenderMap.class, senderConfigStorage); deployable.addInjectables(AmzaSyncPartitionConfigStorage.class, syncPartitionConfigStorage); deployable.buildServer().start(); clientHealthProvider.start(); serviceStartupHealthCheck.success(); } catch (Throwable t) { serviceStartupHealthCheck.info("Encountered the following failure during startup.", t); } }
From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java
private HttpResponse executeWithTimeout(final HttpMethodBase httpMethod, int timeoutMillis) { client.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false)); ExecutorService service = Executors.newSingleThreadExecutor(); Future<HttpResponse> future = service.submit(new Callable<HttpResponse>() { @Override/*from ww w . j a v a 2 s. co m*/ public HttpResponse call() throws IOException { return execute(httpMethod); } }); try { return future.get(timeoutMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { String uriInfo = ""; try { uriInfo = " for " + httpMethod.getURI(); } catch (Exception ie) { } LOG.warn("Http connection thread was interrupted or has timed out" + uriInfo, e); return new HttpResponse(HttpStatus.SC_REQUEST_TIMEOUT, "Request Timeout", null); } finally { service.shutdownNow(); } }
From source file:mase.conillon.ConillonMasterProblem.java
public static <T> T runWithTimeout(Callable<T> callable, long timeout, TimeUnit timeUnit) throws Exception { final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<T> future = executor.submit(callable); executor.shutdown(); // This does not cancel the already-scheduled task. try {/*from w ww. jav a 2s . co m*/ return future.get(timeout, timeUnit); } catch (InterruptedException | ExecutionException | TimeoutException e) { future.cancel(true); throw e; } }
From source file:com.meltmedia.cadmium.core.git.GitService.java
/** * Initializes war content directory for a Cadmium war. * @param uri The remote Git repository ssh URI. * @param branch The remote branch to checkout. * @param root The shared content root.//from www . ja v a 2 s. c o m * @param warName The name of the war file. * @param historyManager The history manager to log the initialization event. * @return A GitService object the points to the freshly cloned Git repository. * @throws RefNotFoundException * @throws Exception */ public static GitService initializeContentDirectory(String uri, String branch, String root, String warName, HistoryManager historyManager, ConfigManager configManager) throws Exception { initializeBaseDirectoryStructure(root, warName); String warDir = FileSystemManager.getChildDirectoryIfExists(root, warName); Properties configProperties = configManager.getDefaultProperties(); GitLocation gitLocation = new GitLocation(uri, branch, configProperties.getProperty("git.ref.sha")); GitService cloned = initializeRepo(gitLocation, warDir, "git-checkout"); try { String renderedContentDir = initializeSnapshotDirectory(warDir, configProperties, "com.meltmedia.cadmium.lastUpdated", "git-checkout", "renderedContent"); boolean hasExisting = configProperties.containsKey("com.meltmedia.cadmium.lastUpdated") && renderedContentDir != null && renderedContentDir.equals(configProperties.getProperty("com.meltmedia.cadmium.lastUpdated")); if (renderedContentDir != null) { configProperties.setProperty("com.meltmedia.cadmium.lastUpdated", renderedContentDir); } configProperties.setProperty("branch", cloned.getBranchName()); configProperties.setProperty("git.ref.sha", cloned.getCurrentRevision()); configProperties.setProperty("repo", cloned.getRemoteRepository()); if (renderedContentDir != null) { String sourceFilePath = renderedContentDir + File.separator + "MET-INF" + File.separator + "source"; if (sourceFilePath != null && FileSystemManager.canRead(sourceFilePath)) { try { configProperties.setProperty("source", FileSystemManager.getFileContents(sourceFilePath)); } catch (Exception e) { log.warn("Failed to read source file {}", sourceFilePath); } } else if (!configProperties.containsKey("source")) { configProperties.setProperty("source", "{}"); } } else if (!configProperties.containsKey("source")) { configProperties.setProperty("source", "{}"); } configManager.persistDefaultProperties(); ExecutorService pool = null; if (historyManager == null) { pool = Executors.newSingleThreadExecutor(); historyManager = new HistoryManager(warDir, pool); } try { if (historyManager != null && !hasExisting) { historyManager.logEvent(EntryType.CONTENT, new GitLocation(cloned.getRemoteRepository(), cloned.getBranchName(), cloned.getCurrentRevision()), "AUTO", renderedContentDir, "", "Initial content pull.", true, true); } } finally { if (pool != null) { pool.shutdownNow(); } } return cloned; } catch (Throwable e) { cloned.close(); throw new Exception(e); } }
From source file:com.scaleoutsoftware.soss.hserver.hadoop.SubmittedJob.java
public void submit() { ExecutorService async = Executors.newSingleThreadExecutor(); runningJob = async.submit(this); async.shutdown(); }
From source file:com.all.messengine.impl.DefaultMessEngine.java
public DefaultMessEngine() { queue = new LinkedBlockingQueue<Message<?>>(); messageExecutor = Executors.newCachedThreadPool(); engineExecutor = Executors.newSingleThreadExecutor(); listeners = new HashMap<String, List<MessageListener<? extends Message<?>>>>(); responseManager = new ResponseManager(); shuttingDown = new AtomicBoolean(false); }
From source file:mase.conillon.ConillonMasterProblem.java
public static void runWithTimeout(Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception { final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future future = executor.submit(runnable); executor.shutdown(); // This does not cancel the already-scheduled task. try {/*www . ja v a 2s . c om*/ future.get(timeout, timeUnit); } catch (InterruptedException | ExecutionException | TimeoutException e) { future.cancel(true); throw e; } }