예제 #1
0
  @Test
  public void testDestroyTopicRemovesStatistics() {
    String randomTopicName = randomString();

    HazelcastInstance instance = createHazelcastInstance();
    final ITopic<String> topic = instance.getTopic(randomTopicName);
    topic.publish("foobar");

    // we need to give the message the chance to be processed, else the topic statistics are
    // recreated
    // so in theory the destroy for the topic is broken
    sleepSeconds(1);

    topic.destroy();

    final TopicService topicService =
        getNode(instance).nodeEngine.getService(TopicService.SERVICE_NAME);

    assertTrueEventually(
        new AssertTask() {
          @Override
          public void run() {
            boolean containsStats = topicService.getStatsMap().containsKey(topic.getName());
            assertFalse(containsStats);
          }
        });
  }
예제 #2
0
  @Test(timeout = 120000)
  public void testIssue991EvictedNullIssue() throws InterruptedException {
    MapStoreConfig mapStoreConfig = new MapStoreConfig();
    mapStoreConfig.setEnabled(true);
    mapStoreConfig.setImplementation(
        new MapLoader<String, String>() {
          @Override
          public String load(String key) {
            return null;
          }

          @Override
          public Map<String, String> loadAll(Collection<String> keys) {
            return null;
          }

          @Override
          public Set<String> loadAllKeys() {
            return null;
          }
        });
    Config config = getConfig();
    config.getMapConfig("testIssue991EvictedNullIssue").setMapStoreConfig(mapStoreConfig);
    HazelcastInstance hc = createHazelcastInstance(config);
    IMap<Object, Object> map = hc.getMap("testIssue991EvictedNullIssue");
    map.get("key");
    assertNull(map.get("key"));
    map.put("key", "value");
    Thread.sleep(2000);
    assertEquals("value", map.get("key"));
  }
예제 #3
0
  @Test(timeout = 120000)
  public void testMapStoreNotCalledFromEntryProcessorBackup() throws Exception {
    final String mapName = "testMapStoreNotCalledFromEntryProcessorBackup_" + randomString();
    final int instanceCount = 2;
    Config config = getConfig();
    // Configure map with one backup and dummy map store
    MapConfig mapConfig = config.getMapConfig(mapName);
    mapConfig.setBackupCount(1);
    MapStoreConfig mapStoreConfig = new MapStoreConfig();
    MapStoreWithStoreCount mapStore = new MapStoreWithStoreCount(1, 120);
    mapStoreConfig.setImplementation(mapStore);
    mapConfig.setMapStoreConfig(mapStoreConfig);

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(instanceCount);
    HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config);
    HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config);

    final IMap<String, String> map = instance1.getMap(mapName);
    final String key = "key";
    final String value = "value";
    // executeOnKey
    map.executeOnKey(key, new ValueSetterEntryProcessor(value));
    mapStore.awaitStores();

    assertEquals(value, map.get(key));
    assertEquals(1, mapStore.getCount());
  }
예제 #4
0
  @Test(timeout = 120000)
  public void testSlowStore() throws Exception {
    final TestMapStore store = new WaitingOnFirstTestMapStore();
    Config config = getConfig();
    MapStoreConfig mapStoreConfig = new MapStoreConfig();
    mapStoreConfig.setEnabled(true);
    mapStoreConfig.setWriteDelaySeconds(1);
    mapStoreConfig.setImplementation(store);
    config.getMapConfig("default").setMapStoreConfig(mapStoreConfig);
    HazelcastInstance h1 = createHazelcastInstance(config);
    final IMap<Integer, Integer> map = h1.getMap("testSlowStore");
    int count = 1000;
    for (int i = 0; i < count; i++) {
      map.put(i, 1);
    }
    Thread.sleep(2000); // sleep for scheduling following puts to a different second
    for (int i = 0; i < count; i++) {
      map.put(i, 2);
    }
    for (int i = 0; i < count; i++) {
      final int index = i;
      assertTrueEventually(
          new AssertTask() {
            @Override
            public void run() throws Exception {
              final Integer valueInMap = map.get(index);
              final Integer valueInStore = (Integer) store.getStore().get(index);

              assertEquals(valueInMap, valueInStore);
            }
          });
    }
  }
예제 #5
0
 @Test(timeout = 120000)
 public void testIssue583MapReplaceShouldTriggerMapStore() {
   final ConcurrentMap<String, Long> store = new ConcurrentHashMap<String, Long>();
   final MapStore<String, Long> myMapStore = new SimpleMapStore<String, Long>(store);
   Config config = getConfig();
   config
       .getMapConfig("myMap")
       .setMapStoreConfig(new MapStoreConfig().setImplementation(myMapStore));
   TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);
   HazelcastInstance hc = nodeFactory.newHazelcastInstance(config);
   IMap<String, Long> myMap = hc.getMap("myMap");
   myMap.put("one", 1L);
   assertEquals(1L, myMap.get("one").longValue());
   assertEquals(1L, store.get("one").longValue());
   myMap.putIfAbsent("two", 2L);
   assertEquals(2L, myMap.get("two").longValue());
   assertEquals(2L, store.get("two").longValue());
   myMap.putIfAbsent("one", 5L);
   assertEquals(1L, myMap.get("one").longValue());
   assertEquals(1L, store.get("one").longValue());
   myMap.replace("one", 1L, 111L);
   assertEquals(111L, myMap.get("one").longValue());
   assertEquals(111L, store.get("one").longValue());
   myMap.replace("one", 1L);
   assertEquals(1L, myMap.get("one").longValue());
   assertEquals(1L, store.get("one").longValue());
 }
예제 #6
0
  // ignored due to: https://github.com/hazelcast/hazelcast/issues/5035
  @Ignore
  @Test
  public void testMapLoaderLoadUpdatingIndex() throws Exception {
    final int nodeCount = 3;
    String mapName = randomString();
    SampleIndexableObjectMapLoader loader = new SampleIndexableObjectMapLoader();

    Config config = createMapConfig(mapName, loader);

    NodeBuilder nodeBuilder = new NodeBuilder(nodeCount, config).build();
    HazelcastInstance node = nodeBuilder.getRandomNode();

    IMap<Integer, SampleIndexableObject> map = node.getMap(mapName);
    for (int i = 0; i < 10; i++) {
      map.put(i, new SampleIndexableObject("My-" + i, i));
    }

    final SqlPredicate predicate = new SqlPredicate("name='My-5'");
    assertPredicateResultCorrect(map, predicate);

    map.destroy();
    loader.preloadValues = true;

    node = nodeBuilder.getRandomNode();
    map = node.getMap(mapName);

    assertLoadAllKeysCount(loader, 1);
    assertPredicateResultCorrect(map, predicate);
  }
  @Test
  public void clientsConsume_withNodeShutdown() throws InterruptedException {

    final int initial = 2000, max = 8000;

    for (int i = 0; i < initial; i++) {
      cluster.getRandomNode().getQueue("Q1").offer(i);
      cluster.getRandomNode().getQueue("Q2").offer(i);
    }

    int expectCount = 0;
    for (int i = initial; i < max; i++) {

      if (i == max / 2) {
        cluster.shutdownRandomNode();
      }
      final int index = i;

      assertExactlyOneSuccessfulRun(
          new AssertTask() {
            @Override
            public void run() throws Exception {
              assertTrue(cluster.getRandomNode().getQueue("Q1").offer(index));
            }
          });

      assertExactlyOneSuccessfulRun(
          new AssertTask() {
            @Override
            public void run() throws Exception {
              assertTrue(cluster.getRandomNode().getQueue("Q2").offer(index));
            }
          });

      final int expected = expectCount;

      assertExactlyOneSuccessfulRun(
          new AssertTask() {
            @Override
            public void run() throws Exception {
              assertEquals(expected, client1.getQueue("Q1").poll());
            }
          });

      assertExactlyOneSuccessfulRun(
          new AssertTask() {
            @Override
            public void run() throws Exception {
              assertEquals(expected, client2.getQueue("Q2").poll());
            }
          });

      expectCount++;
    }

    for (int i = expectCount; i < max; i++) {
      assertEquals(i, client1.getQueue("Q1").poll());
      assertEquals(i, client2.getQueue("Q2").poll());
    }
  }
