点 滴


  • 首页

  • 关于

  • 分类

  • 归档

HashMap 的使用

发表于 2018-12-04 | 分类于 java | 阅读次数:

HashMap 的使用

在开发中经常使用到 HashMap,分析一下 HashMap 带参的构造方法

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
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}

/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

一个参数的构造方法,传入的参数是初始大小,最终调用两个参数的构造方法,传入初始大小和负载系数。默认的负载系数 DEFAULT_LOAD_FACTOR 是 0.75f.调用tableSizeFor(int)传入初始大小值算出threshold,具体的 tableSizeFor(int) 方法,threshold实际值会在第一次put(k,v)重新计算。

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

写一个测试 tableSizeFor 方法算出的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
for(int i = 0; i < 20; i++) {
System.out.println(i+":"+tableSizeFor(i));
}
}
static final int MAXIMUM_CAPACITY = 1 << 30;

static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

分析输出,这里输出的规律是,最小的2的幂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
0:1
1:1
2:2
3:4
4:4
5:8
6:8
7:8
8:8
9:16
10:16
11:16
12:16
13:16
14:16
15:16
16:16
17:32
18:32
19:32

put(k,v)如果是第一次调用会直接调用resize()计算threshold分配table大小,方法在最后会判断size大小是否大于 threshold,如果插入元素大于threshold则调用resize(),然后重新计算 threshold,调整table的大小.阅读源码发现threshold计算方式是table大小乘负载系数 DEFAULT_LOAD_FACTOR.也就是说如果new HashMap(8),在第一次put(k,v)时会计算出threshold为6(负载系数0.75),在第6个参数put(k,v)时,就会重新扩容。扩容的算法使用左移<<算出结果等同*2。如果想防止二次扩容可以使用实际参数数量 / 负载系数(默认0.75) + 1.

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
119
120
121
122
123
124
125
126
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

总结

如果想防止二次扩容可以使用此算法: 实际参数数量 / 负载系数(默认0.75) + 1.

maven findbugs 插件使用

发表于 2018-11-16 | 分类于 maven | 阅读次数:

Maven Findbugs 插件使用

什么是 Findbugs

Findbugs是使用静态分析查找Java代码中的错误的程序

pom 依赖

1
2
3
4
5
6
7
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.5.2</version>
</plugin>
</plugins>

命令

1
mvn clean compile findbugs:findbugs findbugs:gui

执行这条命令

  1. 清理 target 目录
  2. 编译 class
  3. 生成 findbugs 文件
  4. 执行 findbugs gui 程序,查看问题

基于JMS 远程分区的 spring batch

发表于 2018-10-18 | 分类于 spring | 阅读次数:

基于JMS 远程分区的 spring batch

关于 spring batch 的应用场景

通常做法

在支付系统中避免不了每天的交易结算,我们通常这样做,定时每天读取所有需要处理的交易记录,然后 for 循环处理,数据量小业务逻辑简单这样做没什么问题。如果业务复杂,就不能这么简单处理了,后期代码维护将是一个大问题。当数据量大了读取所有数据再处理也是行不通的,大量数据不可能一次全部读取到内存中,数据量大单台机处理也会很缓慢。

思考解决方案

这里可能会考虑到分批次多进程多线程处理,大致方案是读取所有需要处理数据的key,发送到mq,多台机器消费处理。

spring batch 来解决

spring batch 介绍 可以在官方文档看看,鉴于上面的场景,在 step read 前读取所有 key,然后拆分,拆分数量可以根据部署消费者数量定义,分区之后发送到mq,消费者接收到需要处理的 key 后,本地再拆分多线程处理,大致方案就是这样。

一张图来理解

jms-batch
这里 主 定义为 M, 从 定义为 S.
调度系统发送一条起批消息,哪台先抢到消费,哪台就是 M(注意:这种模式即是M也是S,除非明确指定了某一台来起批,不去监听 S 队列)。M 启动 job 执行分区逻辑,通过mq分发 key 到 S(本身 M 也监听了,所以 M 也是 S), S 收到消息执行业务逻辑(也可本地分片多线程处理),S执行完回复消息,或者 M 到数据库轮训结果。批量结束。

一个简单的demo batch-demo

迭代器 (Iterator)

