示例#1
1
  /**
   * 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();
    }
  }
 @Override
 public Thread newThread(Runnable r) {
   Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
   if (t.isDaemon()) t.setDaemon(false);
   t.setPriority(threadPriority);
   return t;
 }
示例#3
1
 @Override
 /** {@inheritDoc} */
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r);
   t.setDaemon(true);
   return t;
 }
  public void waitInternal(boolean interrupt) {
    if (queueListener.get() == null) {
      return;
    }
    if (isCurrentThread()) {
      return;
    }

    long MAX_TIMEOUT = 1000 * 10;
    long start = System.currentTimeMillis();

    while (queueListener.get().isRunning()) {
      try {
        TimeUnit.MILLISECONDS.sleep(100);

        Thread thread = queueListener.get().getThread();
        if (interrupt) {
          if (thread != null) {
            thread.interrupt();
          }
        } else if (System.currentTimeMillis() - start > MAX_TIMEOUT) {
          if (thread != null) {
            String msg = "Waited for " + MAX_TIMEOUT + "ms, will now interrupt the thread";
            log.warn(msg);
            thread.interrupt();
            throw new RuntimeException(msg);
          }
        }
      } catch (InterruptedException e) {
        log.trace("Got Interrupted while waiting for tasks.", e);
      }
    }
  }
 @Test
 public void removeListener() throws InterruptedException, IOException {
   HazelcastClient hClient = getHazelcastClient();
   final IMap<String, String> map = hClient.getMap("removeListener");
   final CountDownLatch entryAddLatch = new CountDownLatch(5);
   final CountDownLatch entryUpdatedLatch = new CountDownLatch(5);
   final CountDownLatch entryRemovedLatch = new CountDownLatch(5);
   CountDownLatchEntryListener<String, String> listener1 =
       new CountDownLatchEntryListener<String, String>(
           entryAddLatch, entryUpdatedLatch, entryRemovedLatch);
   CountDownLatchEntryListener<String, String> listener2 =
       new CountDownLatchEntryListener<String, String>(
           entryAddLatch, entryUpdatedLatch, entryRemovedLatch);
   map.addEntryListener(listener1, true);
   map.put("hello", "world");
   map.put("hello", "new world");
   map.remove("hello");
   Thread.sleep(100);
   assertEquals(4, entryAddLatch.getCount());
   assertEquals(4, entryRemovedLatch.getCount());
   assertEquals(4, entryUpdatedLatch.getCount());
   map.removeEntryListener(listener1);
   map.put("hello", "world");
   map.put("hello", "new world");
   map.remove("hello");
   Thread.sleep(100);
   assertEquals(4, entryAddLatch.getCount());
   assertEquals(4, entryRemovedLatch.getCount());
   assertEquals(4, entryUpdatedLatch.getCount());
 }
  /** 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));
  }
  @Test
  public void putFromMultipleThreads() throws InterruptedException {
    final HazelcastInstance h = Hazelcast.newHazelcastInstance(null);
    final AtomicInteger counter = new AtomicInteger(0);
    class Putter implements Runnable {
      volatile Boolean run = true;

      public void run() {
        HazelcastClient hClient = TestUtility.newHazelcastClient(h);
        while (run) {
          Map<String, String> clientMap = hClient.getMap("putFromMultipleThreads");
          clientMap.put(String.valueOf(counter.incrementAndGet()), String.valueOf(counter.get()));
        }
      }
    };
    List<Putter> list = new ArrayList<Putter>();
    for (int i = 0; i < 10; i++) {
      Putter p = new Putter();
      list.add(p);
      new Thread(p).start();
    }
    Thread.sleep(5000);
    for (Iterator<Putter> it = list.iterator(); it.hasNext(); ) {
      Putter p = it.next();
      p.run = false;
    }
    Thread.sleep(100);
    assertEquals(counter.get(), h.getMap("putFromMultipleThreads").size());
  }
 @Override
 public void run() {
   try {
     boolean running = true;
     while (running) {
       try {
         // block on event availability
         ThreadBoundEvent event = queue.take();
         // add to the batch, and see if we can add more
         batch.add(event);
         if (maxBatchSize > 0) {
           queue.drainTo(batch, maxBatchSize);
         }
         // check for the stop condition (and remove it)
         // treat batches of 1 (the most common case) specially
         if (batch.size() > 1) {
           ListIterator<ThreadBoundEvent> itr = batch.listIterator();
           while (itr.hasNext()) {
             ThreadBoundEvent next = itr.next();
             if (next.getClass().equals(ShutdownTask.class)) {
               running = false;
               ((ShutdownTask) next).latch.countDown();
               itr.remove();
             }
           }
           eventProcessor.process(batch);
         } else {
           // just the one event, no need to iterate
           if (event.getClass().equals(ShutdownTask.class)) {
             running = false;
             ((ShutdownTask) event).latch.countDown();
           } else {
             eventProcessor.process(batch);
           }
         }
       } catch (InterruptedException e) {
         LOG.warn(
             String.format(
                 "Consumer on queue %s interrupted.", Thread.currentThread().getName()));
         // ignore
       } catch (Throwable exception) {
         LOG.error(
             String.format(
                 "exception on queue %s while executing events",
                 Thread.currentThread().getName()),
             exception);
       } finally {
         // reset the batch
         batch.clear();
       }
     }
   } catch (Throwable unexpectedThrowable) {
     // we observed some cases where trying to log the inner exception threw an error
     // don't use the logger here as that seems to be causing the problem in the first place
     System.err.println("Caught and unexpected Throwable while logging");
     System.err.println(
         "This problem happens when jar files change at runtime, JVM might be UNSTABLE");
     unexpectedThrowable.printStackTrace(System.err);
   }
 }
示例#9
0
  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();
    }
  }
示例#10
0
  /* (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);
  }
示例#11
0
 @Override
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r);
   t.setDaemon(true);
   t.setName("shell-bolt-heartbeat");
   return t;
 }
  public static void main(String[] args) throws Exception {
    int maxThreads = 100;

    if (args.length > 0) maxThreads = Integer.parseInt(args[0]);

    System.out.print("Warmup:");
    for (int j = 0; j < 2; ++j) {
      int k = 1;
      for (int i = 1; i <= maxThreads; ) {
        System.out.print(" " + i);
        oneTest(i, 10000, false);
        Thread.sleep(100);
        if (i == k) {
          k = i << 1;
          i = i + (i >>> 1);
        } else i = k;
      }
    }
    System.out.println();

    int k = 1;
    for (int i = 1; i <= maxThreads; ) {
      System.out.println("Threads:" + i);
      oneTest(i, maxIters, true);
      Thread.sleep(100);
      if (i == k) {
        k = i << 1;
        i = i + (i >>> 1);
      } else i = k;
    }
  }
示例#13
0
文件: BaseTest.java 项目: fanlu/MyApp
 @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());
 }
示例#14
0
  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);
    }
  }
示例#15
0
 @Override
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r);
   t.setName("Threading.THREAD_POOL worker");
   t.setDaemon(true);
   return t;
 }
示例#16
0
  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;
  }
示例#17
0
  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();
  }
  /**
   * Tests the behavior of Zookeeper upon a restart. ZK should clean up old coordinates.
   *
   * @throws Exception
   */
  @Test
  public void testZookeeperRestarts() throws Exception {
    final CountDownLatch connectedLatch1 = new CountDownLatch(1);
    final CountDownLatch connectedLatch2 = new CountDownLatch(3);
    TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1, connectedLatch2);
    assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
    log.info("Killing zookeeper");
    forwarder.terminate();

    ezk.shutdown();
    ezk.del();
    ezk.init();
    Thread.sleep(2000);
    forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);

    int timeoutSecs = 30;
    while (--timeoutSecs > 0) {
      Thread.sleep(1000);
    }
    Coordinate c = Coordinate.parse("1.service.user.cell");
    cn.createCoordinate(c);

    Thread.sleep(9000);
    assertEquals(
        listener.events.get(listener.events.size() - 1), CoordinateListener.Event.COORDINATE_OK);
  }
