コード例 #1
0
  @Test
  public void testOfferPoll() throws IOException, InterruptedException {

    final IQueue q = client.getQueue(queueForTestOfferPoll);

    for (int i = 0; i < 10; i++) {
      boolean result = q.offer("item");
      if (i < maxSizeForQueue) {
        assertTrue(result);
      } else {
        assertFalse(result);
      }
    }
    assertEquals(maxSizeForQueue, q.size());

    final Thread t1 =
        new Thread() {
          public void run() {
            try {
              Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            q.poll();
          }
        };
    t1.start();

    boolean result = q.offer("item", 5, TimeUnit.SECONDS);
    assertTrue(result);

    for (int i = 0; i < 10; i++) {
      Object o = q.poll();
      if (i < maxSizeForQueue) {
        assertNotNull(o);
      } else {
        assertNull(o);
      }
    }
    assertEquals(0, q.size());

    final Thread t2 =
        new Thread() {
          public void run() {
            try {
              Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            q.offer("item1");
          }
        };
    t2.start();

    Object o = q.poll(5, TimeUnit.SECONDS);
    assertEquals("item1", o);
    t1.join(10000);
    t2.join(10000);
  }
コード例 #2
0
  @Test
  public void parallelRead() {
    Random rnd = new Random();
    int N = 10;

    // write N key values in hashmap and store
    for (int i = 0; i < N; i++) {
      String keyValue = String.valueOf(rnd.nextInt(999999));
      String resultValue = String.valueOf(rnd.nextInt(99999));

      KeyImpl key = new KeyImpl();
      key.setKey(keyValue);

      ValueImpl value = new ValueImpl();
      value.setValue(resultValue);

      ValueListImpl valueList = new ValueListImpl();
      valueList.getValueList().add(value);
      try {
        kvbis.insert(key, valueList);
        testMap.put(keyValue, resultValue);
      } catch (KeyAlreadyPresentException_Exception e) {
        // do nothing
      } catch (IOException_Exception e) {
        e.printStackTrace();
      } catch (ServiceNotInitializedException_Exception e) {
        e.printStackTrace();
      }
    }

    keys = new ArrayList<String>(testMap.keySet());
    String randomUpdateKey = keys.get(rnd.nextInt(keys.size()));

    Runnable updater = new UpdateThread(randomUpdateKey);
    Thread updateThread = new Thread(updater);
    updateThread.start();

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    Runnable reader = new ReadThread(randomUpdateKey);
    Thread readThread = new Thread(reader);
    readThread.start();

    try {
      readThread.join();
      updateThread.join();
    } catch (InterruptedException e) {

    }

    // if one read failed fail test case
    assertEquals("Result", readValue, updatedValue);
  }
コード例 #3
0
ファイル: LockTest.java プロジェクト: harunpehlivan/hazelcast
  @Test
  public void testIsLocked2() throws Exception {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final Config config = new Config();

    final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config);
    final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config);

    final int key = new Random().nextInt();

    final ILock lock = instance1.getLock(key);
    lock.lock();
    assertTrue(lock.isLocked());
    assertTrue(lock.isLockedByCurrentThread());

    assertTrue(lock.tryLock());
    assertTrue(lock.isLocked());
    assertTrue(lock.isLockedByCurrentThread());

    final AtomicBoolean result = new AtomicBoolean();
    final Thread thread =
        new Thread() {
          public void run() {
            result.set(lock.isLockedByCurrentThread());
          }
        };
    thread.start();
    thread.join();
    assertFalse(result.get());

    lock.unlock();
    assertTrue(lock.isLocked());
    assertTrue(lock.isLockedByCurrentThread());
  }
