Пример #1
0
 /** Run a basic task */
 @Test
 public void testBasicTask() throws Exception {
   Callable<String> task = new BasicTestTask();
   ExecutorService executor = createSingleNodeExecutorService("testBasicTask");
   Future future = executor.submit(task);
   assertEquals(future.get(), BasicTestTask.RESULT);
 }
Пример #2
0
 @Test
 public void testInvokeAllTimeoutCancelled() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("testInvokeAll");
   assertFalse(executor.isShutdown());
   // Only one task
   ArrayList<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
   tasks.add(new CancellationAwareTask(0));
   List<Future<Boolean>> futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), 1);
   assertEquals(futures.get(0).get(), Boolean.TRUE);
   // More tasks
   tasks.clear();
   for (int i = 0; i < COUNT; i++) {
     tasks.add(new CancellationAwareTask(i < 2 ? 0 : 20000));
   }
   futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), COUNT);
   for (int i = 0; i < COUNT; i++) {
     if (i < 2) {
       assertEquals(futures.get(i).get(), Boolean.TRUE);
     } else {
       boolean excepted = false;
       try {
         futures.get(i).get();
       } catch (CancellationException e) {
         excepted = true;
       }
       assertTrue(excepted);
     }
   }
 }
Пример #3
0
 /** Execute a task that is executing something else inside. Nested Execution. */
 @Test(timeout = 10000)
 public void testNestedExecution() throws Exception {
   Callable<String> task = new NestedExecutorTask();
   ExecutorService executor = createSingleNodeExecutorService("testNestedExecution");
   Future future = executor.submit(task);
   future.get();
 }
Пример #4
0
  @Test
  public void testPostregisteredExecutionCallbackCompletableFuture() throws Exception {
    HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance();
    Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original");
    originalField.setAccessible(true);
    HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy);
    NodeEngine nodeEngine = hz.node.nodeEngine;
    ExecutionService es = nodeEngine.getExecutionService();

    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    try {
      Future future =
          executorService.submit(
              new Callable<String>() {
                @Override
                public String call() {
                  try {
                    return "success";
                  } finally {
                    latch1.countDown();
                  }
                }
              });

      final ICompletableFuture completableFuture = es.asCompletableFuture(future);
      latch1.await(30, TimeUnit.SECONDS);

      final AtomicReference reference = new AtomicReference();
      completableFuture.andThen(
          new ExecutionCallback() {
            @Override
            public void onResponse(Object response) {
              reference.set(response);
              latch2.countDown();
            }

            @Override
            public void onFailure(Throwable t) {
              reference.set(t);
              latch2.countDown();
            }
          });

      latch2.await(30, TimeUnit.SECONDS);
      if (reference.get() instanceof Throwable) {
        ((Throwable) reference.get()).printStackTrace();
      }

      assertEquals("success", reference.get());

    } finally {
      executorService.shutdown();
    }
  }
Пример #5
0
  /** Shutting down the cluster should act as the ExecutorService shutdown */
  @Test(expected = RejectedExecutionException.class)
  public void testClusterShutdown() throws Exception {
    ExecutorService executor = createSingleNodeExecutorService("testClusterShutdown");
    shutdownNodeFactory();
    Thread.sleep(2000);

    assertNotNull(executor);
    assertTrue(executor.isShutdown());
    assertTrue(executor.isTerminated());

    // New tasks must be rejected
    Callable<String> task = new BasicTestTask();
    executor.submit(task);
  }
Пример #6
0
 /** Test for the issue 129. Repeatedly runs tasks and check for isDone() status after get(). */
 @Test
 public void testIsDoneMethod2() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("isDoneMethod2");
   for (int i = 0; i < COUNT; i++) {
     Callable<String> task1 = new BasicTestTask();
     Callable<String> task2 = new BasicTestTask();
     Future future1 = executor.submit(task1);
     Future future2 = executor.submit(task2);
     assertEquals(future2.get(), BasicTestTask.RESULT);
     assertTrue(future2.isDone());
     assertEquals(future1.get(), BasicTestTask.RESULT);
     assertTrue(future1.isDone());
   }
 }
Пример #7
0
 /** Test multiple Future.get() invocation */
 @Test
 public void testMultipleFutureGets() throws Exception {
   Callable<String> task = new BasicTestTask();
   ExecutorService executor = createSingleNodeExecutorService("isTwoGetFromFuture");
   Future<String> future = executor.submit(task);
   String s1 = future.get();
   assertEquals(s1, BasicTestTask.RESULT);
   assertTrue(future.isDone());
   String s2 = future.get();
   assertEquals(s2, BasicTestTask.RESULT);
   assertTrue(future.isDone());
   String s3 = future.get();
   assertEquals(s3, BasicTestTask.RESULT);
   assertTrue(future.isDone());
   String s4 = future.get();
   assertEquals(s4, BasicTestTask.RESULT);
   assertTrue(future.isDone());
 }
