Hazelcast 锁不提供同步

Hazelcast lock doesn't provide synchronization

我试图在 Hazelcast 中实现方法同步,但即使在单个集群上它似乎也不起作用。

我使用的是简单的 Hazelcast 配置

@Configuration
public class HazelcastConfig {
    @Bean
    HazelcastInstance hazelcastInstance(){
        return Hazelcast.newHazelcastInstance();
    }
}

有一个示例服务,它使用时间戳生成一些 ID。它应该是唯一的,所以我正在使用由 Hazelcast

提供的锁
@Service
public class MyService {
    @Autowired
    private HazelcastInstance hazelcastInstance;

    public Long generateVersion(){
        ILock lock = hazelcastInstance.getLock("version_key");
        try{
            lock.lock();
            return System.currentTimeMillis();
        } catch (Exception ex) {
            LOGGER.error("Could not generate version ", ex);
            throw ex;
        } finally{
            lock.unlock();
        }
    }
}

测试检查,没有生成重复项。

@Test
public void test() throws InterruptedException, ExecutionException {
    List<Long> versions = new ArrayList();
    Collection<Callable<Long>> tasks = new ArrayList<>();
    int nThreads = 100;
    for(int i=0; i<nThreads; i++){
        tasks.add(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return myService.generateVersion();
            }
        });
    }
    ExecutorService executor = Executors.newFixedThreadPool(nThreads);
    List<Future<Long>> results = executor.invokeAll(tasks);
    for(Future<Long> result : results){
        Long pingResult = result.get();
        if (!versions.contains(pingResult))
            versions.add(pingResult);
        else
            throw new AssertionError("Found duplicate "+ pingResult);
    }
}

但是,我在 运行 测试时得到了很多重复项。测试是在单个节点上运行(我计划之后在集群环境中运行)。

hazelcast 是否在单个集群节点上提供同步?还是我配置有误?

System.getTimestamp() 可能不是唯一的。你可以调用它两次并得到相同的结果。

您可以让 Hazelcast 为您生成 ID https://docs.hazelcast.org//docs/3.10.5/javadoc/com/hazelcast/flakeidgen/FlakeIdGenerator.html