コード例 #4
0
ファイル: TestTempTables.java プロジェクト: elfilip/teiid-1
  @Test
  public void testAtomicUpdate() throws Exception {
    execute(
        "create local temporary table x (e1 string, e2 integer, primary key (e2))",
        new List[] {Arrays.asList(0)}); // $NON-NLS-1$
    execute(
        "insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); // $NON-NLS-1$
    execute(
        "insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); // $NON-NLS-1$
    try {
      execute("update x set e2 = 3", new List[] {Arrays.asList(1)}); // $NON-NLS-1$
    } catch (TeiidProcessingException e) {
      // should be a duplicate key
    }
    // should revert back to original
    execute("select count(*) from x", new List[] {Arrays.asList(2)}); // $NON-NLS-1$

    Thread t =
        new Thread() {
          public void run() {
            try {
              execute("select count(e1) from x", new List[] {Arrays.asList(2)});
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    t.start();
    t.join(2000);
    assertFalse(t.isAlive());
  }
コード例 #5
0
 private static <R> void verifyInvocationCannotBeInterrupted(final WSTester<R> inTester)
     throws Exception {
   resetServiceParameters();
   getMockSAService().setSleep(true);
   inTester.setReturnValue(false);
   final Semaphore sema = new Semaphore(0);
   final AtomicReference<Exception> interruptFailure = new AtomicReference<Exception>();
   Thread t =
       new Thread() {
         @Override
         public void run() {
           sema.release();
           try {
             inTester.invokeApi(false);
           } catch (Exception ex) {
             interruptFailure.set(ex);
           }
         }
       };
   t.start();
   // Wait for the thread to be started
   sema.acquire();
   // Interrupt it as soon as it is found started
   t.interrupt();
   // wait for it to end
   t.join();
   // verify that we are not able to interrupt it
   assertNull("API invocation got interrupted!", interruptFailure.get());
 }
コード例 #6
0
  /**
   * Time a multi-threaded access to a cache.
   *
   * @return the timing stopwatch
   */
  private <V> StopWatch timeMultiThreaded(
      String id, final Map<Integer, V> map, ValueFactory<V> factory) throws InterruptedException {

    StopWatch stopWatch = new StopWatch(id);
    for (int i = 0; i < 500; i++) {
      map.put(i, factory.newValue(i));
    }
    Thread[] threads = new Thread[30];
    stopWatch.start("Running threads");
    for (int threadIndex = 0; threadIndex < threads.length; threadIndex++) {
      threads[threadIndex] =
          new Thread("Cache access thread " + threadIndex) {
            @Override
            public void run() {
              for (int j = 0; j < 1000; j++) {
                for (int i = 0; i < 1000; i++) {
                  map.get(i);
                }
              }
            }
          };
    }
    for (Thread thread : threads) {
      thread.start();
    }

    for (Thread thread : threads) {
      if (thread.isAlive()) {
        thread.join(2000);
      }
    }
    stopWatch.stop();
    return stopWatch;
  }
コード例 #7
0
ファイル: ChannelTest.java プロジェクト: pmbauer/quasar
  @Test
  public void sendMessageFromThreadToThread() throws Exception {
    final Channel<String> ch = newChannel();

    Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  Thread.sleep(100);

                  ch.send("a message");
                } catch (InterruptedException | SuspendExecution ex) {
                  throw new AssertionError(ex);
                }
              }
            });
    thread.start();

    String m = ch.receive();

    assertThat(m, equalTo("a message"));

    thread.join();
  }
コード例 #8
0
ファイル: LockTest.java プロジェクト: harunpehlivan/hazelcast
  @Test(expected = DistributedObjectDestroyedException.class)
  public void testDestroyLockWhenOtherWaitingOnLock() throws InterruptedException {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1);
    final HazelcastInstance instance = nodeFactory.newHazelcastInstance(new Config());
    final ILock lock = instance.getLock("testLockDestroyWhenWaitingLock");
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                lock.lock();
              }
            });
    t.start();
    t.join();

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  Thread.sleep(1000);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                lock.destroy();
              }
            })
        .start();

    lock.lock();
  }
