@Test
  public void testSubmitToKeyOwnerCallable() throws Exception {
    final int k = simpleTestNodeCount;
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(new Config());
    final AtomicInteger count = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(k / 2);
    final ExecutionCallback callback =
        new ExecutionCallback() {
          public void onResponse(Object response) {
            if ((Boolean) response) count.incrementAndGet();
            latch.countDown();
          }

          public void onFailure(Throwable t) {}
        };
    for (int i = 0; i < k; i++) {
      final HazelcastInstance instance = instances[i];
      final IExecutorService service = instance.getExecutorService("testSubmitToKeyOwnerCallable");
      final String script = "hazelcast.getCluster().getLocalMember().equals(member)";
      final HashMap map = new HashMap();
      final Member localMember = instance.getCluster().getLocalMember();
      map.put("member", localMember);
      int key = 0;
      while (!localMember.equals(instance.getPartitionService().getPartition(++key).getOwner())) ;
      if (i % 2 == 0) {
        final Future f = service.submitToKeyOwner(new ScriptCallable(script, map), key);
        assertTrue((Boolean) f.get(5, TimeUnit.SECONDS));
      } else {
        service.submitToKeyOwner(new ScriptCallable(script, map), key, callback);
      }
    }
    assertTrue(latch.await(30, TimeUnit.SECONDS));
    assertEquals(k / 2, count.get());
  }
  @Test
  public void testSubmitToAllMembersCallable() throws InterruptedException {
    final int k = simpleTestNodeCount;
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(new Config());
    final AtomicInteger count = new AtomicInteger(0);
    final CountDownLatch countDownLatch = new CountDownLatch(k * k);
    final MultiExecutionCallback callback =
        new MultiExecutionCallback() {
          public void onResponse(Member member, Object value) {
            count.incrementAndGet();
            countDownLatch.countDown();
          }

          public void onComplete(Map<Member, Object> values) {}
        };
    for (int i = 0; i < k; i++) {
      final IExecutorService service =
          instances[i].getExecutorService("testSubmitToAllMembersCallable");
      final String script =
          "hazelcast.getAtomicLong('testSubmitToAllMembersCallable').incrementAndGet();";
      service.submitToAllMembers(new ScriptCallable(script, null), callback);
    }
    countDownLatch.await(30, TimeUnit.SECONDS);
    final IAtomicLong result = instances[0].getAtomicLong("testSubmitToAllMembersCallable");
    assertEquals(k * k, result.get());
    assertEquals(k * k, count.get());
  }
  @Test
  public void testSubmitToMemberRunnable() throws InterruptedException {
    final int k = simpleTestNodeCount;
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(new Config());
    final AtomicInteger count = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(k);
    final ExecutionCallback callback =
        new ExecutionCallback() {
          public void onResponse(Object response) {
            if (response == null) {
              count.incrementAndGet();
            }
            latch.countDown();
          }

          public void onFailure(Throwable t) {}
        };
    for (int i = 0; i < k; i++) {
      final HazelcastInstance instance = instances[i];
      final IExecutorService service = instance.getExecutorService("testSubmitToMemberRunnable");
      final String script =
          "if(!hazelcast.getCluster().getLocalMember().equals(member)) "
              + "hazelcast.getAtomicLong('testSubmitToMemberRunnable').incrementAndGet();";
      final HashMap map = new HashMap();
      map.put("member", instance.getCluster().getLocalMember());
      service.submitToMember(
          new ScriptRunnable(script, map), instance.getCluster().getLocalMember(), callback);
    }
    latch.await(10, TimeUnit.SECONDS);
    assertEquals(0, instances[0].getAtomicLong("testSubmitToMemberRunnable").get());
    assertEquals(k, count.get());
  }
 /** Test the method isDone() */
 @Test
 public void testIsDoneMethod() throws Exception {
   Callable<String> task = new BasicTestTask();
   IExecutorService executor = createSingleNodeExecutorService("isDoneMethod");
   Future future = executor.submit(task);
   if (future.isDone()) {
     assertTrue(future.isDone());
   }
   assertEquals(future.get(), BasicTestTask.RESULT);
   assertTrue(future.isDone());
 }
  @Test
  public void hazelcastInstanceAwareAndLocal() throws Exception {
    final Config config = new Config();
    config.addExecutorConfig(new ExecutorConfig("test", 1));
    final HazelcastInstance instance = createHazelcastInstance(config);
    IExecutorService executor = instance.getExecutorService("test");

    HazelcastInstanceAwareRunnable task = new HazelcastInstanceAwareRunnable();
    executor.submit(task).get();
    assertTrue("The setHazelcastInstance should have been called", task.initializeCalled);
  }
 @Test
 public void testSubmitMultipleNode() throws ExecutionException, InterruptedException {
   final int k = simpleTestNodeCount;
   TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
   final HazelcastInstance[] instances = factory.newInstances(new Config());
   for (int i = 0; i < k; i++) {
     final IExecutorService service = instances[i].getExecutorService("testSubmitMultipleNode");
     final String script = "hazelcast.getAtomicLong('testSubmitMultipleNode').incrementAndGet();";
     final Future future = service.submit(new ScriptCallable(script, null));
     assertEquals((long) (i + 1), future.get());
   }
 }
 @Test
 public void testExecuteMultipleNode() throws InterruptedException, ExecutionException {
   final int k = simpleTestNodeCount;
   TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
   final HazelcastInstance[] instances = factory.newInstances(new Config());
   for (int i = 0; i < k; i++) {
     final IExecutorService service = instances[i].getExecutorService("testExecuteMultipleNode");
     final String script = "hazelcast.getAtomicLong('count').incrementAndGet();";
     final int rand = new Random().nextInt(100);
     final Future<Integer> future = service.submit(new ScriptRunnable(script, null), rand);
     assertEquals(Integer.valueOf(rand), future.get());
   }
   final IAtomicLong count = instances[0].getAtomicLong("count");
   assertEquals(k, count.get());
 }
  /** Test the Execution Callback */
  @Test
  public void testExecutionCallback() throws Exception {
    Callable<String> task = new BasicTestTask();
    IExecutorService executor = createSingleNodeExecutorService("testExecutionCallback");
    final CountDownLatch latch = new CountDownLatch(1);
    final ExecutionCallback executionCallback =
        new ExecutionCallback() {
          public void onResponse(Object response) {
            latch.countDown();
          }

          public void onFailure(Throwable t) {}
        };
    executor.submit(task, executionCallback);

    assertTrue(latch.await(2, TimeUnit.SECONDS));
  }
  @Test
  public void testSubmitToMembersRunnable() throws InterruptedException {
    final int k = simpleTestNodeCount;
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(new Config());
    final AtomicInteger count = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(k);
    final MultiExecutionCallback callback =
        new MultiExecutionCallback() {
          public void onResponse(Member member, Object value) {
            count.incrementAndGet();
          }

          public void onComplete(Map<Member, Object> values) {
            latch.countDown();
          }
        };
    int sum = 0;
    final Set<Member> membersSet = instances[0].getCluster().getMembers();
    final Member[] members = membersSet.toArray(new Member[membersSet.size()]);
    final Random random = new Random();
    for (int i = 0; i < k; i++) {
      final IExecutorService service =
          instances[i].getExecutorService("testSubmitToMembersRunnable");
      final String script =
          "hazelcast.getAtomicLong('testSubmitToMembersRunnable').incrementAndGet();";
      final int n = random.nextInt(k) + 1;
      sum += n;
      Member[] m = new Member[n];
      System.arraycopy(members, 0, m, 0, n);
      service.submitToMembers(new ScriptRunnable(script, null), Arrays.asList(m), callback);
    }

    assertTrue(latch.await(30, TimeUnit.SECONDS));
    final IAtomicLong result = instances[0].getAtomicLong("testSubmitToMembersRunnable");
    assertEquals(sum, result.get());
    assertEquals(sum, count.get());
  }
  @Test
  public void testExecutorServiceStats() throws InterruptedException, ExecutionException {
    final IExecutorService executorService =
        createSingleNodeExecutorService("testExecutorServiceStats");
    final int k = 10;
    final CountDownLatch latch = new CountDownLatch(k);
    final int executionTime = 200;
    for (int i = 0; i < k; i++) {
      executorService.execute(
          new Runnable() {
            public void run() {
              try {
                Thread.sleep(executionTime);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              latch.countDown();
            }
          });
    }
    latch.await(2, TimeUnit.MINUTES);

    final Future<Boolean> f = executorService.submit(new CancellationAwareTask(10000));
    Thread.sleep(1000);
    f.cancel(true);
    try {
      f.get();
    } catch (CancellationException e) {
    }

    final LocalExecutorStats stats = executorService.getLocalExecutorStats();
    assertEquals(k + 1, stats.getStartedTaskCount());
    assertEquals(k, stats.getCompletedTaskCount());
    assertEquals(0, stats.getPendingTaskCount());
    assertEquals(1, stats.getCancelledTaskCount());
  }
  @Test
  public void testManagedContextAndLocal() throws Exception {
    final Config config = new Config();
    config.addExecutorConfig(new ExecutorConfig("test", 1));
    config.setManagedContext(
        new ManagedContext() {
          @Override
          public Object initialize(Object obj) {
            if (obj instanceof RunnableWithManagedContext) {
              RunnableWithManagedContext task = (RunnableWithManagedContext) obj;
              task.initializeCalled = true;
            }
            return obj;
          }
        });

    final HazelcastInstance instance = createHazelcastInstance(config);
    IExecutorService executor = instance.getExecutorService("test");

    RunnableWithManagedContext task = new RunnableWithManagedContext();
    executor.submit(task).get();
    assertTrue(
        "The task should have been initialized by the ManagedContext", task.initializeCalled);
  }