示例#19
0
    final void test() throws Exception {
      Future[] futures = new Future[nthreads];
      for (int i = 0; i < nthreads; ++i) futures[i] = pool.submit(this);

      barrier.await();
      Thread.sleep(TIMEOUT);
      boolean tooLate = false;
      for (int i = 1; i < nthreads; ++i) {
        if (!futures[i].cancel(true)) tooLate = true;
        // Unbunch some of the cancels
        if ((i & 3) == 0) Thread.sleep(1 + rng.next() % 10);
      }

      Object f0 = futures[0].get();
      if (!tooLate) {
        for (int i = 1; i < nthreads; ++i) {
          if (!futures[i].isDone() || !futures[i].isCancelled())
            throw new Error("Only one thread should complete");
        }
      } else System.out.print("(cancelled too late) ");

      long endTime = System.nanoTime();
      long time = endTime - timer.startTime;
      if (print) {
        double secs = (double) (time) / 1000000000.0;
        System.out.println("\t " + secs + "s run time");
      }
    }
示例#20
0
  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);
  }
示例#21
0
文件: BaseTest.java 项目: fanlu/MyApp
 @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 testCoordinateListenerConnectionDiesReconnectAfterTimeout() throws Exception {
    final CountDownLatch connectedLatch1 = new CountDownLatch(2);
    final CountDownLatch connectedLatch2 = new CountDownLatch(6);
    TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1, connectedLatch2);
    assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
    assertEquals(
        CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1));
    log.info("Killing connection");
    forwarder.terminate();

    log.info("Connection down.");

    Thread.sleep(9000);
    log.info("Recreating connection soon" + forwarderPort + "->" + zkport);
    Thread.sleep(1000);
    assertEquals(
        CoordinateListener.Event.NO_CONNECTION_TO_STORAGE,
        listener.events.get(listener.events.size() - 1));
    forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);
    assertTrue(connectedLatch2.await(20, TimeUnit.SECONDS));

    for (int c = 0; c < 100; c++) {
      if (CoordinateListener.Event.COORDINATE_OK
          == listener.events.get(listener.events.size() - 1)) {
        break;
      }
      Thread.sleep(300);
    }
    Thread.sleep(4500);
    assertEquals(
        CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1));

    forwarder.terminate();
  }
示例#23
0
  // 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);
    }
  }
 public Notifier(String listenNodePath) {
   super.setDaemon(true);
   super.setName("LTSRedisSubscribe");
   this.listenNodePath = listenNodePath;
   if (monitorId == null) {
     monitorId = listenNodePath;
   }
 }
示例#25
0
  @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 printThreads() {
   Thread[] threads = getAllThreads();
   for (int i = 0; i < threads.length; i++) {
     Thread t = threads[i];
     if (t != null) {
       System.out.println(t.getName());
     }
   }
 }
示例#27
0
 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);
 }
 void stop() {
   stopping = true;
   sinkThread.interrupt();
   try {
     sinkThread.join();
   } catch (InterruptedException e) {
     LOG.warn("Stop interrupted", e);
   }
 }
示例#29
0
 @Override
 public void run() {
   System.out.println(
       System.currentTimeMillis() + ":Thread ID:" + Thread.currentThread().getId());
   try {
     Thread.sleep(100);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
示例#30
0
 synchronized void waitingCall() {
   try {
     while (!Thread.interrupted()) {
       wait();
       System.out.print(Thread.currentThread() + " ");
     }
   } catch (InterruptedException e) {
     // OK to exit this way
   }
 }