コード例 #9
0
  /**
   * Initiator and target should successfully connect to the local SOCKS5 proxy.
   *
   * @throws Exception should not happen
   */
  @Test
  public void shouldSuccessfullyConnectThroughLocalSocks5Proxy() throws Exception {

    // start a local SOCKS5 proxy
    Socks5Proxy.setLocalSocks5ProxyPort(proxyPort);
    Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
    socks5Proxy.start();

    // test data
    final byte[] data = new byte[] {1, 2, 3};

    // create digest
    final String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

    // allow connection of target with this digest
    socks5Proxy.addTransfer(digest);

    // build stream host information
    final StreamHost streamHost =
        new StreamHost(connection.getUser(), socks5Proxy.getLocalAddresses().get(0));
    streamHost.setPort(socks5Proxy.getPort());

    // target connects to local SOCKS5 proxy
    Thread targetThread =
        new Thread() {

          @Override
          public void run() {
            try {
              Socks5Client targetClient = new Socks5Client(streamHost, digest);
              Socket socket = targetClient.getSocket(10000);
              socket.getOutputStream().write(data);
            } catch (Exception e) {
              fail(e.getMessage());
            }
          }
        };
    targetThread.start();

    Thread.sleep(200);

    // initiator connects
    Socks5ClientForInitiator socks5Client =
        new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID);

    Socket socket = socks5Client.getSocket(10000);

    // verify test data
    InputStream in = socket.getInputStream();
    for (int i = 0; i < data.length; i++) {
      assertEquals(data[i], in.read());
    }

    targetThread.join();

    protocol.verifyAll(); // assert no XMPP messages were sent

    socks5Proxy.removeTransfer(digest);
    socks5Proxy.stop();
  }
コード例 #10
0
ファイル: ChannelTest.java プロジェクト: pmbauer/quasar
  @Ignore
  @Test
  public void whenReceiveNotCalledFromOwnerThenThrowException4() throws Exception {
    assumeTrue(Debug.isAssertionsEnabled());
    final Channel<String> ch = newChannel();

    Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  ch.receive();
                } catch (InterruptedException ex) {
                  throw new AssertionError(ex);
                } catch (SuspendExecution e) {
                  throw new AssertionError(e);
                }
              }
            });
    thread.start();

    Thread.sleep(100);
    ch.send("a message");

    boolean thrown = false;
    try {
      ch.receive();
    } catch (Throwable e) {
      thrown = true;
    }
    assertTrue(thrown);

    thread.join();
  }
コード例 #11
0
  @Test
  public void testShouldBlockWhenNotAtHead() throws InterruptedException {
    MockQueue q = new MockQueue();
    final BlockingEnvelopeMap map = new MockBlockingEnvelopeMap(q);

    map.register(SSP, "0");

    Thread t =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  // Should trigger a take() call.
                  map.poll(FETCH, -1);
                } catch (InterruptedException e) {
                  throw new RuntimeException(e);
                }
              }
            });

    t.setDaemon(true);
    t.start();
    q.awaitPollTimeout();
    t.join(60000);

    // 1000 = blocking timeout constant
    assertEquals(1000, q.timeout);
    assertFalse(t.isAlive());
  }
コード例 #12
0
  private static void testCallExitsOnClose(
      final QueueCall call, ClosableBlockingQueue<String> queue) throws Exception {

    final AtomicReference<Throwable> errorRef = new AtomicReference<>();

    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            try {
              call.call();
            } catch (Throwable t) {
              errorRef.set(t);
            }
          }
        };

    Thread thread = new Thread(runnable);
    thread.start();
    Thread.sleep(100);
    queue.close();
    thread.join();

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    Throwable cause = errorRef.get();
    assertTrue(cause instanceof IllegalStateException);
  }
コード例 #13
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);
    }
  }
