List of usage examples for java.lang Thread isAlive
public final native boolean isAlive();
From source file:org.apache.flink.streaming.connectors.kinesis.manualtests.ManualExactlyOnceTest.java
public static void main(String[] args) throws Exception { final ParameterTool pt = ParameterTool.fromArgs(args); LOG.info("Starting exactly once test"); // create a stream for the test: Properties configProps = new Properties(); configProps.setProperty(KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_ACCESSKEYID, pt.getRequired("accessKey")); configProps.setProperty(KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_SECRETKEY, pt.getRequired("secretKey")); AmazonKinesisClient client = new AmazonKinesisClient( AWSUtil.getCredentialsProvider(configProps).getCredentials()); client.setRegion(Region.getRegion(Regions.fromName(pt.getRequired("region")))); final String streamName = "flink-test-" + UUID.randomUUID().toString(); client.createStream(streamName, 1);/*from www .jav a 2 s .c o m*/ // wait until stream has been created DescribeStreamResult status = client.describeStream(streamName); LOG.info("status {}", status); while (!status.getStreamDescription().getStreamStatus().equals("ACTIVE")) { status = client.describeStream(streamName); LOG.info("Status of stream {}", status); Thread.sleep(1000); } final Configuration flinkConfig = new Configuration(); flinkConfig.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, 1); flinkConfig.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, 8); flinkConfig.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 16); flinkConfig.setString(ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_DELAY, "0 s"); ForkableFlinkMiniCluster flink = new ForkableFlinkMiniCluster(flinkConfig, false); flink.start(); final int flinkPort = flink.getLeaderRPCPort(); try { final Tuple1<Throwable> producerException = new Tuple1<>(); Runnable producer = new Runnable() { @Override public void run() { try { StreamExecutionEnvironment see = StreamExecutionEnvironment .createRemoteEnvironment("localhost", flinkPort, flinkConfig); see.setParallelism(2); // start data generator DataStream<String> simpleStringStream = see .addSource(new EventsGenerator(TOTAL_EVENT_COUNT)).setParallelism(1); Properties producerProps = new Properties(); producerProps.setProperty( KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_ACCESSKEYID, pt.getRequired("accessKey")); producerProps.setProperty( KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_SECRETKEY, pt.getRequired("secretKey")); producerProps.setProperty(KinesisConfigConstants.CONFIG_AWS_REGION, pt.getRequired("region")); FlinkKinesisProducer<String> kinesis = new FlinkKinesisProducer<>(new SimpleStringSchema(), producerProps); kinesis.setFailOnError(true); kinesis.setDefaultStream(streamName); kinesis.setDefaultPartition("0"); simpleStringStream.addSink(kinesis); LOG.info("Starting producing topology"); see.execute("Producing topology"); LOG.info("Producing topo finished"); } catch (Exception e) { LOG.warn("Error while running producing topology", e); producerException.f0 = e; } } }; Thread producerThread = new Thread(producer); producerThread.start(); final Tuple1<Throwable> consumerException = new Tuple1<>(); Runnable consumer = new Runnable() { @Override public void run() { try { StreamExecutionEnvironment see = StreamExecutionEnvironment .createRemoteEnvironment("localhost", flinkPort, flinkConfig); see.setParallelism(2); see.enableCheckpointing(500); // we restart two times see.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, 500L)); // consuming topology Properties consumerProps = new Properties(); consumerProps.setProperty( KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_ACCESSKEYID, pt.getRequired("accessKey")); consumerProps.setProperty( KinesisConfigConstants.CONFIG_AWS_CREDENTIALS_PROVIDER_BASIC_SECRETKEY, pt.getRequired("secretKey")); consumerProps.setProperty(KinesisConfigConstants.CONFIG_AWS_REGION, pt.getRequired("region")); // start reading from beginning consumerProps.setProperty(KinesisConfigConstants.CONFIG_STREAM_INIT_POSITION_TYPE, InitialPosition.TRIM_HORIZON.name()); DataStream<String> consuming = see.addSource( new FlinkKinesisConsumer<>(streamName, new SimpleStringSchema(), consumerProps)); consuming.flatMap(new RichFlatMapFunction<String, String>() { int count = 0; @Override public void flatMap(String value, Collector<String> out) throws Exception { if (count++ >= 200 && getRuntimeContext().getAttemptNumber() == 0) { throw new RuntimeException("Artificial failure. Restart pls"); } out.collect(value); } }).flatMap(new ExactlyOnceValidatingMapper()); // validate consumed records for correctness LOG.info("Starting consuming topology"); tryExecute(see, "Consuming topo"); LOG.info("Consuming topo finished"); } catch (Exception e) { LOG.warn("Error while running consuming topology", e); consumerException.f0 = e; } } }; Thread consumerThread = new Thread(consumer); consumerThread.start(); long deadline = System.currentTimeMillis() + (1000 * 2 * 60); // wait at most for two minutes while (consumerThread.isAlive() || producerThread.isAlive()) { Thread.sleep(1000); if (System.currentTimeMillis() >= deadline) { LOG.warn("Deadline passed"); break; // enough waiting } } if (producerThread.isAlive()) { producerThread.interrupt(); } if (consumerThread.isAlive()) { consumerThread.interrupt(); } if (producerException.f0 != null) { throw new RuntimeException("Producer failed", producerException.f0); } if (consumerException.f0 != null) { throw new RuntimeException("Consumer failed", consumerException.f0); } LOG.info("+++ TEST passed! +++"); } finally { client.deleteStream(streamName); client.shutdown(); // stopping flink flink.stop(); } }
From source file:no.eris.applet.AppletViewer.java
public static void main(String[] av) { if (av.length < 2) { throw new IllegalArgumentException("USAGE: AppletViewer configFileAttributes configFileParams"); }/*from w w w . j a v a2s. c om*/ Thread t = AppletViewer.build(av[0], av[1]).run(true); if (t != null) { while (t.isAlive()) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(System.err); } } } }
From source file:org.sourcepit.docker.watcher.Main.java
public static void main(String[] args) throws IOException { final HttpClientFactory clientFactory = new HttpClientFactory() { @Override//from w ww . jav a 2 s .c o m public CloseableHttpClient createHttpClient() { return HttpClients.createDefault(); } }; final String dockerDaemonUri = "http://192.168.56.101:2375"; final String consulAgentUri = "http://192.168.56.101:8500"; final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>(); final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(), consulAgentUri); final Thread containerStateDispatcher = new Thread("Consul Forwarder") { @Override public void run() { while (true) { try { consulForwarder.forward(queue.take()); } catch (InterruptedException e) { break; } catch (Exception e) { LOG.error("Error while forwarding Docker container state to Consul.", e); } } } }; containerStateDispatcher.start(); final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) { @Override protected void handle(List<JsonObject> containerState) { queue.add(containerState); } }; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { watcher.stop(); while (containerStateDispatcher.isAlive()) { containerStateDispatcher.interrupt(); try { Thread.sleep(100L); } catch (InterruptedException e) { } } } }); watcher.start(); }
From source file:Snippet151.java
public static void main(String[] args) { final Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL); table.addListener(SWT.SetData, new Listener() { public void handleEvent(Event e) { TableItem item = (TableItem) e.item; int index = table.indexOf(item); item.setText("Item " + data[index]); }/*from w w w. j a va 2 s .c o m*/ }); Thread thread = new Thread() { public void run() { int count = 0; Random random = new Random(); while (count++ < 500) { if (table.isDisposed()) return; // add 10 random numbers to array and sort int grow = 10; int[] newData = new int[data.length + grow]; System.arraycopy(data, 0, newData, 0, data.length); int index = data.length; data = newData; for (int j = 0; j < grow; j++) { data[index++] = random.nextInt(); } Arrays.sort(data); display.syncExec(new Runnable() { public void run() { if (table.isDisposed()) return; table.setItemCount(data.length); table.clearAll(); } }); try { Thread.sleep(500); } catch (Throwable t) { } } } }; thread.start(); shell.open(); while (!shell.isDisposed() || thread.isAlive()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:org.apache.flink.streaming.connectors.kinesis.manualtests.ManualExactlyOnceWithStreamReshardingTest.java
public static void main(String[] args) throws Exception { final ParameterTool pt = ParameterTool.fromArgs(args); LOG.info("Starting exactly once with stream resharding test"); final String streamName = "flink-test-" + UUID.randomUUID().toString(); final String accessKey = pt.getRequired("accessKey"); final String secretKey = pt.getRequired("secretKey"); final String region = pt.getRequired("region"); final Properties configProps = new Properties(); configProps.setProperty(ConsumerConfigConstants.AWS_ACCESS_KEY_ID, accessKey); configProps.setProperty(ConsumerConfigConstants.AWS_SECRET_ACCESS_KEY, secretKey); configProps.setProperty(ConsumerConfigConstants.AWS_REGION, region); configProps.setProperty(ConsumerConfigConstants.SHARD_DISCOVERY_INTERVAL_MILLIS, "0"); final AmazonKinesisClient client = AWSUtil.createKinesisClient(configProps); // the stream is first created with 1 shard client.createStream(streamName, 1);// ww w. ja v a 2 s . c om // wait until stream has been created DescribeStreamResult status = client.describeStream(streamName); LOG.info("status {}", status); while (!status.getStreamDescription().getStreamStatus().equals("ACTIVE")) { status = client.describeStream(streamName); LOG.info("Status of stream {}", status); Thread.sleep(1000); } final Configuration flinkConfig = new Configuration(); flinkConfig.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, 1); flinkConfig.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, 8); flinkConfig.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 16); flinkConfig.setString(ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_DELAY, "0 s"); LocalFlinkMiniCluster flink = new LocalFlinkMiniCluster(flinkConfig, false); flink.start(); final int flinkPort = flink.getLeaderRPCPort(); try { // we have to use a manual generator here instead of the FlinkKinesisProducer // because the FlinkKinesisProducer currently has a problem where records will be resent to a shard // when resharding happens; this affects the consumer exactly-once validation test and will never pass final AtomicReference<Throwable> producerError = new AtomicReference<>(); Runnable manualGenerate = new Runnable() { @Override public void run() { AmazonKinesisClient client = AWSUtil.createKinesisClient(configProps); int count = 0; final int batchSize = 30; while (true) { try { Thread.sleep(10); Set<PutRecordsRequestEntry> batch = new HashSet<>(); for (int i = count; i < count + batchSize; i++) { if (i >= TOTAL_EVENT_COUNT) { break; } batch.add(new PutRecordsRequestEntry() .withData( ByteBuffer.wrap(((i) + "-" + RandomStringUtils.randomAlphabetic(12)) .getBytes(ConfigConstants.DEFAULT_CHARSET))) .withPartitionKey(UUID.randomUUID().toString())); } count += batchSize; PutRecordsResult result = client.putRecords( new PutRecordsRequest().withStreamName(streamName).withRecords(batch)); // the putRecords() operation may have failing records; to keep this test simple // instead of retrying on failed records, we simply pass on a runtime exception // and let this test fail if (result.getFailedRecordCount() > 0) { producerError.set(new RuntimeException( "The producer has failed records in one of the put batch attempts.")); break; } if (count >= TOTAL_EVENT_COUNT) { break; } } catch (Exception e) { producerError.set(e); } } } }; Thread producerThread = new Thread(manualGenerate); producerThread.start(); final AtomicReference<Throwable> consumerError = new AtomicReference<>(); Thread consumerThread = ExactlyOnceValidatingConsumerThread.create(TOTAL_EVENT_COUNT, 10000, 2, 500, 500, accessKey, secretKey, region, streamName, consumerError, flinkPort, flinkConfig); consumerThread.start(); // reshard the Kinesis stream while the producer / and consumers are running Runnable splitShard = new Runnable() { @Override public void run() { try { // first, split shard in the middle of the hash range Thread.sleep(5000); LOG.info("Splitting shard ..."); client.splitShard(streamName, KinesisShardIdGenerator.generateFromShardOrder(0), "170141183460469231731687303715884105727"); // wait until the split shard operation finishes updating ... DescribeStreamResult status; Random rand = new Random(); do { status = null; while (status == null) { // retry until we get status try { status = client.describeStream(streamName); } catch (LimitExceededException lee) { LOG.warn("LimitExceededException while describing stream ... retrying ..."); Thread.sleep(rand.nextInt(1200)); } } } while (!status.getStreamDescription().getStreamStatus().equals("ACTIVE")); // then merge again Thread.sleep(7000); LOG.info("Merging shards ..."); client.mergeShards(streamName, KinesisShardIdGenerator.generateFromShardOrder(1), KinesisShardIdGenerator.generateFromShardOrder(2)); } catch (InterruptedException iex) { // } } }; Thread splitShardThread = new Thread(splitShard); splitShardThread.start(); boolean deadlinePassed = false; long deadline = System.currentTimeMillis() + (1000 * 5 * 60); // wait at most for five minutes // wait until both producer and consumer finishes, or an unexpected error is thrown while ((consumerThread.isAlive() || producerThread.isAlive()) && (producerError.get() == null && consumerError.get() == null)) { Thread.sleep(1000); if (System.currentTimeMillis() >= deadline) { LOG.warn("Deadline passed"); deadlinePassed = true; break; // enough waiting } } if (producerThread.isAlive()) { producerThread.interrupt(); } if (consumerThread.isAlive()) { consumerThread.interrupt(); } if (producerError.get() != null) { LOG.info("+++ TEST failed! +++"); throw new RuntimeException("Producer failed", producerError.get()); } if (consumerError.get() != null) { LOG.info("+++ TEST failed! +++"); throw new RuntimeException("Consumer failed", consumerError.get()); } if (!deadlinePassed) { LOG.info("+++ TEST passed! +++"); } else { LOG.info("+++ TEST failed! +++"); } } finally { client.deleteStream(streamName); client.shutdown(); // stopping flink flink.stop(); } }
From source file:MyThread.java
static void showThreadStatus(Thread thrd) { System.out.println(thrd.getName() + " Alive:" + thrd.isAlive() + " State:" + thrd.getState()); }
From source file:Main.java
/** * Attempt to join the thread specified safely. * /* w w w .j a v a 2s . c o m*/ * @param thread the thread to join, not null * @param timeoutMillis the timeout in milliseconds * @return true if the join succeeded, false if a timeout occurred */ public static boolean safeJoin(Thread thread, long timeoutMillis) { if (!thread.isAlive()) { return true; } try { thread.join(timeoutMillis); } catch (InterruptedException e) { // clear the interrupted state Thread.interrupted(); } return !thread.isAlive(); }
From source file:Main.java
/** * Determines whether the specified Thread is alive, guarding against null Object references. * <p/>//from w w w .j a va2s . com * @param thread the Thread to determine for aliveness. * @return a boolean value indicating whether the specified Thread is alive. Will return false if the Thread Object * references is null. * @see java.lang.Thread#isAlive() */ public static boolean isAlive(final Thread thread) { return (thread != null && thread.isAlive()); }
From source file:Main.java
public static void joinUninterruptibly(Thread t) { boolean interrupted = false; while (t.isAlive()) { try {//from w w w . j av a 2 s . c o m t.join(); } catch (InterruptedException e) { interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } }
From source file:Main.java
/** * For testing only - prevent the tests to exit until all thread finished *///w ww . java 2 s. c o m public static void waitForBackgroundThreads() { Enumeration e = threads.elements(); while (e.hasMoreElements()) { Thread thread = (Thread) e.nextElement(); if (thread.isAlive()) { try { thread.join(); } catch (InterruptedException ignore) { ignore.printStackTrace(); } } } }