Пример #8
0
 @Test
 public void testInvokeAllTimeoutSuccess() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("testInvokeAll");
   assertFalse(executor.isShutdown());
   // Only one task
   ArrayList<Callable<String>> tasks = new ArrayList<Callable<String>>();
   tasks.add(new BasicTestTask());
   List<Future<String>> futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), 1);
   assertEquals(futures.get(0).get(), BasicTestTask.RESULT);
   // More tasks
   tasks.clear();
   for (int i = 0; i < COUNT; i++) {
     tasks.add(new BasicTestTask());
   }
   futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS);
   assertEquals(futures.size(), COUNT);
   for (int i = 0; i < COUNT; i++) {
     assertEquals(futures.get(i).get(), BasicTestTask.RESULT);
   }
 }
Пример #9
0
  @Test
  public void testCancellationAwareTask2() {
    Callable task1 = new CancellationAwareTask(5000);
    ExecutorService executor = createSingleNodeExecutorService("testCancellationAwareTask", 1);
    executor.submit(task1);

    Callable task2 = new BasicTestTask();
    Future future = executor.submit(task2);
    assertFalse(future.isDone());
    assertTrue(future.cancel(true));
    assertTrue(future.isCancelled());
    assertTrue(future.isDone());

    try {
      future.get();
      fail("Should not complete the task successfully");
    } catch (CancellationException expected) {
    } catch (Exception e) {
      fail("Unexpected exception " + e);
    }
  }
Пример #10
0
  @Test
  public void testCancellationAwareTask() throws ExecutionException, InterruptedException {
    CancellationAwareTask task = new CancellationAwareTask(5000);
    ExecutorService executor = createSingleNodeExecutorService("testCancellationAwareTask");
    Future future = executor.submit(task);
    try {
      future.get(2, TimeUnit.SECONDS);
      fail("Should throw TimeoutException!");
    } catch (TimeoutException expected) {
    }
    assertFalse(future.isDone());
    assertTrue(future.cancel(true));
    assertTrue(future.isCancelled());
    assertTrue(future.isDone());

    try {
      future.get();
      fail("Should not complete the task successfully");
    } catch (CancellationException expected) {
    } catch (Exception e) {
      fail("Unexpected exception " + e);
    }
  }
Пример #11
0
 /** Shutdown-related method behaviour when the cluster is running */
 @Test
 public void testShutdownBehaviour() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("testShutdownBehaviour");
   // Fresh instance, is not shutting down
   assertFalse(executor.isShutdown());
   assertFalse(executor.isTerminated());
   executor.shutdown();
   assertTrue(executor.isShutdown());
   assertTrue(executor.isTerminated());
   // shutdownNow() should return an empty list and be ignored
   List<Runnable> pending = executor.shutdownNow();
   assertTrue(pending.isEmpty());
   assertTrue(executor.isShutdown());
   assertTrue(executor.isTerminated());
   // awaitTermination() should return immediately false
   try {
     boolean terminated = executor.awaitTermination(60L, TimeUnit.SECONDS);
     assertFalse(terminated);
   } catch (InterruptedException ie) {
     fail("InterruptedException");
   }
   assertTrue(executor.isShutdown());
   assertTrue(executor.isTerminated());
 }
Пример #12
0
 /** Submit a null task must raise a NullPointerException */
 @Test(expected = NullPointerException.class)
 public void submitNullTask() throws Exception {
   ExecutorService executor = createSingleNodeExecutorService("submitNullTask");
   Callable c = null;
   executor.submit(c);
 }