コード例 #14
0
ファイル: FieldValuesTest.java プロジェクト: happyyang/vtk-2
  @Test
  public void multithreadedDateValueIndexFieldEncoding() {

    Thread[] threads = new Thread[10];
    for (int i = 0; i < threads.length; i++) {
      threads[i] =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  dateValueIndexFieldEncoding();
                }
              });
    }
    for (Thread thread : threads) {
      thread.start();
    }
    for (Thread thread : threads) {
      try {
        thread.join();
      } catch (InterruptedException ie) {
        fail("Interrupted while waiting for test threads to finish.");
      }
    }
  }
コード例 #15
0
 @After
 public void tearDown() {
   try {
     RunnableQueue.stop();
     t.join();
   } catch (InterruptedException e) {
     throw new AssertionError("Thread unexpectedly interrupted during join");
   } catch (ExecutionException e) {
     throw new AssertionError("Stop's runnable unexpectedly threw an exception.");
   }
 }
コード例 #16
0
ファイル: EvictionTest.java プロジェクト: qhfu/hazelcast
  @Test
  public void testMapRecordIdleEvictionOnMigration() throws InterruptedException {
    Config cfg = new Config();
    final String name = "testMapRecordIdleEvictionOnMigration";
    MapConfig mc = cfg.getMapConfig(name);
    int maxIdleSeconds = 10;
    int size = 100;
    final int nsize = size / 5;
    mc.setMaxIdleSeconds(maxIdleSeconds);
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(3);

    HazelcastInstance instance1 = factory.newHazelcastInstance(cfg);
    final IMap map = instance1.getMap(name);
    final CountDownLatch latch = new CountDownLatch(size - nsize);
    map.addEntryListener(
        new EntryAdapter() {
          public void entryEvicted(EntryEvent event) {
            latch.countDown();
          }
        },
        false);

    for (int i = 0; i < size; i++) {
      map.put(i, i);
    }
    final Thread thread =
        new Thread(
            new Runnable() {
              public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                  try {
                    for (int i = 0; i < nsize; i++) {
                      map.get(i);
                    }
                    Thread.sleep(1000);
                  } catch (HazelcastInstanceNotActiveException e) {
                    return;
                  } catch (InterruptedException e) {
                    return;
                  }
                }
              }
            });
    thread.start();
    HazelcastInstance instance2 = factory.newHazelcastInstance(cfg);
    HazelcastInstance instance3 = factory.newHazelcastInstance(cfg);

    assertTrue(latch.await(1, TimeUnit.MINUTES));
    Assert.assertEquals(nsize, map.size());

    thread.interrupt();
    thread.join(5000);
  }
