Java NIO and BIO

我们都知NIO是非阻塞IO,BIO是阻塞IO,那到底什么是阻塞,什么是非阻塞呢,它们与同步/异步又有什么区别呢?先来了解一下阻塞/非阻塞,同步/异步的概念。

基于HashMap和双向链表实现LRUCache

使用HashMap和双向链表实现LRUCache,HashMap用来定位节点是否已经存在,时间复杂度为O(1),双向链表用来用来实现LRU规则,移动节点的时间复杂度也是O(1),代码如下:

Java类与对象初始化过程

看看如下代码,输出结果是啥?

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
/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 18:59 2018/4/1.
*/
public class Test {
public static int k = 0;
public static Test t1 = new Test("t1");
public static Test t2 = new Test("t2");
public static int i = print("i");
public static int n = 99;
public int j = print("j");
static {
print("静态块");
}
public Test(String string){
System.out.println((++k) + ":" + string + " i=" + i + " n=" + n);
++i;
++n;
}
{
print("构造块");
}
public static int print(String string){
System.out.println((++k) + ":" + string + " i=" + i + " n=" + n);
++n;
return ++i;
}

public static void main(String[] args) {
Test test = new Test("init");
}
}

基于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方法都持有锁;(表述不够官方)
Your browser is out-of-date!

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

×