Ermintar
Ermintar

Reputation: 1393

Hazelcast lock doesn't provide synchronization

I'm trying to acheive method synchronization in Hazelcast, but it doesn't seem to work even on a single cluster.

I'm using a simple Hazelcast config

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

There's a sample service, that generates some ID, using timestamp. It's supposed to be unique, so I'm using lock, provided by 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 checks, that there were no duplicates generated.

@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);
    }
}

However, I get a lot of duplicates while I run the test. Test is run on a single node (I plan to run it on a cluster environment afterwards).

Is hazelcast providing synchronization on a single cluster node? Or have I misconfigured it?

Upvotes: 2

Views: 864

Answers (1)

Neil Stevenson
Neil Stevenson

Reputation: 3150

System.getTimestamp() might not be unique. You can call it twice and get the same result.

You could get Hazelcast to generate the id for you https://docs.hazelcast.org//docs/3.10.5/javadoc/com/hazelcast/flakeidgen/FlakeIdGenerator.html

Upvotes: 1

Related Questions