コード例 #17
0
  @Test
  public void testProtocolSet() throws Exception {
    final ThrottleInterceptor i = new ThrottleInterceptor();
    final Exchange exc = new Exchange(null);

    long t = System.currentTimeMillis();
    i.handleRequest(exc);
    assertTrue(System.currentTimeMillis() - t < 2000);

    t = System.currentTimeMillis();
    i.setDelay(3000);
    i.handleRequest(exc);
    assertTrue(System.currentTimeMillis() - t > 2000);

    i.setDelay(0);

    i.setMaxThreads(3);
    assertEquals(Outcome.CONTINUE, i.handleRequest(exc));

    assertEquals(Outcome.ABORT, i.handleRequest(exc));
    assertEquals(503, exc.getResponse().getStatusCode());

    i.handleResponse(exc);
    assertEquals(Outcome.CONTINUE, i.handleRequest(exc));

    i.setBusyDelay(3000);
    t = System.currentTimeMillis();
    assertEquals(Outcome.ABORT, i.handleRequest(exc));
    assertTrue(System.currentTimeMillis() - t > 2000);

    Thread thread1 =
        new Thread() {
          @Override
          public void run() {
            try {
              success = (Outcome.CONTINUE == i.handleRequest(exc));
            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          };
        };

    thread1.start();

    Thread.sleep(1000);
    i.handleResponse(exc);

    thread1.join();

    assertTrue(success);
  }
コード例 #18
0
ファイル: LockTest.java プロジェクト: harunpehlivan/hazelcast
  @Test(timeout = 100000)
  public void testKeyOwnerDiesOnCondition() throws Exception {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);
    final Config config = new Config();
    final HazelcastInstance keyOwner = nodeFactory.newHazelcastInstance(config);
    final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config);
    final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config);
    int k = 0;
    final AtomicInteger atomicInteger = new AtomicInteger(0);
    while (keyOwner
        .getCluster()
        .getLocalMember()
        .equals(instance1.getPartitionService().getPartition(k++).getOwner())) {
      Thread.sleep(10);
    }

    final int key = k;
    final ILock lock1 = instance1.getLock(key);
    final String name = "testKeyOwnerDiesOnCondition";
    final ICondition condition1 = lock1.newCondition(name);

    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                final ILock lock = instance2.getLock(key);
                final ICondition condition = lock.newCondition(name);
                lock.lock();
                try {
                  condition.await();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                } finally {
                  lock.unlock();
                }
                atomicInteger.incrementAndGet();
              }
            });
    t.start();
    Thread.sleep(1000);
    lock1.lock();
    keyOwner.getLifecycleService().shutdown();

    condition1.signal();

    lock1.unlock();
    Thread.sleep(1000);
    t.join();
    Assert.assertEquals(1, atomicInteger.get());
  }
コード例 #19
0
 @Test
 public void testMultiThread() throws InterruptedException {
   SessionState ss = SessionState.get();
   ss.getDefaultJob().set("foo", "bar");
   Thread thread =
       new Thread() {
         @Override
         public void run() {
           SessionState ss = SessionState.get();
           assertEquals("bar", ss.getDefaultJob().get("foo"));
         }
       };
   thread.start();
   thread.join();
 }
コード例 #20
0
ファイル: StoreWALTest.java プロジェクト: jibaro/mapdb
  void compact_tx_works(final boolean rollbacks, final boolean pre) throws InterruptedException {
    e = openEngine();
    Map<Long, String> m = fill(e);
    e.commit();

    if (pre) e.$_TEST_HACK_COMPACT_PRE_COMMIT_WAIT = true;
    else e.$_TEST_HACK_COMPACT_POST_COMMIT_WAIT = true;

    Thread t =
        new Thread() {
          @Override
          public void run() {
            e.compact();
          }
        };
    t.start();

    Thread.sleep(1000);

    // we should be able to commit while compaction is running
    for (Long recid : m.keySet()) {
      boolean revert = rollbacks && Math.random() < 0.5;
      e.update(recid, "ZZZ", Serializer.STRING);
      if (revert) {
        e.rollback();
      } else {
        e.commit();
        m.put(recid, "ZZZ");
      }
    }

    if (pre) assertTrue(t.isAlive());

    Thread.sleep(1000);

    e.$_TEST_HACK_COMPACT_PRE_COMMIT_WAIT = false;
    e.$_TEST_HACK_COMPACT_POST_COMMIT_WAIT = false;

    t.join();

    for (Long recid : m.keySet()) {
      assertEquals(m.get(recid), e.get(recid, Serializer.STRING));
    }

    e.close();
  }