发表于 2018-10-07 | 分类于 设计模式 | 阅读次数:

迭代器(Iterator)

提供按顺序访问聚合对象的元素,并不暴露聚合对象的内部表示。

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
33
34
35
36
37
38
39
40
41
public interface Iterator<T> {

boolean hasNext();

T next();
}


public class ConcreteIterator<Item> implements Iterator<Item> {

private Item[] items;
private int position = 0;

public ConcreteIterator(Item[] items) {
this.items = items;
}

@Override
public boolean hasNext() {
return position < items.length;
}

@Override
public Item next() {
return items[position++];
}
}

public class IteratorTest {

public static void main(String[] args) {
Integer[] items = new Integer[10];
for (int i = 0; i < items.length; i++) {
items[i] = i;
}
Iterator<Integer> iterator = new ConcreteIterator<>(items);
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

Java finally 关键字用法

发表于 2018-09-13 | 阅读次数:

Java finally 关键字使用

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FinallyTest {

public static void main(String[] args) {
int t = testFinally();
System.out.println(t);
}

public static int testFinally() {
int i = 0;
try {
i = i + 10;
return i;
} finally {
i = i + 10;
}
}
}

问题

  • finally 块会执行吗?
  • 返回结果是多少? 为什么?

执行结果

1
10

finally 块执行了

在 Eclipse 断点调试,发现 finally 确实执行,查看 Oracle 的官方文档,解释了 finally 只有在 JVM 退出了或进程被 kill 掉了才不会执行。

返回结果是 10,为什么?

在 Eclipse 断点调试,发现 finally 确实执行了 i = i + 10, i 的值被修改为 20.但是最后栈顶的值设置为10,返回的还是 10.

查看虚拟机指令

javap -c

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
public class FinallyTest {
public FinallyTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: invokestatic #2 // Method testFinally:()I
3: istore_1
4: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
7: iload_1
8: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
11: return

public static int testFinally();
Code:
0: iconst_0 // int型常量0进栈
1: istore_0 // 栈顶int数值存入第1局部变量
2: iload_0 // 第1个int型变量进栈
3: bipush 10 // byte型常量 10 进栈
5: iadd // 执行 0 + 10 放到栈顶
6: istore_0 // 栈顶int数值存入第1局部变量
7: iload_0 // 第1个int型变量进栈
8: istore_1 // 栈顶int数值存入第2局部变量
9: iload_0 // 第1个int型变量进栈
10: bipush 10 // byte型常量 10 进栈
12: iadd // 执行 10 + 10 放到栈顶
13: istore_0 // 栈顶int数值存入第1局部变量
14: iload_1 // 第2个int型变量进栈
15: ireturn // 返回结果
16: astore_2
17: iload_0
18: bipush 10
20: iadd
21: istore_0
22: aload_2
23: athrow
Exception table:
from to target type
2 9 16 any
}

堆栈执行图

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
0: 0

1: 0 0

2: 0 0
0

3: 10 0
0
0

5: 10 0
0
0

6: 10 10
0
0

7: 10 10
10
0
0

8: 10 10
10 10
0
0
9: 10 10
10 10
10
0
0

10: 10 10
10 10
10
10
0
0

12: 20 10
10 10
10
10
0
0

13: 20 20
10 10
10
10
0
0

14: 10 20
20 10
10
10
10
0
0

15: ireturn // 弹出栈顶到调用处

jdb 调试

1
2
3
4
5
6
7
8
9
10
11
已完成的步骤: "线程=main", FinallyTest.testFinally(), 行=12 bci=15
12 return i;

main[1] locals
方法参数:
本地变量:
i = 20
main[1] stepi
>
已完成的步骤: "线程=main", FinallyTest.main(), 行=4 bci=3
4 int t = testFinally();

javac 编译时 把 finally 块的代码编译到 ireturn 之前了

此处还有疑问,ireturn 后的代码是干嘛的

参考

  • 你真的了解try{ return }finally{}中的return?: https://www.cnblogs.com/averey/p/4379646.html
  • JVM指令: http://gityuan.com/2015/10/24/jvm-bytecode-grammar/
12…6

luokai

个人博客

29 日志
14 分类
15 标签
© 2018 luokai
由 Hexo 强力驱动
|
主题 — NexT.Gemini v6.0.4