Пример #13
0
  protected void handleCommand(String command) {
    if (command.contains("__")) {
      namespace = command.split("__")[0];
      command = command.substring(command.indexOf("__") + 2);
    }

    if (echo) {
      if (Thread.currentThread().getName().toLowerCase().indexOf("main") < 0)
        println(" [" + Thread.currentThread().getName() + "] " + command);
      else println(command);
    }
    if (command == null || command.startsWith("//")) return;
    command = command.trim();
    if (command == null || command.length() == 0) {
      return;
    }
    String first = command;
    int spaceIndex = command.indexOf(' ');
    String[] argsSplit = command.split(" ");
    String[] args = new String[argsSplit.length];
    for (int i = 0; i < argsSplit.length; i++) {
      args[i] = argsSplit[i].trim();
    }
    if (spaceIndex != -1) {
      first = args[0];
    }
    if (command.startsWith("help")) {
      handleHelp(command);
    } else if (first.startsWith("#") && first.length() > 1) {
      int repeat = Integer.parseInt(first.substring(1));
      long t0 = Clock.currentTimeMillis();
      for (int i = 0; i < repeat; i++) {
        handleCommand(command.substring(first.length()).replaceAll("\\$i", "" + i));
      }
      println("ops/s = " + repeat * 1000 / (Clock.currentTimeMillis() - t0));
      return;
    } else if (first.startsWith("&") && first.length() > 1) {
      final int fork = Integer.parseInt(first.substring(1));
      ExecutorService pool = Executors.newFixedThreadPool(fork);
      final String threadCommand = command.substring(first.length());
      for (int i = 0; i < fork; i++) {
        final int threadID = i;
        pool.submit(
            new Runnable() {
              public void run() {
                String command = threadCommand;
                String[] threadArgs = command.replaceAll("\\$t", "" + threadID).trim().split(" ");
                // TODO &t #4 m.putmany x k
                if ("m.putmany".equals(threadArgs[0]) || "m.removemany".equals(threadArgs[0])) {
                  if (threadArgs.length < 4) {
                    command += " " + Integer.parseInt(threadArgs[1]) * threadID;
                  }
                }
                handleCommand(command);
              }
            });
      }
      pool.shutdown();
      try {
        pool.awaitTermination(60 * 60, TimeUnit.SECONDS); // wait 1h
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (first.startsWith("@")) {
      if (first.length() == 1) {
        println("usage: @<file-name>");
        return;
      }
      File f = new File(first.substring(1));
      println("Executing script file " + f.getAbsolutePath());
      if (f.exists()) {
        try {
          BufferedReader br = new BufferedReader(new FileReader(f));
          String l = br.readLine();
          while (l != null) {
            handleCommand(l);
            l = br.readLine();
          }
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else {
        println("File not found! " + f.getAbsolutePath());
      }
    } else if (command.indexOf(';') != -1) {
      StringTokenizer st = new StringTokenizer(command, ";");
      while (st.hasMoreTokens()) {
        handleCommand(st.nextToken());
      }
      return;
    } else if ("silent".equals(first)) {
      silent = Boolean.parseBoolean(args[1]);
    } else if ("shutdown".equals(first)) {
      hazelcast.getLifecycleService().shutdown();
    } else if ("echo".equals(first)) {
      echo = Boolean.parseBoolean(args[1]);
      println("echo: " + echo);
    } else if ("ns".equals(first)) {
      if (args.length > 1) {
        namespace = args[1];
        println("namespace: " + namespace);
        //                init();
      }
    } else if ("whoami".equals(first)) {
      println(hazelcast.getCluster().getLocalMember());
    } else if ("who".equals(first)) {
      println(hazelcast.getCluster());
    } else if ("jvm".equals(first)) {
      System.gc();
      println("Memory max: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
      println(
          "Memory free: "
              + Runtime.getRuntime().freeMemory() / 1024 / 1024
              + "M "
              + (int) (Runtime.getRuntime().freeMemory() * 100 / Runtime.getRuntime().maxMemory())
              + "%");
      long total = Runtime.getRuntime().totalMemory();
      long free = Runtime.getRuntime().freeMemory();
      println("Used Memory:" + ((total - free) / 1024 / 1024) + "MB");
      println("# procs: " + Runtime.getRuntime().availableProcessors());
      println(
          "OS info: "
              + ManagementFactory.getOperatingSystemMXBean().getArch()
              + " "
              + ManagementFactory.getOperatingSystemMXBean().getName()
              + " "
              + ManagementFactory.getOperatingSystemMXBean().getVersion());
      println(
          "JVM: "
              + ManagementFactory.getRuntimeMXBean().getVmVendor()
              + " "
              + ManagementFactory.getRuntimeMXBean().getVmName()
              + " "
              + ManagementFactory.getRuntimeMXBean().getVmVersion());
    } else if (first.indexOf("ock") != -1 && first.indexOf(".") == -1) {
      handleLock(args);
    } else if (first.indexOf(".size") != -1) {
      handleSize(args);
    } else if (first.indexOf(".clear") != -1) {
      handleClear(args);
    } else if (first.indexOf(".destroy") != -1) {
      handleDestroy(args);
    } else if (first.indexOf(".iterator") != -1) {
      handleIterator(args);
    } else if (first.indexOf(".contains") != -1) {
      handleContains(args);
    } else if (first.indexOf(".stats") != -1) {
      handStats(args);
    } else if ("t.publish".equals(first)) {
      handleTopicPublish(args);
    } else if ("q.offer".equals(first)) {
      handleQOffer(args);
    } else if ("q.take".equals(first)) {
      handleQTake(args);
    } else if ("q.poll".equals(first)) {
      handleQPoll(args);
    } else if ("q.peek".equals(first)) {
      handleQPeek(args);
    } else if ("q.capacity".equals(first)) {
      handleQCapacity(args);
    } else if ("q.offermany".equals(first)) {
      handleQOfferMany(args);
    } else if ("q.pollmany".equals(first)) {
      handleQPollMany(args);
    } else if ("s.add".equals(first)) {
      handleSetAdd(args);
    } else if ("s.remove".equals(first)) {
      handleSetRemove(args);
    } else if ("s.addmany".equals(first)) {
      handleSetAddMany(args);
    } else if ("s.removemany".equals(first)) {
      handleSetRemoveMany(args);
    } else if (first.equals("m.replace")) {
      handleMapReplace(args);
    } else if (first.equalsIgnoreCase("m.putIfAbsent")) {
      handleMapPutIfAbsent(args);
    } else if (first.equals("m.putAsync")) {
      handleMapPutAsync(args);
    } else if (first.equals("m.getAsync")) {
      handleMapGetAsync(args);
    } else if (first.equals("m.put")) {
      handleMapPut(args);
    } else if (first.equals("m.get")) {
      handleMapGet(args);
    } else if (first.equalsIgnoreCase("m.getMapEntry")) {
      handleMapGetMapEntry(args);
    } else if (first.equals("m.remove")) {
      handleMapRemove(args);
    } else if (first.equals("m.evict")) {
      handleMapEvict(args);
    } else if (first.equals("m.putmany") || first.equalsIgnoreCase("m.putAll")) {
      handleMapPutMany(args);
    } else if (first.equals("m.getmany")) {
      handleMapGetMany(args);
    } else if (first.equals("m.removemany")) {
      handleMapRemoveMany(args);
    } else if (command.equalsIgnoreCase("m.localKeys")) {
      handleMapLocalKeys();
    } else if (command.equals("m.keys")) {
      handleMapKeys();
    } else if (command.equals("m.values")) {
      handleMapValues();
    } else if (command.equals("m.entries")) {
      handleMapEntries();
    } else if (first.equals("m.lock")) {
      handleMapLock(args);
    } else if (first.equalsIgnoreCase("m.tryLock")) {
      handleMapTryLock(args);
    } else if (first.equals("m.unlock")) {
      handleMapUnlock(args);
    } else if (first.indexOf(".addListener") != -1) {
      handleAddListener(args);
    } else if (first.equals("m.removeMapListener")) {
      handleRemoveListener(args);
    } else if (first.equals("m.unlock")) {
      handleMapUnlock(args);
    } else if (first.equals("l.add")) {
      handleListAdd(args);
    } else if (first.equals("l.set")) {
      handleListSet(args);
    } else if ("l.addmany".equals(first)) {
      handleListAddMany(args);
    } else if (first.equals("l.remove")) {
      handleListRemove(args);
    } else if (first.equals("l.contains")) {
      handleListContains(args);
    } else if ("a.get".equals(first)) {
      handleAtomicNumberGet(args);
    } else if ("a.set".equals(first)) {
      handleAtomicNumberSet(args);
    } else if ("a.inc".equals(first)) {
      handleAtomicNumberInc(args);
    } else if ("a.dec".equals(first)) {
      handleAtomicNumberDec(args);
      //        } else if (first.equals("execute")) {
      //            execute(args);
    } else if (first.equals("partitions")) {
      handlePartitions(args);
      //        } else if (first.equals("txn")) {
      //            hazelcast.getTransaction().begin();
      //        } else if (first.equals("commit")) {
      //            hazelcast.getTransaction().commit();
      //        } else if (first.equals("rollback")) {
      //            hazelcast.getTransaction().rollback();
      //        } else if (first.equalsIgnoreCase("executeOnKey")) {
      //            executeOnKey(args);
      //        } else if (first.equalsIgnoreCase("executeOnMember")) {
      //            executeOnMember(args);
      //        } else if (first.equalsIgnoreCase("executeOnMembers")) {
      //            executeOnMembers(args);
      //        } else if (first.equalsIgnoreCase("longOther") ||
      // first.equalsIgnoreCase("executeLongOther")) {
      //            executeLongTaskOnOtherMember(args);
      //        } else if (first.equalsIgnoreCase("long") || first.equalsIgnoreCase("executeLong"))
      // {
      //            executeLong(args);
    } else if (first.equalsIgnoreCase("instances")) {
      handleInstances(args);
    } else if (first.equalsIgnoreCase("quit") || first.equalsIgnoreCase("exit")) {
      System.exit(0);
    } else {
      println("type 'help' for help");
    }
  }