/** Run the test for the queue parameter. */ public static SynchronizedQueueResult testQueue(QueueAdapter<Integer> queue) { try { mQueue = queue; // Please make sure to keep all the "TODO" comments in the // code below to make it easy for peer reviewers to find // them. // TODO - you fill in here to replace the null // initialization below to create two Java Threads, one // that's passed the producerRunnable and the other that's // passed the consumerRunnable. Thread consumer = new Thread(consumerRunnable); Thread producer = new Thread(producerRunnable); // TODO - you fill in here to start the threads. More // interesting results will occur if you start the // consumer first. producer.start(); consumer.start(); // Give the Threads a chance to run before interrupting // them. Thread.sleep(100); // TODO - you fill in here to interrupt the threads. producer.interrupt(); consumer.interrupt(); // TODO - you fill in here to wait for the threads to // exit. consumer.join(); producer.join(); ; // Do some sanity checking to see if the Threads work as // expected. if (consumer == null || producer == null) return SynchronizedQueueResult.THREADS_NEVER_CREATED; else if (consumer.isAlive() || producer.isAlive()) return SynchronizedQueueResult.JOIN_NEVER_CALLED; else if (mConsumerCounter == 0 || mProducerCounter == 0) return SynchronizedQueueResult.THREADS_NEVER_RAN; else if (mConsumerCounter == mMaxIterations || mProducerCounter == mMaxIterations) return SynchronizedQueueResult.THREADS_NEVER_INTERUPTED; else if (mConsumerCounter == FAILURE_OCCURRED || mProducerCounter == FAILURE_OCCURRED) return SynchronizedQueueResult.THREADS_THREW_EXCEPTION; else if (mConsumerCounter == TIMEOUT_OCCURRED || mProducerCounter == TIMEOUT_OCCURRED) return SynchronizedQueueResult.THREADS_TIMEDOUT; else return SynchronizedQueueResult.RAN_PROPERLY; } catch (Exception e) { return SynchronizedQueueResult.TESTING_LOGIC_THREW_EXCEPTION; } }
/** * Start this server. If we manage an own HttpServer, then the HttpServer will be started as well. */ public void start() { // URL as configured takes precedence String configUrl = NetworkUtil.replaceExpression(config.getJolokiaConfig().get(ConfigKey.DISCOVERY_AGENT_URL)); jolokiaHttpHandler.start( lazy, configUrl != null ? configUrl : url, config.getAuthenticator() != null); if (httpServer != null) { // Starting our own server in an own thread group with a fixed name // so that the cleanup thread can recognize it. ThreadGroup threadGroup = new ThreadGroup("jolokia"); threadGroup.setDaemon(false); Thread starterThread = new Thread( threadGroup, new Runnable() { @Override public void run() { httpServer.start(); } }); starterThread.start(); cleaner = new CleanupThread(httpServer, threadGroup); cleaner.start(); } }
public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); CompletionService<String> service = new ExecutorCompletionService<String>(executor); ReportRequest faceRequest = new ReportRequest("Face", service); ReportRequest onlineRequest = new ReportRequest("Online", service); Thread faceThread = new Thread(faceRequest); Thread onlineThread = new Thread(onlineRequest); ReportProcessor processor = new ReportProcessor(service); Thread processThread = new Thread(processor); System.out.println("Main: Starting the Threads"); faceThread.start(); onlineThread.start(); processThread.start(); try { System.out.println("Main: Waiting for the report generators."); faceThread.join(); onlineThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main: Shutting down the executor."); executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } processor.setEnd(true); System.out.println("Main: Ends"); }
public void run() throws Exception { for (Thread t : searcherThreads) { t.start(); } for (Thread t : writerThreads) { t.start(); } barrier1.await(); Refresher refresher = new Refresher(); scheduledExecutorService.scheduleWithFixedDelay( refresher, refreshSchedule.millis(), refreshSchedule.millis(), TimeUnit.MILLISECONDS); Flusher flusher = new Flusher(); scheduledExecutorService.scheduleWithFixedDelay( flusher, flushSchedule.millis(), flushSchedule.millis(), TimeUnit.MILLISECONDS); StopWatch stopWatch = new StopWatch(); stopWatch.start(); barrier2.await(); latch.await(); stopWatch.stop(); System.out.println("Summary"); System.out.println( " -- Readers [" + searcherThreads.length + "] with [" + searcherIterations + "] iterations"); System.out.println( " -- Writers [" + writerThreads.length + "] with [" + writerIterations + "] iterations"); System.out.println(" -- Took: " + stopWatch.totalTime()); System.out.println( " -- Refresh [" + refresher.id + "] took: " + refresher.stopWatch.totalTime()); System.out.println(" -- Flush [" + flusher.id + "] took: " + flusher.stopWatch.totalTime()); System.out.println(" -- Store size " + store.estimateSize()); scheduledExecutorService.shutdown(); engine.refresh(new Engine.Refresh(true)); stopWatch = new StopWatch(); stopWatch.start(); Engine.Searcher searcher = engine.searcher(); TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), idGenerator.get() + 1); stopWatch.stop(); System.out.println( " -- Indexed [" + idGenerator.get() + "] docs, found [" + topDocs.totalHits + "] hits, took " + stopWatch.totalTime()); searcher.release(); }
public static void main(String[] args) throws Exception { int counter = 0; while (true) { Thread outThread = null; Thread errThread = null; try { // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange // *** start slave ServerSocket commSocket = new ServerSocket(0); int commPort = commSocket.getLocalPort(); System.out.println("commPort = " + commPort); // org.pitest.mutationtest.execute.MutationTestProcess#start // - org.pitest.util.CommunicationThread#start FutureTask<Integer> commFuture = createFuture(commSocket); // - org.pitest.util.WrappingProcess#start // - org.pitest.util.JavaProcess#launch Process slaveProcess = startSlaveProcess(commPort); outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout"); errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr"); outThread.start(); errThread.start(); // *** wait for slave to die // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie // - org.pitest.util.CommunicationThread#waitToFinish System.out.println("waitToFinish"); Integer controlReturned = commFuture.get(); System.out.println("controlReturned = " + controlReturned); // NOTE: the following won't get called if commFuture.get() fails! // - org.pitest.util.JavaProcess#destroy outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop slaveProcess.destroy(); } catch (Exception e) { e.printStackTrace(System.out); } // test: the threads should exit eventually outThread.join(); errThread.join(); counter++; System.out.println("try " + counter + ": stdout and stderr threads exited normally"); } }
@Override public void subscribe(final Subscriber<? super String> observer) { observer.onSubscribe(EmptySubscription.INSTANCE); t = new Thread( new Runnable() { @Override public void run() { for (String s : valuesToReturn) { if (s == null) { System.out.println("throwing exception"); try { Thread.sleep(100); } catch (Throwable e) { } observer.onError(new NullPointerException()); return; } else { observer.onNext(s); } } System.out.println("subscription complete"); observer.onComplete(); } }); t.start(); }
public static void main(String[] args) { CustomScheduler scheduler = new CustomScheduler(); Thread t = new Thread(scheduler); t.start(); Future<String> result = scheduler.enqueue( new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(1500); int i = 1; if (1 == i) { throw new RuntimeException("test"); } return "ok"; } }); try { System.out.println(result.get()); ; } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
public SegmentCacheManager(MondrianServer server) { this.server = server; ACTOR = new Actor(); thread = new Thread(ACTOR, "mondrian.rolap.agg.SegmentCacheManager$ACTOR"); thread.setDaemon(true); thread.start(); // Create the index registry. this.indexRegistry = new SegmentCacheIndexRegistry(); // Add a local cache, if needed. if (!MondrianProperties.instance().DisableCaching.get()) { final MemorySegmentCache cache = new MemorySegmentCache(); segmentCacheWorkers.add(new SegmentCacheWorker(cache, thread)); } // Add an external cache, if configured. final List<SegmentCache> externalCache = SegmentCacheWorker.initCache(); for (SegmentCache cache : externalCache) { // Create a worker for this external cache segmentCacheWorkers.add(new SegmentCacheWorker(cache, thread)); // Hook up a listener so it can update // the segment index. cache.addListener(new AsyncCacheListener(this, server)); } compositeCache = new CompositeSegmentCache(segmentCacheWorkers); }
// Do some simple concurrent testing public void testConcurrentSimple() throws InterruptedException { final NonBlockingIdentityHashMap<String, String> nbhm = new NonBlockingIdentityHashMap<String, String>(); final String[] keys = new String[20000]; for (int i = 0; i < 20000; i++) keys[i] = "k" + i; // In 2 threads, add & remove even & odd elements concurrently Thread t1 = new Thread() { public void run() { work_helper(nbhm, "T1", 1, keys); } }; t1.start(); work_helper(nbhm, "T0", 0, keys); t1.join(); // In the end, all members should be removed StringBuffer buf = new StringBuffer(); buf.append("Should be emptyset but has these elements: {"); boolean found = false; for (String x : nbhm.keySet()) { buf.append(" ").append(x); found = true; } if (found) System.out.println(buf + " }"); assertThat("concurrent size=0", nbhm.size(), is(0)); for (String x : nbhm.keySet()) { assertTrue("No elements so never get here", false); } }
private static void testPotato( Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable { try { System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName()); final int iterations = 100000; final List<Integer> list = (List<Integer>) argClazz.newInstance(); final Integer one = Integer.valueOf(1); final List<Integer> oneElementList = Collections.singletonList(one); final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class); final Thread t = new CheckedThread() { public void realRun() { for (int i = 0; i < iterations; i++) { list.add(one); list.remove(one); } } }; t.setDaemon(true); t.start(); for (int i = 0; i < iterations; i++) { Collection<?> coll = constr.newInstance(list); Object[] elts = coll.toArray(); check(elts.length == 0 || (elts.length == 1 && elts[0] == one)); } } catch (Throwable t) { unexpected(t); } }
/** Test for issue #39 */ @Test public void testIsMapKeyLocked() throws InterruptedException { HazelcastClient hClient = getHazelcastClient(); final IMap map = hClient.getMap("testIsMapKeyLocked"); assertFalse(map.isLocked("key")); map.lock("key"); assertTrue(map.isLocked("key")); final CountDownLatch latch = new CountDownLatch(1); Thread thread = new Thread( new Runnable() { public void run() { assertTrue(map.isLocked("key")); try { while (map.isLocked("key")) { Thread.sleep(100); } } catch (InterruptedException e) { throw new RuntimeException(e); } latch.countDown(); } }); thread.start(); Thread.sleep(100); map.unlock("key"); assertTrue(latch.await(3, TimeUnit.SECONDS)); }
public Integer call() { count = 0; try { File[] files = directory.listFiles(); ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>(); for (File file : files) if (file.isDirectory()) { MatchCounter counter = new MatchCounter(file, keyword); FutureTask<Integer> task = new FutureTask<Integer>(counter); results.add(task); Thread t = new Thread(task); t.start(); } else { if (search(file)) count++; } for (Future<Integer> result : results) try { count += result.get(); } catch (ExecutionException e) { e.printStackTrace(); } } catch (InterruptedException e) { } return count; }
/* (non-Javadoc) * @see net.xeoh.plugins.remotediscovery.impl.v4.probes.AbstractProbe#startup() */ @Override public void startup() { super.startup(); final Thread thread = new Thread( new Runnable() { @Override public void run() { backgroundInit(); } }); thread.setDaemon(true); thread.start(); this.timer = new Timer(); this.timer.schedule( new TimerTask() { @Override public void run() { discoverThread(); } }, 0, 260); }
public AnimationFrame() { ArrayComponent comp = new ArrayComponent(); add(comp, BorderLayout.CENTER); final Sorter sorter = new Sorter(comp); JButton runButton = new JButton("Run"); runButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { sorter.setRun(); } }); JButton stepButton = new JButton("Step"); stepButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { sorter.setStep(); } }); JPanel buttons = new JPanel(); buttons.add(runButton); buttons.add(stepButton); add(buttons, BorderLayout.NORTH); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); Thread t = new Thread(sorter); t.start(); }
@Test public void testBolockingQueue() { final BlockingQueue<Object> blockingQ = new ArrayBlockingQueue<Object>(10); Thread thread = new Thread("consumer thread") { public void run() { System.out.println(1); for (int i = 0; i < 5; i++) { // Object object = blockingQ.poll(); // 杯具,不等待就会直接返回 Object object = null; try { object = blockingQ.take(); System.out.println(i); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(object); } } }; thread.start(); try { blockingQ.put("111"); } catch (InterruptedException e) { e.printStackTrace(); } }
@Test public void testThreadInterupt() { Thread thread = new Thread("interupt") { public void run() { for (; ; ) { try { foo(); System.out.println(1); } catch (InterruptedException e) { e.printStackTrace(); break; } catch (Exception e) { e.printStackTrace(); } // if(Thread.interrupted()){ // System.out.println("iiiiiii"); // break; // } } } }; thread.start(); System.out.println(thread.getName()); }
protected void startRunner() { running = true; runner = timer_thread_factory != null ? timer_thread_factory.newThread(this, "Timer runner") : new Thread(this, "Timer runner"); runner.start(); }
@Override protected void setUp() throws Exception { tmp = IO.getFile("generated/tmp"); tmp.mkdirs(); IO.copy(IO.getFile("testdata/ws"), tmp); workspace = Workspace.getWorkspace(tmp); workspace.refresh(); InfoRepository repo = workspace.getPlugin(InfoRepository.class); t1 = create("bsn-1", new Version(1, 0, 0)); t2 = create("bsn-2", new Version(1, 0, 0)); repo.put(new FileInputStream(t1), null); repo.put(new FileInputStream(t2), null); t1 = repo.get("bsn-1", new Version(1, 0, 0), null); t2 = repo.get("bsn-2", new Version(1, 0, 0), null); repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null); workspace.getPlugins().add(repo); File storage = IO.getFile("generated/storage-1"); storage.mkdirs(); configuration = new HashMap<String, Object>(); configuration.put( Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath()); configuration.put( Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2"); framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration); framework.init(); framework.start(); context = framework.getBundleContext(); location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString(); agent = context.installBundle(location); agent.start(); thread = new Thread() { @Override public void run() { try { Main.main( new String[] { "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et" }); } catch (Exception e) { e.printStackTrace(); } } }; thread.setDaemon(true); thread.start(); super.setUp(); }
public static void main(String[] args) throws Exception { for (int i = 0; i < 10; i++) { Thread daemon = new Thread(new SimpleDaemons()); daemon.setDaemon(true); // Must call before start() daemon.start(); } print("All daemons started"); TimeUnit.MILLISECONDS.sleep(175); }
/** * Testing threads thoroughly seems to be a lot of fun, I am not sure yet how to properly do that. * This test tests priority order and total sum received is equal to total sum sent. It also * simulates clients random hanging. */ @Test public void testReceiveData() { DecorateCheckOrderAndCountSumMarshaller sumAppender = new DecorateCheckOrderAndCountSumMarshaller(); QueueWorker worker = new QueueWorker(sumAppender); Thread workerThread = new Thread(worker); // run 20 clients, 10.000 items will be generated per client as defined in // src/test/properties/app.properties for (int i = 0; i < 20; i++) { Runnable clientHangSimulator = null; if (i % 5 == 0) { // simulate occasional client hang for four of the total twenty clients and check worker is // not biased. clientHangSimulator = () -> { if (ThreadLocalRandom.current().nextInt(1001) % 1000 == 0) { try { Thread.sleep(500L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; } executorService.execute(new DataGeneratorTask(clientHangSimulator)); } workerThread.start(); try { barrier.await(); System.out.println("Fired test"); Thread.sleep(1000); executorService.shutdown(); // runs actually much faster, may need update if item count per client is drastically // increased in app.properties executorService.awaitTermination(2 * 60, TimeUnit.SECONDS); System.out.println("exe service awaited"); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } try { workerThread.join(Long.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } Assert.assertEquals( "Sum generated does not match sum received", sumAppender.getSum(), AppContext.getInstance().getTotalGeneratedAmount()); Assert.assertFalse("Worker didn't exit successfully", workerThread.isAlive()); }
public ContinuousChangesFeed(String dbName, HttpResponse httpResponse) { this.httpResponse = httpResponse; try { reader = new BufferedReader(new InputStreamReader(httpResponse.getContent(), "UTF-8")); thread.setName( String.format( "ektorp-%s-changes-listening-thread-%s", dbName, THREAD_COUNT.getAndIncrement())); thread.start(); } catch (UnsupportedEncodingException e) { throw Exceptions.propagate(e); } }
@Test public void testThread() { Thread thread = new Thread("aaa") { public void run() { System.out.println(this.getName()); } }; thread.setName("bbb"); // thread.setDaemon(true); thread.start(); }
void solve() { Thread tcThread = new Thread(tc); // System.out.println("starting client thread"); tcThread.start(); try { tcThread.join(); } catch (Exception e) { e.printStackTrace(); } // System.out.println("joined client thread"); result = SudokuSolver.solve(tc.testcase); success = SudokuSolver.isLegalSolution(result, tc.testcase); }
public void stackLeakByThread() { while (true) { Thread thread = new Thread( new Runnable() { @Override public void run() { dontStop(); } }); thread.start(); } }
/* * Launches against the agent */ public void testSimpleLauncher() throws Exception { Project project = workspace.getProject("p1"); Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun")); bndrun.setProperty("-runpath", "biz.aQute.remote.launcher"); bndrun.setProperty("-runbundles", "bsn-1,bsn-2"); bndrun.setProperty("-runremote", "test"); final RemoteProjectLauncherPlugin pl = (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher(); pl.prepare(); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger exitCode = new AtomicInteger(-1); List<? extends RunSession> sessions = pl.getRunSessions(); assertEquals(1, sessions.size()); final RunSession session = sessions.get(0); Thread t = new Thread("test-launch") { public void run() { try { exitCode.set(session.launch()); } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } }; t.start(); Thread.sleep(500); for (Bundle b : context.getBundles()) { System.out.println(b.getLocation()); } assertEquals(4, context.getBundles().length); String p1 = t1.getAbsolutePath(); System.out.println(p1); assertNotNull(context.getBundle(p1)); assertNotNull(context.getBundle(t2.getAbsolutePath())); pl.cancel(); latch.await(); assertEquals(-3, exitCode.get()); bndrun.close(); }
public void executeWithLowPriorityInOwnThreadAndWait(Runnable runnable) { Thread thread = new Thread(runnable); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); while (true) { try { thread.join(); return; } catch (InterruptedException e) { e.printStackTrace(); } } }
@Test public void testBlockingQL() { final BlockingQL ql = new BlockingQL(); final AtomicInteger c = new AtomicInteger(0); Thread thread = new Thread("producer thread") { public void run() { System.out.println("producer"); for (; ; ) { try { System.out.println(this.getName() + "produce"); ql.offer("aaa" + c.incrementAndGet()); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread1 = new Thread("consumer thread") { public void run() { System.out.println("consumer"); for (; ; ) { try { Object o = ql.take(); System.out.println(this.getName() + " consume " + o); } catch (InterruptedException e) { e.printStackTrace(); } } } }; thread1.start(); thread.start(); }
@Override public void subscribe(final Subscriber<? super String> observer) { observer.onSubscribe(EmptySubscription.INSTANCE); t = new Thread( new Runnable() { @Override public void run() { observer.onNext("hello"); observer.onComplete(); } }); t.start(); }
public ThreadBoundExecutorImpl( ThreadBoundEventProcessor eventProcessor, int maxBatchSize, ThreadFactory threadFactory, int numberOfThreads) { this.threadFactory = threadFactory; LOG.info( format( "Initializing (LinkedBlockingQueue)ThreadBoundExecutor[%s]", threadFactory.toString())); for (int i = 0; i < numberOfThreads; i++) { BlockingQueue<ThreadBoundEvent> queue = new LinkedBlockingQueue<>(); Thread t = threadFactory.newThread(new Consumer(queue, eventProcessor, maxBatchSize)); queues.add(queue); t.start(); } }
public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): "); String directory = in.nextLine(); System.out.print("Enter keyword (e.g. volatile): "); String keyword = in.nextLine(); MatchCounter counter = new MatchCounter(new File(directory), keyword); FutureTask<Integer> task = new FutureTask<Integer>(counter); Thread t = new Thread(task); t.start(); try { System.out.println(task.get() + " matching files."); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { } }