@Override
  public boolean addJobToCurrent(Job j) throws Exception {

    IAtomicReference<Job> r = h.getAtomicReference("job-" + j.getWorkerId());

    if (r.get() != null || !r.isNull()) {
      boolean sent = false;
      while (!sent) {
        // always update
        for (String s : workers()) {
          if (jobFor(s) == null) {
            log.info(
                "Redirecting worker "
                    + j.getWorkerId()
                    + " to "
                    + s
                    + " due to work already being allocated");
            r = h.getAtomicReference("job-" + s);
            j.setWorkerId(s);
            sent = true;
          }
        }
      }
    }

    r.set(j);

    // iterate over jobs without the work/data
    j.setWork(null);

    jobs.add(j);

    return true;
  }
Exemplo n.º 2
0
  @Test(expected = HazelcastInstanceNotActiveException.class)
  public void testShutDownNodeWhenOtherWaitingOnConditionAwait() throws InterruptedException {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final HazelcastInstance instance = nodeFactory.newHazelcastInstance(new Config());
    nodeFactory.newHazelcastInstance(new Config());
    final String name = "testShutDownNodeWhenOtherWaitingOnConditionAwait";
    final ILock lock = instance.getLock(name);
    final ICondition condition = lock.newCondition("s");
    final CountDownLatch latch = new CountDownLatch(1);

    new Thread(
            new Runnable() {
              public void run() {
                try {
                  latch.await(1, TimeUnit.MINUTES);
                  Thread.sleep(5000);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                instance.getLifecycleService().shutdown();
              }
            })
        .start();

    lock.lock();
    try {
      latch.countDown();
      condition.await();
    } catch (InterruptedException e) {
    }
    lock.unlock();
  }
Exemplo n.º 3
0
  @Test
  @Category(ProblematicTest.class) // TODO
  public void testLockInterruption() throws InterruptedException {
    Config config = new Config();
    config.setProperty(GroupProperties.PROP_OPERATION_CALL_TIMEOUT_MILLIS, "5000");
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1);
    final HazelcastInstance hz = nodeFactory.newHazelcastInstance(config);

    final Lock lock = hz.getLock("testLockInterruption2");
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  lock.tryLock(60, TimeUnit.SECONDS);
                } catch (InterruptedException ignored) {
                  latch.countDown();
                }
              }
            });
    lock.lock();
    t.start();
    Thread.sleep(2000);
    t.interrupt();
    assertTrue("tryLock() is not interrupted!", latch.await(30, TimeUnit.SECONDS));
    lock.unlock();
    assertTrue("Could not acquire lock!", lock.tryLock());
  }
Exemplo n.º 4
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());
  }
Exemplo n.º 5
0
  @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());
  }
Exemplo n.º 6
0
  @Test
  public void testZeroResetsTTL() throws InterruptedException {
    Config cfg = new Config();
    MapConfig mc = cfg.getMapConfig("testZeroResetsTTL");
    int ttl = 5;
    mc.setTimeToLiveSeconds(ttl);
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(1);
    HazelcastInstance instance = factory.newHazelcastInstance(cfg);
    IMap<Object, Object> map = instance.getMap("testZeroResetsTTL");
    final CountDownLatch latch = new CountDownLatch(1);
    map.addEntryListener(
        new EntryAdapter<Object, Object>() {
          public void entryEvicted(EntryEvent event) {
            latch.countDown();
          }
        },
        false);

    map.put(1, 1);
    map.put(2, 2);
    map.put(1, 2, 0, TimeUnit.SECONDS);
    latch.await(10, TimeUnit.SECONDS);
    assertNull(map.get(2));
    assertEquals(2, map.get(1));
  }
Exemplo n.º 7
0
  private void testLockEviction(boolean localKey) throws Exception {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final Config config = new Config();

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

    warmUpPartitions(instance2, instance1);

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

    final ILock lock = instance1.getLock(key);
    lock.lock(10, TimeUnit.SECONDS);
    assertTrue(lock.getRemainingLeaseTime() > 0);
    Assert.assertTrue(lock.isLocked());

    final CountDownLatch latch = new CountDownLatch(1);
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                final ILock lock = instance2.getLock(key);
                lock.lock();
                latch.countDown();
              }
            });
    t.start();
    Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
  }
Exemplo n.º 8
0
  @Test
  public void testLockCount() 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();
    assertEquals(1, lock.getLockCount());
    assertTrue(lock.tryLock());
    assertEquals(2, lock.getLockCount());

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

    lock.unlock();
    assertEquals(0, lock.getLockCount());
    assertFalse(lock.isLocked());
    assertEquals(-1L, lock.getRemainingLeaseTime());
  }
Exemplo n.º 9
0
  @Test(timeout = 100000)
  public void testLockOwnerDies() throws Exception {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final Config config = new Config();
    final HazelcastInstance lockOwner = nodeFactory.newHazelcastInstance(config);
    final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config);

    final String name = "testLockOwnerDies";
    final ILock lock = lockOwner.getLock(name);
    lock.lock();
    Assert.assertTrue(lock.isLocked());
    final CountDownLatch latch = new CountDownLatch(1);
    Thread t =
        new Thread(
            new Runnable() {
              public void run() {
                final ILock lock = instance1.getLock(name);
                lock.lock();
                latch.countDown();
              }
            });
    t.start();
    lockOwner.getLifecycleService().shutdown();
    Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
  }
Exemplo n.º 10
0
  @Test(timeout = 100000)
  public void testKeyOwnerDies() 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);

    warmUpPartitions(keyOwner, instance1, instance2);
    final String key = generateKeyOwnedBy(keyOwner);
    final ILock lock1 = instance1.getLock(key);
    lock1.lock();

    final CountDownLatch latch = new CountDownLatch(1);
    new Thread(
            new Runnable() {
              public void run() {
                final ILock lock = instance2.getLock(key);
                lock.lock();
                latch.countDown();
              }
            })
        .start();

    Thread.sleep(1000);
    keyOwner.getLifecycleService().shutdown();
    Assert.assertTrue(lock1.isLocked());
    Assert.assertTrue(lock1.isLockedByCurrentThread());
    Assert.assertTrue(lock1.tryLock());
    lock1.unlock();
    lock1.unlock();
    Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
  }
Exemplo n.º 11
0
 @Test(expected = IllegalMonitorStateException.class)
 public void testIllegalUnlock() {
   final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1);
   final HazelcastInstance instance = nodeFactory.newHazelcastInstance(new Config());
   final ILock lock = instance.getLock("testIllegalUnlock");
   lock.unlock();
 }
Exemplo n.º 12
0
  @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();
  }
    public static void main(String[] args) throws Exception {
        HazelcastInstance hz = Hazelcast.newHazelcastInstance();
        Cluster cluster = hz.getCluster();

        cluster.addMembershipListener(new MembershipListener() {
            @Override
            public void memberAdded(MembershipEvent membershipEvent) {
                System.out.println( "********** MemberAdded " + membershipEvent );
            }

            @Override
            public void memberRemoved(MembershipEvent membershipEvent) {
                System.out.println( "********** MemberRemoved " + membershipEvent );
            }

            @Override
            public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
                System.out.println( "********** MemberAttributeChanged " + memberAttributeEvent );
            }
        });
Member localMember = cluster.getLocalMember();
        System.out.println ( "********** my inetAddress= " + localMember.getInetSocketAddress() );


    }
Exemplo n.º 14
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());
  }
Exemplo n.º 15
0
  @Test(expected = DistributedObjectDestroyedException.class)
  public void testDestroyLockWhenOtherWaitingOnConditionAwait() {
    final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2);
    final HazelcastInstance instance = nodeFactory.newHazelcastInstance(new Config());
    final ILock lock = instance.getLock("testDestroyLockWhenOtherWaitingOnConditionAwait");
    final ICondition condition = lock.newCondition("condition");
    final CountDownLatch latch = new CountDownLatch(1);

    new Thread(
            new Runnable() {
              public void run() {
                try {
                  latch.await(30, TimeUnit.SECONDS);
                  Thread.sleep(5000);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
                lock.destroy();
              }
            })
        .start();

    lock.lock();
    try {
      latch.countDown();
      condition.await();
    } catch (InterruptedException e) {
    }
    lock.unlock();
  }
Exemplo n.º 16
0
 @Test(expected = IllegalMonitorStateException.class)
 public void testIllegalConditionUsage2() {
   final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1);
   final HazelcastInstance instance = nodeFactory.newHazelcastInstance(new Config());
   final ILock lock = instance.getLock("testIllegalConditionUsage");
   final ICondition condition = lock.newCondition("condition");
   condition.signal();
 }
  /* github issue #183 */
  @Test
  public void testKeyBasedListeners() throws InterruptedException {
    try {
      Config config = new Config();
      HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
      IMap<String, String> map = instance.getMap("map");
      map.put("key1", "value1");
      map.put("key2", "value2");
      map.put("key3", "value3");

      ClientConfig clientConfig = new ClientConfig();
      HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);

      final AtomicInteger count = new AtomicInteger(0);
      IMap<String, String> clientMap = client.getMap("map");

      clientMap.addEntryListener(
          new EntryListener<String, String>() {
            public void entryAdded(EntryEvent<String, String> entryEvent) {
              count.incrementAndGet();
            }

            public void entryRemoved(EntryEvent<String, String> entryEvent) {}

            public void entryUpdated(EntryEvent<String, String> entryEvent) {
              count.incrementAndGet();
            }

            public void entryEvicted(EntryEvent<String, String> entryEvent) {}
          },
          "key1",
          true);

      clientMap.addEntryListener(
          new EntryListener<String, String>() {
            public void entryAdded(EntryEvent<String, String> entryEvent) {
              count.incrementAndGet();
            }

            public void entryRemoved(EntryEvent<String, String> entryEvent) {}

            public void entryUpdated(EntryEvent<String, String> entryEvent) {
              System.out.println("event map");
              count.incrementAndGet();
            }

            public void entryEvicted(EntryEvent<String, String> entryEvent) {}
          },
          "key2",
          true);

      map.put("key1", "new-value1");
      Thread.sleep(100);
      Assert.assertEquals(count.get(), 1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 18
0
  @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);
  }
Exemplo n.º 19
0
 @Test(expected = IllegalMonitorStateException.class)
 public void testIllegalConditionUsage1() {
   final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(1);
   final HazelcastInstance instance = nodeFactory.newHazelcastInstance(new Config());
   final ILock lock = instance.getLock("testIllegalConditionUsage");
   final ICondition condition = lock.newCondition("condition");
   try {
     condition.await();
   } catch (InterruptedException e) {
   }
 }
Exemplo n.º 20
0
  @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);
  }
Exemplo n.º 21
0
 /**
  * Test for issue 614
  *
  * @throws InterruptedException
  */
 @Test
 public void testContainsKeyShouldDelayEviction() throws InterruptedException {
   Config cfg = new Config();
   String mapname = "testContainsKeyShouldDelayEviction";
   cfg.getMapConfig(mapname).setMaxIdleSeconds(3);
   TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(1);
   HazelcastInstance instance = factory.newHazelcastInstance(cfg);
   IMap<Object, Object> map = instance.getMap(mapname);
   map.put(1, 1);
   for (int i = 0; i < 20; i++) {
     assertTrue(map.containsKey(1));
     Thread.sleep(500);
   }
 }
Exemplo n.º 22
0
 @Test
 @Ignore
 public void testCallState() throws Exception {
   Config config = new Config();
   final HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
   final HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
   final Node node1 = getNode(h1);
   final Node node2 = getNode(h2);
   Thread.sleep(100);
   final CountDownLatch latch = new CountDownLatch(1);
   final IMap imap1 = h1.getMap("default");
   new Thread(
           new Runnable() {
             public void run() {
               imap1.lock("1");
               latch.countDown();
             }
           })
       .start();
   latch.await();
   //        final IMap imap2 = h2.getMap("default");
   final AtomicInteger threadId = new AtomicInteger();
   new Thread(
           new Runnable() {
             public void run() {
               ThreadContext.get().setCurrentFactory(node1.factory);
               threadId.set(ThreadContext.get().getThreadId());
               imap1.put("1", "value1");
             }
           })
       .start();
   Thread.sleep(1000);
   System.out.println(node1.getThisAddress() + " thread " + threadId.get());
   CallState callState1 =
       node1.getSystemLogService().getCallState(node1.getThisAddress(), threadId.get());
   if (callState1 != null) {
     for (Object callStateLog : callState1.getLogs()) {
       System.out.println(callStateLog);
     }
   }
   CallState callState2 =
       node2.getSystemLogService().getCallState(node1.getThisAddress(), threadId.get());
   System.out.println("========================");
   if (callState2 != null) {
     for (Object callStateLog : callState2.getLogs()) {
       System.out.println(callStateLog);
     }
   }
 }
 @Test
 public void testSqlPredicate() {
   HazelcastInstance h = getHazelcastInstance();
   HazelcastClient hClient = getHazelcastClient();
   IMap<Integer, Employee> map = hClient.getMap("testSqlPredicate");
   for (int i = 0; i < 100; i++) {
     h.getMap("testSqlPredicate").put(i, new Employee("" + i, i, i % 2 == 0, i));
   }
   Set<Entry<Integer, Employee>> set = map.entrySet(new SqlPredicate("active AND age < 30"));
   for (Entry<Integer, Employee> entry : set) {
     System.out.println(entry.getValue());
     assertTrue(entry.getValue().age < 30);
     assertTrue(entry.getValue().active);
   }
 }
  @Test
  public void testExecuteOnAllMembers() {
    final IExecutorService service = client.getExecutorService(randomString());
    final String mapName = randomString();

    service.executeOnAllMembers(new MapPutRunnable(mapName));

    final IMap map = client.getMap(mapName);
    assertTrueEventually(
        new AssertTask() {
          public void run() throws Exception {
            assertEquals(CLUSTER_SIZE, map.size());
          }
        });
  }
Exemplo n.º 25
0
  @Test
  public void testListener() throws Exception {
    final int maxItems = 10;
    final CountDownLatch itemAddedLatch = new CountDownLatch(maxItems);
    final CountDownLatch itemRemovedLatch = new CountDownLatch(maxItems);

    final IQueue queue = client.getQueue(randomString());

    String id =
        queue.addItemListener(
            new ItemListener() {

              public void itemAdded(ItemEvent itemEvent) {
                itemAddedLatch.countDown();
              }

              public void itemRemoved(ItemEvent item) {
                itemRemovedLatch.countDown();
              }
            },
            true);

    new Thread() {
      public void run() {
        for (int i = 0; i < maxItems; i++) {
          queue.offer(i);
          queue.remove(i);
        }
      }
    }.start();

    assertTrue(itemAddedLatch.await(5, TimeUnit.SECONDS));
    assertTrue(itemRemovedLatch.await(5, TimeUnit.SECONDS));
    queue.removeItemListener(id);
  }
Exemplo n.º 26
0
 /*
    github issue 585
 */
 @Test
 public void testIssue585ZeroTTLShouldPreventEvictionWithSet() throws InterruptedException {
   Config config = new Config();
   config.getGroupConfig().setName("testIssue585ZeroTTLShouldPreventEvictionWithSet");
   NearCacheConfig nearCacheConfig = new NearCacheConfig();
   config.getMapConfig("default").setNearCacheConfig(nearCacheConfig);
   int n = 1;
   TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n);
   HazelcastInstance h = factory.newHazelcastInstance(config);
   IMap<String, String> map = h.getMap("testIssue585ZeroTTLShouldPreventEvictionWithSet");
   map.set("key", "value", 1, TimeUnit.SECONDS);
   map.set("key", "value2", 0, TimeUnit.SECONDS);
   Thread.sleep(2000);
   assertEquals("value2", map.get("key"));
   h.getLifecycleService().shutdown();
 }
Exemplo n.º 27
0
 @SuppressWarnings("LockAcquiredButNotSafelyReleased")
 protected void handleLock(String[] args) {
   String lockStr = args[0];
   String key = args[1];
   Lock lock = hazelcast.getLock(key);
   if (lockStr.equalsIgnoreCase("lock")) {
     lock.lock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("unlock")) {
     lock.unlock();
     println("true");
   } else if (lockStr.equalsIgnoreCase("trylock")) {
     String timeout = args.length > 2 ? args[2] : null;
     if (timeout == null) {
       println(lock.tryLock());
     } else {
       long time = Long.valueOf(timeout);
       try {
         println(lock.tryLock(time, TimeUnit.SECONDS));
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
   }
 }
  @Test
  public void testExecuteOnMembers_withEmptyCollection() {
    final IExecutorService service = client.getExecutorService(randomString());
    final String mapName = randomString();
    final Collection collection = new ArrayList();

    service.executeOnMembers(new MapPutRunnable(mapName), collection);

    final IMap map = client.getMap(mapName);
    assertTrueEventually(
        new AssertTask() {
          public void run() throws Exception {
            assertTrue(map.isEmpty());
          }
        });
  }
Exemplo n.º 29
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);
  }
 @Test
 public void testDisablingSystemLogs() throws Exception {
   Config config = new Config();
   config.setProperty(GroupProperties.PROP_SYSTEM_LOG_ENABLED, "true");
   config.getGroupConfig().setName("testDisablingSystemLogs");
   HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
   HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config);
   instance.getMap("map").put("key", "value");
   Node node = TestUtil.getNode(instance);
   assertTrue(node.getSystemLogService().getLogBundle().size() > 0);
   Hazelcast.shutdownAll();
   config.setProperty(GroupProperties.PROP_SYSTEM_LOG_ENABLED, "false");
   instance = Hazelcast.newHazelcastInstance(config);
   instance2 = Hazelcast.newHazelcastInstance(config);
   instance.getMap("map").put("key2", "value2");
   assertTrue(node.getSystemLogService().getLogBundle().size() == 0);
 }