コード例 #21
0
  @Test
  public void testDualConnections() throws Exception {
    SailConnection con2 = sail.getConnection();
    try {
      assertEquals(0, countAllElements());
      con.begin();
      con.addStatement(painter, RDF.TYPE, RDFS.CLASS);
      con.addStatement(painting, RDF.TYPE, RDFS.CLASS);
      con.addStatement(picasso, RDF.TYPE, painter, context1);
      con.addStatement(guernica, RDF.TYPE, painting, context1);
      con.commit();
      assertEquals(4, countAllElements());
      con2.begin();
      con2.addStatement(RDF.NIL, RDF.TYPE, RDF.LIST);
      String query = "SELECT S, P, O FROM {S} P {O}";
      ParsedTupleQuery tupleQuery =
          QueryParserUtil.parseTupleQuery(QueryLanguage.SERQL, query, null);
      assertEquals(
          5,
          countElements(
              con2.evaluate(
                  tupleQuery.getTupleExpr(), null, EmptyBindingSet.getInstance(), false)));
      Runnable clearer =
          new Runnable() {

            public void run() {
              try {
                con.begin();
                con.clear();
                con.commit();
              } catch (SailException e) {
                throw new RuntimeException(e);
              }
            }
          };
      Thread thread = new Thread(clearer);
      thread.start();
      Thread.yield();
      Thread.yield();
      con2.commit();
      thread.join();
    } finally {
      con2.close();
    }
  }
コード例 #22
0
  @Test
  public void testRemoveHostId() throws InterruptedException {
    ReplicationSink rSink = new ReplicationSink();
    SinkManager.add(rSink);

    // start removal in background and send replication confirmations
    final AtomicBoolean success = new AtomicBoolean(false);
    Thread remover =
        new Thread() {
          public void run() {
            try {
              ss.removeNode(removalId.toString());
            } catch (Exception e) {
              System.err.println(e);
              e.printStackTrace();
              return;
            }
            success.set(true);
          }
        };
    remover.start();

    Thread.sleep(1000); // make sure removal is waiting for confirmation

    assertTrue(tmd.isLeaving(removalhost));
    assertEquals(1, tmd.getLeavingEndpoints().size());

    for (InetAddress host : hosts) {
      MessageOut msg =
          new MessageOut(
              host,
              MessagingService.Verb.REPLICATION_FINISHED,
              null,
              null,
              Collections.<String, byte[]>emptyMap());
      MessagingService.instance().sendRR(msg, FBUtilities.getBroadcastAddress());
    }

    remover.join();

    assertTrue(success.get());
    assertTrue(tmd.getLeavingEndpoints().isEmpty());
  }
コード例 #23
0
  @Test
  public void testRegister() throws InterruptedException, IOException {
    RuntimeEnvironment instance = RuntimeEnvironment.getInstance();
    String path = "/tmp/dataroot";
    instance.setDataRoot(path);
    instance.register();
    Thread t =
        new Thread(
            new Runnable() {

              public void run() {
                Configuration c = new Configuration();
                RuntimeEnvironment.getInstance().setConfiguration(c);
              }
            });
    t.start();
    t.join();
    assertEquals(new File(path).getCanonicalFile().getAbsolutePath(), instance.getDataRootPath());
  }
コード例 #24
0
  @Test
  public void testShouldPollWithATimeout() throws InterruptedException {
    MockQueue q = new MockQueue();
    // Always use the same time in this test so that we can be sure we get a
    // 100ms poll, rather than a 99ms poll (for example). Have to do this
    // because BlockingEnvelopeMap calls clock.currentTimeMillis twice, and
    // uses the second call to determine the actual poll time.
    final BlockingEnvelopeMap map =
        new MockBlockingEnvelopeMap(
            q,
            new Clock() {
              private final long NOW = System.currentTimeMillis();

              public long currentTimeMillis() {
                return NOW;
              }
            });

    map.register(SSP, "0");

    Thread t =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  // Should trigger a poll(100, TimeUnit.MILLISECONDS) call.
                  map.poll(FETCH, 100);
                } catch (InterruptedException e) {
                  throw new RuntimeException(e);
                }
              }
            });

    t.setDaemon(true);
    t.start();
    q.awaitPollTimeout();
    t.join(60000);

    assertEquals(100, q.timeout);
    assertFalse(t.isAlive());
  }
