Skip to content

How to synchronize method with HazelCast between two nodes?

There is Spring Boot project. Project works on two nodes. I have method for send message mail with scheduler. The message is sent 2 times, since two nodes are working. How can I use HazelCast to configure the method so that it works once, only by one, more optimal node? There is very little documentation and articles on the net. I have already added HazelCast to the project, and the nodes see each other.


        enabled: true


    implementation group: 'com.hazelcast', name: 'hazelcast-all', version: '4.2'


@Scheduled(cron = "0 0 9 * * ?")
public void senMail(MailDTO mailDTO) {


I have created a distributed map that is visible with two nodes at the same time (this feature is provided by HazelCast). After that, I began to put the key value in this map according to the type of the name of the action and the time of the action. So the second node looked into the map, and if the action was already performed, it no longer performed it. So I solved the problem with duplicate messages.

I create distributed map:

public class HazelCastConfiguration {

    public Config hazelCastConfig() {
        return new Config();

    public HazelcastInstance hazelcastInstance(Config hazelCastConfig) {
        return Hazelcast.newHazelcastInstance(hazelCastConfig);

    public Map<String, LocalDateTime> timeMap(@Qualifier("hazelcastInstance") HazelcastInstance hazelcastInstance) {
        return hazelcastInstance.getMap("hazelcastTimeMap");

And then I use AutoWired for work with map:

private Map<String, LocalDateTime> timeMap;

public void setTimeMap(Map<String, LocalDateTime> timeMap) {
        this.timeMap = timeMap;