Jie Liu
Jie Liu

Reputation: 13

Why do I need to use curator but not zookeeper native API as distributed lock?

Our project depends on distributed lock heavily. I know curator provides several kinds of locks. My question is, can I just use the creating node as a mutex ?

CuratorFramework zkClient = zookeeperConnectionProvider.getZkClientForJobDistributeLock();
            try {
                zkClient.create()
                        .creatingParentsIfNeeded()
                        .withMode(CreateMode.EPHEMERAL)
                        .forPath("/" + job.getIdentifier().jobNodeString());
                LOGGER.info(String.format("create node in zookeeper [%s]", job.getIdentifier().jobNodeString()));
            } catch (Exception e) {
                LOGGER.info(String.format("create job instance node in zookeeper failed [%s], reason [%s]",
                        job.getIdentifier().jobNodeString(),
                        e.getClass().getCanonicalName()));
                return NO_WORK;
            }

When the first process creates successfully, the second process gets the NodeExistsException exception. If this can not work, I want to know the reason.

Upvotes: 1

Views: 496

Answers (1)

Petter
Petter

Reputation: 1337

I think the first objection against doing as you propose is that it's hard to read/understand the code, compare it to:

InterProcessSemaphoreMutex lock = new InterProcessSemaphoreMutex(client, path);
lock.acquire();

Another reason is that you usually use locks to block a thread until another one releases the lock so you can write code that looks like this:

//do normal work
...
lock.acquire();
//do critical single threaded work
...
lock.release();
//back to normal work
...

Which is by all means possible with your code, but here it's created for you.


There are a lot more reasons to use a already implemented lock instead of writing your own, but it mostly boils down to: 'Why reinvent the wheel?"

Upvotes: 1

Related Questions