예제 #8
0
  @Test(timeout = 30000)
  public void testNullFromObjectCombiner() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    JobTracker jobTracker = h1.getJobTracker("default");
    Job<Integer, Integer> job = jobTracker.newJob(KeyValueSource.fromMap(m1));
    JobCompletableFuture<Map<String, BigInteger>> future =
        job.chunkSize(1)
            .mapper(new GroupingTestMapper())
            .combiner(new ObjectCombinerFactory())
            .reducer(new ObjectReducerFactory())
            .submit();

    int[] expectedResults = new int[4];
    for (int i = 0; i < 100; i++) {
      int index = i % 4;
      expectedResults[index] += i;
    }

    Map<String, BigInteger> map = future.get();
    for (int i = 0; i < 4; i++) {
      assertEquals(BigInteger.valueOf(expectedResults[i]), map.get(String.valueOf(i)));
    }
  }
예제 #9
0
  @Test(timeout = 30000)
  public void testDataSerializableIntermediateObject() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    JobTracker jobTracker = h1.getJobTracker("default");
    Job<Integer, Integer> job = jobTracker.newJob(KeyValueSource.fromMap(m1));
    ICompletableFuture<Integer> future =
        job.mapper(new TestMapper())
            .combiner(new DataSerializableIntermediateCombinerFactory())
            .reducer(new DataSerializableIntermediateReducerFactory())
            .submit(new DataSerializableIntermediateCollator());

    // Precalculate result
    int expectedResult = 0;
    for (int i = 0; i < 100; i++) {
      expectedResult += i;
    }
    expectedResult = (int) ((double) expectedResult / 100);

    assertEquals(expectedResult, (int) future.get());
  }
예제 #10
0
  @Test(timeout = 30000)
  public void testMapperReducerCollator() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    JobTracker tracker = h1.getJobTracker("default");
    Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
    ICompletableFuture<Integer> future =
        job.mapper(new GroupingTestMapper())
            .reducer(new TestReducerFactory())
            .submit(new TestCollator());

    int result = future.get();

    // Precalculate result
    int expectedResult = 0;
    for (int i = 0; i < 100; i++) {
      expectedResult += i;
    }

    for (int i = 0; i < 4; i++) {
      assertEquals(expectedResult, result);
    }
  }
예제 #11
0
  @Test(timeout = 30000)
  public void testPartitionPostpone() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    final HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    final HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    final HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    assertClusterSizeEventually(3, h1);

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    JobTracker tracker = h1.getJobTracker("default");
    KeyValueSource<Integer, Integer> kvs = KeyValueSource.fromMap(m1);
    KeyValueSource<Integer, Integer> wrapper = new MapKeyValueSourceAdapter<Integer, Integer>(kvs);
    Job<Integer, Integer> job = tracker.newJob(wrapper);
    ICompletableFuture<Map<String, List<Integer>>> future = job.mapper(new TestMapper()).submit();

    Map<String, List<Integer>> result = future.get();

    assertEquals(100, result.size());
    for (List<Integer> value : result.values()) {
      assertEquals(1, value.size());
    }
  }
예제 #12
0
  @Test(timeout = 30000)
  public void testMapperReducer() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    JobTracker tracker = h1.getJobTracker("default");
    Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
    ICompletableFuture<Map<String, Integer>> future =
        job.mapper(new GroupingTestMapper()).reducer(new TestReducerFactory()).submit();

    Map<String, Integer> result = future.get();

    // Precalculate results
    int[] expectedResults = new int[4];
    for (int i = 0; i < 100; i++) {
      int index = i % 4;
      expectedResults[index] += i;
    }

    for (int i = 0; i < 4; i++) {
      assertEquals(expectedResults[i], (int) result.get(String.valueOf(i)));
    }
  }
예제 #13
0
  @Test(timeout = 30000, expected = CancellationException.class)
  public void testInProcessCancellation() throws Exception {

    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);

    final HazelcastInstance h1 = nodeFactory.newHazelcastInstance();
    final HazelcastInstance h2 = nodeFactory.newHazelcastInstance();
    final HazelcastInstance h3 = nodeFactory.newHazelcastInstance();

    assertClusterSizeEventually(3, h1);

    IMap<Integer, Integer> m1 = h1.getMap(MAP_NAME);
    for (int i = 0; i < 100; i++) {
      m1.put(i, i);
    }

    JobTracker tracker = h1.getJobTracker("default");
    Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
    ICompletableFuture<Map<String, List<Integer>>> future =
        job.mapper(new TimeConsumingMapper()).submit();

    future.cancel(true);

    try {
      Map<String, List<Integer>> result = future.get();
      fail();

    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }
예제 #14
0
  @Test
  public void testTopicStats() throws InterruptedException {
    String topicName = "testTopicStats" + generateRandomString(5);

    HazelcastInstance instance = createHazelcastInstance();
    ITopic<String> topic = instance.getTopic(topicName);

    final CountDownLatch latch1 = new CountDownLatch(1000);
    topic.addMessageListener(
        new MessageListener<String>() {
          public void onMessage(Message msg) {
            latch1.countDown();
          }
        });

    final CountDownLatch latch2 = new CountDownLatch(1000);
    topic.addMessageListener(
        new MessageListener<String>() {
          public void onMessage(Message msg) {
            latch2.countDown();
          }
        });

    for (int i = 0; i < 1000; i++) {
      topic.publish("sancar");
    }
    assertTrue(latch1.await(1, TimeUnit.MINUTES));
    assertTrue(latch2.await(1, TimeUnit.MINUTES));

    LocalTopicStatsImpl stats = (LocalTopicStatsImpl) topic.getLocalTopicStats();
    assertEquals(1000, stats.getPublishOperationCount());
    assertEquals(2000, stats.getReceiveOperationCount());
  }
  @Before
  public void setupCluster() {
    Config config = new Config();
    config.addRingBufferConfig(
        new RingbufferConfig("when*").setCapacity(100).setTimeToLiveSeconds(5));
    hazelcastFactory.newHazelcastInstance(config);
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.addReliableTopicConfig(
        new ClientReliableTopicConfig("whenError_*")
            .setTopicOverloadPolicy(TopicOverloadPolicy.ERROR));
    clientConfig.addReliableTopicConfig(
        new ClientReliableTopicConfig("whenDiscardOldest_*")
            .setTopicOverloadPolicy(TopicOverloadPolicy.DISCARD_OLDEST));
    clientConfig.addReliableTopicConfig(
        new ClientReliableTopicConfig("whenDiscardNewest_*")
            .setTopicOverloadPolicy(TopicOverloadPolicy.DISCARD_NEWEST));
    clientConfig.addReliableTopicConfig(
        new ClientReliableTopicConfig("whenBlock_*")
            .setTopicOverloadPolicy(TopicOverloadPolicy.BLOCK));
    HazelcastInstance client = hazelcastFactory.newHazelcastClient(clientConfig);

    serializationService = ((HazelcastClientProxy) client).getSerializationService();

    String topicName = getTestMethodName();
    topic = client.<String>getReliableTopic(topicName);

    ringbuffer = ((ClientReliableTopicProxy<String>) topic).getRingbuffer();
  }
예제 #16
0
  @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
  public void testRemovedEntry_shouldNotBeReached_afterMigration() throws Exception {
    String mapName = randomMapName();
    TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(2);
    MapStoreTest.SimpleMapStore<Integer, Integer> store =
        new MapStoreTest.SimpleMapStore<Integer, Integer>();
    store.store.put(1, 0);

    Config config = createConfig(mapName, store);
    HazelcastInstance node1 = factory.newHazelcastInstance(config);

    IMap<Integer, Integer> map = node1.getMap(mapName);

    map.put(1, 1);
    map.delete(1);

    HazelcastInstance node2 = factory.newHazelcastInstance(config);

    map = node2.getMap(mapName);

    Integer value = map.get(1);
    factory.shutdownAll();

    assertNull(value);
  }
예제 #18
0
  @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());
  }
예제 #19
0
  @Test
  public void setMapStoreConfigImplementationTest() {
    String mapName = "mapStoreImpObjTest";
    String xml =
        "<hazelcast xmlns=\"http://www.hazelcast.com/schema/config\">\n"
            + "<map name=\""
            + mapName
            + "\">\n"
            + "<map-store enabled=\"true\">\n"
            + "<class-name>com.hazelcast.config.helpers.DummyMapStore</class-name>\n"
            + "<write-delay-seconds>5</write-delay-seconds>\n"
            + "</map-store>\n"
            + "</map>\n"
            + "</hazelcast>\n";

    Config config = buildConfig(xml);
    HazelcastInstance hz = createHazelcastInstance(config);
    hz.getMap(mapName);

    MapConfig mapConfig = hz.getConfig().getMapConfig(mapName);
    MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
    Object o = mapStoreConfig.getImplementation();

    assertNotNull(o);
    assertTrue(o instanceof DummyMapStore);
  }
예제 #20
0
  @Test
  public void testStats() throws InterruptedException {
    factory.newHazelcastInstance();
    HazelcastInstance hz = factory.newHazelcastClient();
    final ILock lock = hz.getLock(randomName());

    lock.lock();
    assertTrue(lock.isLocked());
    assertTrue(lock.isLockedByCurrentThread());
    assertEquals(1, lock.getLockCount());

    lock.unlock();
    assertFalse(lock.isLocked());
    assertEquals(0, lock.getLockCount());
    assertEquals(-1L, lock.getRemainingLeaseTime());

    lock.lock(1, TimeUnit.MINUTES);
    assertTrue(lock.isLocked());
    assertTrue(lock.isLockedByCurrentThread());
    assertEquals(1, lock.getLockCount());
    assertTrue(lock.getRemainingLeaseTime() > 1000 * 30);

    final CountDownLatch latch = new CountDownLatch(1);
    new Thread() {
      public void run() {
        assertTrue(lock.isLocked());
        assertFalse(lock.isLockedByCurrentThread());
        assertEquals(1, lock.getLockCount());
        assertTrue(lock.getRemainingLeaseTime() > 1000 * 30);
        latch.countDown();
      }
    }.start();
    assertTrue(latch.await(1, TimeUnit.MINUTES));
  }
  @Setup
  public void setup(TestContext testContext) {
    HazelcastInstance hazelcastInstance = testContext.getTargetInstance();
    results = hazelcastInstance.getList(basename);
    listeners = hazelcastInstance.getList(basename + "listeners");

    cache = CacheUtils.getCache(hazelcastInstance, basename);
    listener = new ICacheEntryListener<Integer, Long>();
    filter = new ICacheEntryEventFilter<Integer, Long>();

    CacheEntryListenerConfiguration<Integer, Long> config =
        new MutableCacheEntryListenerConfiguration<Integer, Long>(
            FactoryBuilder.factoryOf(listener),
            FactoryBuilder.factoryOf(filter),
            false,
            syncEvents);
    cache.registerCacheEntryListener(config);

    builder
        .addOperation(Operation.PUT, put)
        .addOperation(Operation.PUT_EXPIRY, putExpiry)
        .addOperation(Operation.PUT_EXPIRY_ASYNC, putAsyncExpiry)
        .addOperation(Operation.GET_EXPIRY, getExpiry)
        .addOperation(Operation.GET_EXPIRY_ASYNC, getAsyncExpiry)
        .addOperation(Operation.REMOVE, remove)
        .addOperation(Operation.REPLACE, replace);
  }
예제 #22
0
  @Test
  public void testLockTtl() throws Exception {
    factory.newHazelcastInstance();
    HazelcastInstance hz = factory.newHazelcastClient();
    final ILock lock = hz.getLock(randomName());

    lock.lock(3, TimeUnit.SECONDS);
    final CountDownLatch latch = new CountDownLatch(2);
    new Thread() {
      public void run() {
        if (!lock.tryLock()) {
          latch.countDown();
        }
        try {
          if (lock.tryLock(5, TimeUnit.SECONDS)) {
            latch.countDown();
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    lock.forceUnlock();
  }
예제 #23
0
  @Test(timeout = 120000)
  public void testInitialLoadModeEagerMultipleThread() {
    final String mapName = "default";
    final int instanceCount = 2;
    final int size = 10000;
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(instanceCount);
    final CountDownLatch countDownLatch = new CountDownLatch(instanceCount - 1);
    final Config config = getConfig();
    GroupConfig groupConfig = new GroupConfig("testEager");
    config.setGroupConfig(groupConfig);
    MapStoreConfig mapStoreConfig = new MapStoreConfig();
    mapStoreConfig.setEnabled(true);
    mapStoreConfig.setImplementation(new SimpleMapLoader(size, true));
    mapStoreConfig.setInitialLoadMode(MapStoreConfig.InitialLoadMode.EAGER);
    config.getMapConfig(mapName).setMapStoreConfig(mapStoreConfig);

    HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config);
    Runnable runnable =
        new Runnable() {
          public void run() {
            HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config);
            final IMap<Object, Object> map = instance2.getMap(mapName);
            assertEquals(size, map.size());
            countDownLatch.countDown();
          }
        };
    new Thread(runnable).start();

    assertOpenEventually(countDownLatch, 120);
    IMap map = instance1.getMap(mapName);
    assertEquals(size, map.size());
  }
  private void testHitsAndLastAccessTimeAreSetWithSingleNode(Config config) throws Exception {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1);
    final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config);

    final ReplicatedMap<Integer, Integer> map = instance1.getReplicatedMap(randomMapName());
    final int operations = 100;
    execute(
        new Runnable() {
          @Override
          public void run() {
            for (int i = 0; i < operations; i++) {
              map.put(i, i);
            }
          }
        },
        ADDED,
        operations,
        1,
        map);

    for (int i = 0; i < operations; i++) {
      map.containsKey(i);
    }

    for (int i = 0; i < operations; i++) {
      final ReplicatedRecord<Integer, Integer> replicatedRecord = getReplicatedRecord(map, i);
      assertEquals(1, replicatedRecord.getHits());
      assertTrue(
          "Last access time should be set for " + i, replicatedRecord.getLastAccessTime() > 0);
    }
  }
예제 #25
0
  @Test(timeout = 120000)
  public void testOneMemberFlush() throws Exception {
    TestMapStore testMapStore = new TestMapStore(1, 1, 1);
    testMapStore.setLoadAllKeys(false);
    int size = 100;
    Config config = newConfig(testMapStore, 200);
    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3);
    HazelcastInstance h1 = nodeFactory.newHazelcastInstance(config);
    IMap map = h1.getMap("default");
    assertEquals(0, map.size());
    for (int i = 0; i < size; i++) {
      map.put(i, i);
    }
    assertEquals(size, map.size());
    assertEquals(0, testMapStore.getStore().size());
    assertEquals(size, map.getLocalMapStats().getDirtyEntryCount());
    map.flush();
    assertEquals(size, testMapStore.getStore().size());
    assertEquals(0, map.getLocalMapStats().getDirtyEntryCount());
    assertEquals(size, map.size());

    for (int i = 0; i < size / 2; i++) {
      map.remove(i);
    }
    assertEquals(size / 2, map.size());
    assertEquals(size, testMapStore.getStore().size());
    map.flush();
    assertEquals(size / 2, testMapStore.getStore().size());
    assertEquals(size / 2, map.size());
  }
예제 #26
0
  @Test
  public void testHeartbeatResumedEvent() throws InterruptedException {
    hazelcastFactory.newHazelcastInstance();
    HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig());
    final HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();

    // make sure client is connected to instance2
    String keyOwnedByInstance2 = generateKeyOwnedBy(instance2);
    IMap<String, String> map = client.getMap(randomString());
    map.put(keyOwnedByInstance2, randomString());

    HazelcastClientInstanceImpl clientImpl = getHazelcastClientInstanceImpl(client);
    ClientConnectionManager connectionManager = clientImpl.getConnectionManager();
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    connectionManager.addConnectionHeartbeatListener(
        new ConnectionHeartbeatListener() {
          @Override
          public void heartbeatResumed(Connection connection) {
            assertEquals(
                instance2.getCluster().getLocalMember().getAddress(), connection.getEndPoint());
            countDownLatch.countDown();
          }

          @Override
          public void heartbeatStopped(Connection connection) {}
        });

    blockMessagesFromInstance(instance2, client);
    sleepMillis(HEARTBEAT_TIMEOUT_MILLIS * 2);
    unblockMessagesFromInstance(instance2, client);

    assertOpenEventually(countDownLatch);
  }
