基于Zookeeper实现分布式锁

基于Zookeeper实现分布式锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import com.google.common.base.Strings;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.*;

/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 15:37 2018/3/31.
*/
public class DistributedLockBasedOnZookeeper {
private String hostPort = "host:port";
private String lockNameSpace = "/myLock";
private String nodeString = lockNameSpace + "/test1";
private ZooKeeper zk;

public DistributedLockBasedOnZookeeper(){
try {
zk = new ZooKeeper(hostPort, 6000, event -> {
System.out.println("Receive event " + event);
if (Watcher.Event.KeeperState.SyncConnected == event.getState()){
System.out.println("Connection is established...");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
private void ensureRootPath() throws InterruptedException {
try {
if (zk.exists(lockNameSpace, true) == null){
zk.create(lockNameSpace, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (KeeperException e) {
e.printStackTrace();
}
}

private void watchNode(String nodeString, final Thread thread){
try {
zk.exists(nodeString, event -> {
System.out.println("==" + event.toString());
if (event.getType() == Watcher.Event.EventType.NodeDeleted){
System.out.println("There is a Thread released lock.....");
thread.interrupt();
}
try {
zk.exists(nodeString, true);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

/**
* get Lock
* @return
*/
public boolean getLock() throws InterruptedException {
String path = null;
ensureRootPath();
watchNode(nodeString, Thread.currentThread());
while (true){
try {
path = zk.create(nodeString, "".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
} catch (KeeperException e) {
System.out.println(Thread.currentThread().getName() + "getting Lock but can not get");
Thread.sleep(5000);
}
if (!Strings.nullToEmpty(path).trim().isEmpty()){
System.out.println(Thread.currentThread().getName() + " get Lock...");
return true;
}
}
}

/**
* release Lock
*/
public void unlock(){
try {
zk.delete(nodeString, -1);
System.out.println(Thread.currentThread().getName() + " release Lock...");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
ExecutorService service = new ThreadPoolExecutor(10, 10, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());

for (int i = 0; i < 4; i++){
service.execute(() -> {
DistributedLockBasedOnZookeeper lockBasedOnZookeeper = new DistributedLockBasedOnZookeeper();
try {
lockBasedOnZookeeper.getLock();
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lockBasedOnZookeeper.unlock();
});
}
service.shutdown();
}
}

How-to-understand-the-DeadLock

如何理解如下代码会造成DeadLock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 10:36 2018/4/14.
*/
public class DeadLock {
static class Friend{
private final String name;
public Friend(String name){
this.name = name;
}

public String getName(){
return this.name;
}

public synchronized void bow(Friend friend){
System.out.format("%s:%s" + " has bowed to me!%n", this.name, friend.getName());
friend.bowBack(this);
}
public synchronized void bowBack(Friend friend){
System.out.format("%s:%s" + " has bowed back to me!%n", this.name, friend.getName());
}
}

public static void main(String[] args) throws InterruptedException {
final Friend friendA = new Friend("Shuai");
final Friend friendB = new Friend("Junlan");
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
2, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(2));
/// Why not using this way to create ThreadPool?
// ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
threadPoolExecutor.execute(() -> friendA.bow(friendB));
threadPoolExecutor.execute(() -> friendB.bow(friendA));
threadPoolExecutor.shutdown();

}
}

output

1
2
Shuai:Junlan has bowed to me!
Junlan:Shuai has bowed to me!

Conclusion

  • 类的实例对类中所有的synchronized方法都持有锁;(表述不够官方)

Distributed-Systems-Technologies

1.分布式系统中基本概念及常用技术介绍

网络I/O模型

1.同步和异步
  • 同步:
  • 异步:
2.阻塞和非阻塞
  • 阻塞:
  • 非阻塞:
3.UNIX网络I/O模型

远程过程调用(RPC)

Basing on Spring SpringMVC MyBatis Druid Shrio developing web system

源码下载地址:https://github.com/shuaijunlan/Autumn-Framework

在线Demo:http://autumn.shuaijunlan.cn

项目介绍

Autumn-Framework旨在提供通用的web系统解决方案,目前由作者本人一个人维护,更新速度缓慢,但是会持续更新,此项目适合初学者学习使用,也欢迎您加入我一起维护整个项目。

analyse the source code of Timer

Timer Class Introduction

在JDK库中Timer类主要负责计划任务的功能,也就是在指定的时间开始执行某任务。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×