コード例 #25
0
ファイル: LockTest.java プロジェクト: harunpehlivan/hazelcast
  @Test
  public void testLockConditionSimpleUsage() throws InterruptedException {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final Config config = new Config();
    final String name = "testLockConditionSimpleUsage";
    final ILock lock = nodeFactory.newHazelcastInstance(config).getLock(name);
    final ICondition condition = lock.newCondition(name + "c");
    final AtomicInteger count = new AtomicInteger(0);

    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  lock.lock();
                  if (lock.isLockedByCurrentThread()) {
                    count.incrementAndGet();
                  }
                  condition.await();
                  if (lock.isLockedByCurrentThread()) {
                    count.incrementAndGet();
                  }
                } catch (InterruptedException ignored) {
                } finally {
                  lock.unlock();
                }
              }
            });
    t.start();
    Thread.sleep(1000);

    final ILock lock1 = nodeFactory.newHazelcastInstance(config).getLock(name);
    final ICondition condition1 = lock1.newCondition(name + "c");
    Assert.assertEquals(false, lock1.isLocked());
    lock1.lock();
    Assert.assertEquals(true, lock1.isLocked());
    condition1.signal();
    lock1.unlock();
    t.join();
    Assert.assertEquals(2, count.get());
  }
コード例 #26
0
ファイル: CMMTest.java プロジェクト: villalon/tml-cmm
  @Test
  public void PennTreeAnnotation() throws Exception {

    repository.addAnnotator(new PennTreeAnnotator());
    Thread th = repository.annotateDocuments();
    th.run();
    th.join();

    assertNotNull(th);

    assertNotNull(repository.getAnnotations("s1d0100.a1", "penntree"));

    String[] lines = repository.getAnnotations("s3d0100.a1", "penntree").split("\r\n");
    String[] expectedLines = sentence3pennstring.split("\r\n");

    assertEquals(lines.length, expectedLines.length);

    for (int i = 0; i < Math.min(lines.length, expectedLines.length); i++) {
      assertEquals(expectedLines[i].trim(), lines[i].trim());
    }
  }
コード例 #27
0
ファイル: LockTest.java プロジェクト: harunpehlivan/hazelcast
  private void testShutDownNodeWhenOtherWaitingOnLock(boolean localKey)
      throws InterruptedException {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final HazelcastInstance instance = nodeFactory.newHazelcastInstance(new Config());
    final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(new Config());
    warmUpPartitions(instance2, instance);

    final String key;
    if (localKey) {
      key = generateKeyOwnedBy(instance);
    } else {
      key = generateKeyNotOwnedBy(instance);
    }

    final ILock lock = instance.getLock(key);
    final Thread thread =
        new Thread(
            new Runnable() {
              public void run() {
                lock.lock();
              }
            });
    thread.start();
    thread.join();
    new Thread(
            new Runnable() {
              public void run() {
                try {
                  Thread.sleep(3000);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                instance.getLifecycleService().shutdown();
              }
            })
        .start();
    lock.lock();
  }
コード例 #28
0
ファイル: LockTest.java プロジェクト: harunpehlivan/hazelcast
  @Test(timeout = 100000)
  public void testScheduledLockActionForDeadMember() throws Exception {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final HazelcastInstance h1 = nodeFactory.newHazelcastInstance(new Config());
    final ILock lock1 = h1.getLock("default");
    final HazelcastInstance h2 = nodeFactory.newHazelcastInstance(new Config());
    final ILock lock2 = h2.getLock("default");

    assertTrue(lock1.tryLock());

    final AtomicBoolean error = new AtomicBoolean(false);
    final Thread thread =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  lock2.lock();
                  error.set(true);
                } catch (Throwable ignored) {
                }
              }
            });
    thread.start();
    Thread.sleep(5000);

    assertTrue(lock1.isLocked());
    h2.getLifecycleService().shutdown();
    thread.join(10000);
    assertFalse(thread.isAlive());
    assertFalse(error.get());

    assertTrue(lock1.isLocked());
    lock1.unlock();
    assertFalse(lock1.isLocked());
    assertTrue(lock1.tryLock());
  }