예제 #27
0
  @Test(timeout = 120000)
  public void testIssue1142ExceptionWhenLoadAllReturnsNull() {
    Config config = getConfig();
    String mapname = "testIssue1142ExceptionWhenLoadAllReturnsNull";
    MapStoreConfig mapStoreConfig = new MapStoreConfig();
    mapStoreConfig.setImplementation(
        new MapStoreAdapter<String, String>() {
          @Override
          public Set<String> loadAllKeys() {
            Set keys = new HashSet();
            keys.add("key");
            return keys;
          }

          public Map loadAll(Collection keys) {
            return null;
          }
        });
    config.getMapConfig(mapname).setMapStoreConfig(mapStoreConfig);
    TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    HazelcastInstance instance = nodeFactory.newHazelcastInstance(config);
    HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config);
    final IMap map = instance.getMap(mapname);
    for (int i = 0; i < 300; i++) {
      map.put(i, i);
    }
    assertEquals(300, map.size());
  }
예제 #28
0
  private void multicastJoin(int count, final boolean sleep) throws InterruptedException {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(count);

    final Config config = new Config();
    config.setProperty("hazelcast.wait.seconds.before.join", "5");
    config.getNetworkConfig().getJoin().getMulticastConfig().setMulticastTimeoutSeconds(25);
    final ConcurrentMap<Integer, HazelcastInstance> map =
        new ConcurrentHashMap<Integer, HazelcastInstance>();
    final CountDownLatch latch = new CountDownLatch(count);
    final ExecutorService ex = Executors.newCachedThreadPool();
    for (int i = 0; i < count; i++) {
      final int index = i;
      ex.execute(
          new Runnable() {
            public void run() {
              if (sleep) {
                try {
                  Thread.sleep((int) (1000 * Math.random()));
                } catch (InterruptedException ignored) {
                }
              }
              HazelcastInstance h = nodeFactory.newHazelcastInstance(config);
              map.put(index, h);
              latch.countDown();
            }
          });
    }
    assertOpenEventually(latch);
    for (HazelcastInstance h : map.values()) {
      assertEquals(count, h.getCluster().getMembers().size());
    }
    ex.shutdown();
  }
예제 #29
0
  @Test(timeout = 120000)
  public void testMapStoreWriteRemoveOrder() {
    final String mapName = randomMapName("testMapStoreWriteDeleteOrder");
    final int numIterations = 10;
    final int writeDelaySeconds = 3;
    // create map store implementation
    final RecordingMapStore store = new RecordingMapStore(0, 1);
    // create hazelcast config
    final Config config = newConfig(mapName, store, writeDelaySeconds);
    // start hazelcast instance
    final HazelcastInstance hzInstance = createHazelcastInstance(config);
    // loop over num iterations
    final IMap<String, String> map = hzInstance.getMap(mapName);
    for (int k = 0; k < numIterations; k++) {
      String key = String.valueOf(k + 10); // 2 digits for sorting in output
      String value = "v:" + key;
      // add entry
      map.put(key, value);
      // sleep 300ms
      sleepMillis(1);
      // remove entry
      map.remove(key);
    }
    // wait for store to finish
    store.awaitStores();
    // wait for remove to finish
    store.awaitRemoves();

    assertEquals(0, store.getStore().size());
  }
예제 #30
0
  @Test
  public void addTwoMessageListener() throws InterruptedException {
    String topicName = "addTwoMessageListener" + generateRandomString(5);

    HazelcastInstance instance = createHazelcastInstance();
    ITopic<String> topic = instance.getTopic(topicName);

    final CountDownLatch latch = new CountDownLatch(2);
    final String message = "Hazelcast Rocks!";

    topic.addMessageListener(
        new MessageListener<String>() {
          public void onMessage(Message<String> msg) {
            if (msg.getMessageObject().equals(message)) {
              latch.countDown();
            }
          }
        });
    topic.addMessageListener(
        new MessageListener<String>() {
          public void onMessage(Message<String> msg) {
            if (msg.getMessageObject().equals(message)) {
              latch.countDown();
            }
          }
        });
    topic.publish(message);

    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
  }