コード例 #29
0
  @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
  @Test
  public void testMultiThreadedAddGet() {
    try {
      final ClosableBlockingQueue<Integer> queue = new ClosableBlockingQueue<>();
      final AtomicReference<Throwable> pushErrorRef = new AtomicReference<>();
      final AtomicReference<Throwable> pollErrorRef = new AtomicReference<>();

      final int numElements = 2000;

      Thread pusher =
          new Thread("pusher") {

            @Override
            public void run() {
              try {
                final Random rnd = new Random();
                for (int i = 0; i < numElements; i++) {
                  queue.add(i);

                  // sleep a bit, sometimes
                  int sleepTime = rnd.nextInt(3);
                  if (sleepTime > 1) {
                    Thread.sleep(sleepTime);
                  }
                }

                while (true) {
                  if (queue.close()) {
                    break;
                  } else {
                    Thread.sleep(5);
                  }
                }
              } catch (Throwable t) {
                pushErrorRef.set(t);
              }
            }
          };
      pusher.start();

      Thread poller =
          new Thread("poller") {

            @SuppressWarnings("InfiniteLoopStatement")
            @Override
            public void run() {
              try {
                int count = 0;

                try {
                  final Random rnd = new Random();
                  int nextExpected = 0;

                  while (true) {
                    int getMethod = count % 7;
                    switch (getMethod) {
                      case 0:
                        {
                          Integer next = queue.getElementBlocking(1);
                          if (next != null) {
                            assertEquals(nextExpected, next.intValue());
                            nextExpected++;
                            count++;
                          }
                          break;
                        }
                      case 1:
                        {
                          List<Integer> nextList = queue.getBatchBlocking();
                          for (Integer next : nextList) {
                            assertNotNull(next);
                            assertEquals(nextExpected, next.intValue());
                            nextExpected++;
                            count++;
                          }
                          break;
                        }
                      case 2:
                        {
                          List<Integer> nextList = queue.getBatchBlocking(1);
                          if (nextList != null) {
                            for (Integer next : nextList) {
                              assertNotNull(next);
                              assertEquals(nextExpected, next.intValue());
                              nextExpected++;
                              count++;
                            }
                          }
                          break;
                        }
                      case 3:
                        {
                          Integer next = queue.poll();
                          if (next != null) {
                            assertEquals(nextExpected, next.intValue());
                            nextExpected++;
                            count++;
                          }
                          break;
                        }
                      case 4:
                        {
                          List<Integer> nextList = queue.pollBatch();
                          if (nextList != null) {
                            for (Integer next : nextList) {
                              assertNotNull(next);
                              assertEquals(nextExpected, next.intValue());
                              nextExpected++;
                              count++;
                            }
                          }
                          break;
                        }
                      default:
                        {
                          Integer next = queue.getElementBlocking();
                          assertNotNull(next);
                          assertEquals(nextExpected, next.intValue());
                          nextExpected++;
                          count++;
                        }
                    }

                    // sleep a bit, sometimes
                    int sleepTime = rnd.nextInt(3);
                    if (sleepTime > 1) {
                      Thread.sleep(sleepTime);
                    }
                  }
                } catch (IllegalStateException e) {
                  // we get this once the queue is closed
                  assertEquals(numElements, count);
                }
              } catch (Throwable t) {
                pollErrorRef.set(t);
              }
            }
          };
      poller.start();

      pusher.join();
      poller.join();

      if (pushErrorRef.get() != null) {
        Throwable t = pushErrorRef.get();
        t.printStackTrace();
        fail("Error in pusher: " + t.getMessage());
      }
      if (pollErrorRef.get() != null) {
        Throwable t = pollErrorRef.get();
        t.printStackTrace();
        fail("Error in poller: " + t.getMessage());
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
コード例 #30
0
 void join() {
   try {
     thr.join();
   } catch (InterruptedException e) {
   }
 }