0% found this document useful (0 votes)
127 views

《Java面试手册》

1. The document discusses key concepts in Java including data types, object-oriented programming principles like inheritance and polymorphism, Java features like packages and interfaces, and core Java APIs. 2. Important Java concepts covered include primitives vs reference types, inheritance hierarchies using the "is-a" relationship, polymorphism through method overriding, and Java memory management using the garbage collector. 3. The summary also touches on core Java classes like Object, String, and common programming constructs such as main methods, loops, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

《Java面试手册》

1. The document discusses key concepts in Java including data types, object-oriented programming principles like inheritance and polymorphism, Java features like packages and interfaces, and core Java APIs. 2. Important Java concepts covered include primitives vs reference types, inheritance hierarchies using the "is-a" relationship, polymorphism through method overriding, and Java memory management using the garbage collector. 3. The summary also touches on core Java classes like Object, String, and common programming constructs such as main methods, loops, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 166

Java 们

1.Java
1. 知


1) 知

( )
2) 知(1)
(2)

2. 知

1. 知
2. 知
3. 知
is-a class dog extends animal, dog is a
animal.
⾃ -
4. 知

3. 知


样 样

1. 知
2. 知
(upcast) JVM (downcast)
2.Java
1. Java Java C C++
Java
2. Java Java 然
样 implements
3. Java Java Internet Java
样java net 会 URL然URLConnection然
Socket然ServerSocket Java RMI样
4. Java Java 然 然是了 Java
Java
5. Java Java Java
知 样 ClassLoader 然

6. Java Java 样 java Java


样 class Java
7. Java Java Java
Java 样
8. Java Java
9. Java Java Thread

:https://blog.csdn.net/shenzixincaiji/article/details/82766104

3. JDK JRE
JDK知Java Development Kit Java Java
JRE知Java Runtime Environment Java Java

JDK JRE Java Javac Java


知 Java JRE
Java JDK

4.Java
Tips:boolean 4 1
Java


⽣ Java


1.
2.
看想

5. main private
”main public ” idea public

6. public static void main(String args[])

public: main Java Java


pulic.

static: Java static

void: main

String args 为

7.== equals
== String
.

== equals public boolean equals(Object obj) Object


true, ==
String, BitSet, Date, File equals String

public class EqualsTest {


public static void main(String[] args) {
String s1 = “abc”;
String s2 = s1;
String s5 = “abc”;
String s3 = new String(”abc”);
String s4 = new String(”abc”);
System.out.println(”== comparison : ” + (s1 == s5));
System.out.println(”== comparison : ” + (s1 == s2));
System.out.println(”Using equals method : ” + s1.equals(s2));
System.out.println(”== comparison : ” + s3 == s4);
System.out.println(”Using equals method : ” + s3.equals(s4));
}
}

== comparison : true
== comparison : true
Using equals method : true
false
Using equals method :true

8.Object
Object Object

clone Cloneable
CloneNotSupportedException

equals Object ==

hashCode equals hashCode


Collection

getClass final

wait wait()
wait(long timeout)

1然 notify
2然 notifyAll

3然 interrupt

4然

5然 InterruptedException

notify

notifyAll

toString 为

知https://www.cnblogs.com/remember-forget/p/5971962.html

9. Java ?
Java 知

10.while do
while 事 do/while
事 do

11.char ?
Java Unicode Unicode 16 char 16

12.public private protected

Tips: default

13.float f=3.4;
3.4 样double 样float 样down-casting
情 float f =(float)3.4; float f =3.4F
14.short s1 = 1; s1 = s1 + 1; short s1 = 1; s1 += 1;
short s1 = 1; s1 = s1 + 1又 1 int s1+1 int
short short s1 = 1; s1 += 1又+= 为 Java
又Java s1+= 1; s1 = (short)(s1 + 1)

15.& &&
1. &知(1) 又(2)

: 0 & 1 = 0 ; 0 & 0 = 0; 1 & 1 = 1

: a == b & b ==c 样 a==b false b c)

2.&&:

a== b && b== c 样 a==b false b c)

&&,

16.IntegerCache

public class IntegerTest {

public static void main(String[] args) {

Integer a = 100, b = 100 ,c = 129,d = 129;

System.out.println(a==b);

System.out.println(c==d);
}
}

true
false

/**
* Cache to support the object identity semantics of autoboxing for
values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/

private static class IntegerCache {


static final int low = -128;
static final int high;
static final Integer cache[];

static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =

sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore
it.
}
}
high = h;

cache = new Integer[(high - low) + 1];


int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);

// range [-128, 127] must be interned (JLS7 5.1.7)


assert IntegerCache.high >= 127;
}

private IntegerCache() {}
}

public static Integer valueOf(int i) {


assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
, -128~127
-XX:AutoBoxCacheMax

17.Locale
Locale

18.Java final finally finalize


1. final
final 为

final
final 又

final ⼼
知 private final

2. finally
finally

finally finally 爱 finally

finally 知
try try finally
try jvm system.exit(n) finally 样
finally return try catch return return
finally return

3. finalize
finalize() Object protected
GC
finalize() 知

java finalize
finalize() JVM finalize
finalize() GC Roots
finalize GC 样 finalize

19.hashCode() equals()

1.equals() hashCode() 友
equals样 hashCode()
hash
2.hashCode() equals() 友
hashCode() hashcode 样 hash
hashCode()
样PS知 知

equals() hashCode() equals()

hashCode() equals() hashCode()

1. 知

equals hashCode又

Set hashCode equals Set


Map hashCode equals又

String hashCode equals String key 又

2然 友
hashCode HashTable然HashMap然HashSet hash
hashCode

3然 hashCode 友
equals hashCode
“ ” hashCode

hashMap然hasoTable hashSet “ ”

4然 equals() hashCode hashCode equals ?

hashCode hashCode
HashMap key hashCode equals true
hashCode equal ObjectA ObjectB name
hashCode name hashCode equals false

5然 hashCode?

hashCode
hashCode equals get hashCode hashCode false

知https://blog.csdn.net/xlgen157387/article/details/88087963

20. ?

现 “ ” 现 ” “

2

package com.test;

public class ShallowCopy {


public static void main(String[] args) throws CloneNotSupportedException
{
Teacher teacher = new Teacher();
teacher.setName("riemann");
teacher.setAge(27);

Student2 student1 = new Student2();


student1.setName("edgar");
student1.setAge(18);
student1.setTeacher(teacher);

Student2 student2 = (Student2) student1.clone();


System.out.println("拷⻉贝后");
System.out.println(student2.getName());
System.out.println(student2.getAge());
System.out.println(student2.getTeacher().getName());
System.out.println(student2.getTeacher().getAge());

System.out.println("修改⽼老老师的信息后——————");
// 修改⽼老老师的信息
teacher.setName("Games");
System.out.println(student1.getTeacher().getName());
System.out.println(student2.getTeacher().getName());

}
}

class Teacher implements Cloneable {


private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}

class Student2 implements Cloneable {


private String name;
private int age;
private Teacher teacher;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public Teacher getTeacher() {


return teacher;
}

public void setTeacher(Teacher teacher) {


this.teacher = teacher;
}

public Object clone() throws CloneNotSupportedException {


Object object = super.clone();
return object;
}
}

拷⻉贝后
edgar
18
riemann
27
修改⽼老老师的信息后——————
Games
Games
知 student1 student2 student1 student2
teacher 现

现 现 现 现 , 现
现 现 现 现

package com.test;

public class DeepCopy {


public static void main(String[] args) throws CloneNotSupportedException
{
Teacher2 teacher = new Teacher2();
teacher.setName("riemann");
teacher.setAge(27);

Student3 student1 = new Student3();


student1.setName("edgar");
student1.setAge(18);
student1.setTeacher(teacher);

Student3 student2 = (Student3) student1.clone();


System.out.println("拷⻉贝后");
System.out.println(student2.getName());
System.out.println(student2.getAge());
System.out.println(student2.getTeacher().getName());
System.out.println(student2.getTeacher().getAge());
System.out.println("修改⽼老老师的信息后——————");
// 修改⽼老老师的信息
teacher.setName("Games");
System.out.println(student1.getTeacher().getName());
System.out.println(student2.getTeacher().getName());
}
}

class Teacher2 implements Cloneable {


private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public Object clone() throws CloneNotSupportedException {


return super.clone();
}
}

class Student3 implements Cloneable {


private String name;
private int age;
private Teacher2 teacher;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public Teacher2 getTeacher() {


return teacher;
}

public void setTeacher(Teacher2 teacher) {


this.teacher = teacher;
}

public Object clone() throws CloneNotSupportedException {


// 浅复制时:
// Object object = super.clone();
// return object;

// 改为深复制:
Student3 student = (Student3) super.clone();
// 本来是浅复制,现在将Teacher对象复制⼀一份并重新set进来
student.setTeacher((Teacher2) student.getTeacher().clone());
return student;

}
}

拷⻉贝后
edgar
18
riemann
27
修改⽼老老师的信息后——————
Games
riemann


student1 student2 student1 student2 teacher
teacher student1 , 现
21.Java
String然StringBuffer然StringBuilder

String StringBuffer然StringBuilder String


String String StringBuffer然StringBuilder
们 为 String

StringBuffer StringBuilder StringBuffer StringBuilder


StringBuilder StringBuffer StringBuilder
StringBuffer

22.String str="a" String str=new String("a")

String str="a"; -> String str=new String("a") ->

23. final
final

24.static 5
样1 样abstract 样static 友

(2) 样static 友

(3) static 友

static ⼼
样4 友


new new
然 又

样5 Java (override) private static 友

Java static static


static

25. Overload Override

样 然


26.Java
1

String s = "abc" s 为 “abc” 是


2 SoftReference

ReferenceQueue 是了
JVM
3 WeakReference


是了 ⽆

4 PhantomReference

是了 没
是了

样ReferenceQueue 是了

27.Java Comparator Comparable


Comparable comparator
( Comparable
) “ ” Comparable
comparator

28. Java , ?
Java

29. Java ?
Java

30. ?
Serializable ,

31. ?
transient :

transient private String phone;//不不参与序列列化

32.Java
⽣ 知
java ⽣ 知1.⽣ 又2.
java

1.Java
Collection Java

Set

List List

Map key value . Map key知 key value

Queue然Dequeue然SortedSet然SortedMap ListIterator

2.Collection Collections
Collection
List然Set
Collections
知 Collections. sort(list)

3.List Set Map Collection


List然Set Map Map List Set Set
⼼ 样 List

4.Collections.sort
Java 6 Arrays.sort() Collections.sort() MergeSort Java 7
TimSort

5.List Set Map


List然Set然Map 知 然 ⼼

6.HashMap Hashtable
样1 HashMap⼼ key value null HashTable ⼼

样2 HashTable HashMap HashMap HashTable

样3 Java1.4 LinkedHashMap HashMap


HashMap LinkedHashMap HashTable

样4 HashMap key Set fail-fast HashTable key Enumeration


fail-fast

样5 HashTable 事 Map
CocurrentHashMap

7. HashMap TreeMap
Map 然 然 HashMap
HashMap key TreeMap

8. HashMap
HashMap Hash put(key,value) get(key) key
HashMap key. hashCode() hash hash value bucket
hash hash HashMap hash
value hash

9. HashSet
HashSet HashMap HashSet HashMap HashSet
HashSet HashMap HashSet

10.ArrayList LinkedList
知ArrayList LinkedList
知ArrayList LinkedList LinkedList

知 LinkedList ArrayList
ArrayList
都 ArrayList
LinkedList

11. Map Collection


Map 发 Map Map Map
Collection

Map Collection 友Map key-value key value


“ ”

12.ArrayList Vector
ArrayList Vector

样1

样2

样3 ArrayList Vector 事 fail-fast

样4 ArrayList Vector ⼼ null

ArrayList Vector

样1 Vector ArrayList 事
CopyOnWriteArrayList

样2 ArrayList Vector

样3 ArrayList Collections

13.Array ArrayList
Array ArrayList
Array ArrayList ⾃
Array ArrayList addAll然removeAll然iteration ArrayList

14. Queue poll() remove()



知 poll() null remove() NoSuchElementException

Queue<String> queue = new LinkedList<String>();


queue. offer("string"); // add
System. out. println(queue. poll());
System. out. println(queue. remove());
System. out. println(queue. size());

15.LinkedHashMap ?
LinkedHashMap HashMap Iterator LinkedHashMap

16.HashMap
HashMap + + 样JDK1.8
知 友 友

(1) HashMap Node[] table 就


Node Node[JDK1.8]

static class Node<K,V> implements Map.Entry<K,V> {


final int hash; //⽤用来定位数组索引位置
final K key;
V value;
Node<K,V> next; //链表的下⼀一个node

Node(int hash, K key, V value, Node<K,V> next) { … }


public final K getKey(){ … }
public final V getValue() { … }
public final String toString() { … }
public final int hashCode() { … }
public final V setValue(V newValue) { … }
public final boolean equals(Object o) { … }
}

Node HashMap Map.Entry ( )


Node

(2) HashMap
Java HashMap
Hash

map.put("美团","⼩小美");

" " key hashCode() hashCode 样 Java


Hash 样
key Hash Hash Hash
map

就 Hash 就 Hash

就 们 hash Hash map
Hash 就 样Node[] table 友 Hash ⾃

Hash ⾃ HashMap HashMap


int threshold; // 所能容纳的key-value对极限


final float loadFactor; // 负载因⼦子
int modCount;
int size;
Node[] table length( 16) Load factor ( 0.75)
threshold HashMap Node( ) threshold = length * Load factor

threshold Load factor length( ) ⼼


resize(⾃ ) ⾃ HashMap
0.75 ⼀
Load factor 又
loadFactor 1

size HashMap table length然


threshold modCount HashMap
事 put
key value

HashMap 就 table length 2 n ( )



http://blog.csdn.net/liuqiyao_01/article/details/14475159 Hashtable 就 11 就
样Hashtable⾃ HashMap
⾃ HashMap 就

Hash
HashMap JDK1.8
样 8
HashMap 然 然

HashMap key 就 然put 然


1. 就

然 然 就 HashMap
HashMap
hash
HashMap
hash ( + ):

⽅方法⼀一:
static final int hash(Object key) { //jdk1.8 & jdk1.7
int h;
// h = key.hashCode() 为第⼀一步 取hashCode值
// h ^ (h >>> 16) 为第⼆二步 ⾼高位参与运算
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
⽅方法⼆二:
static int indexFor(int h, int length) { //jdk1.7的源码,jdk1.8没有这个⽅方法,但
是实现原理理⼀一样的
return h & (length-1); //第三步 取模运算
}
Hash 知 key hashCode

hashCode() Hash
hash
HashMap 知
table

h & (table.length -1) HashMap


2 n HashMap length 2 n h& (length-1)
length h%length & %

JDK1.8 hashCode() 16 16 知(h =


k.hashCode()) ^ (h >>> 16) 然 然 table length
Bit Hash

n table

2.HashMap put

HashMap put
. table[i] null resize() ⾃ 又

做. key hash i table[i]==null


table[i] 动又

动. table[i] key value


hashCode equals又

. table[i] treeNode table[i]


活又

活. table[i] 8 8
又 key value 又

. size threshold ⾃

JDK1.8HashMap put :

public V put(K key, V value) {


2 // 对key的hashCode()做hash
3 return putVal(hash(key), key, value, false, true);
4 }
5
6 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
7 boolean evict) {
8 Node<K,V>[] tab; Node<K,V> p; int n, i;
9 // 步骤①:tab为空则创建
10 if ((tab = table) == null || (n = tab.length) == 0)
11 n = (tab = resize()).length;
12 // 步骤②:计算index,并对null做处理理
13 if ((p = tab[i = (n - 1) & hash]) == null)
14 tab[i] = newNode(hash, key, value, null);
15 else {
16 Node<K,V> e; K k;
17 // 步骤③:节点key存在,直接覆盖value
18 if (p.hash == hash &&
19 ((k = p.key) == key || (key != null && key.equals(k))))
20 e = p;
21 // 步骤④:判断该链为红⿊黑树
22 else if (p instanceof TreeNode)
23 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key,
value);
24 // 步骤⑤:该链为链表
25 else {
26 for (int binCount = 0; ; ++binCount) {
27 if ((e = p.next) == null) {
28 p.next = newNode(hash, key,value,null);
//链表⻓长度⼤大于8转换为红⿊黑树进⾏行行处理理
29 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
30 treeifyBin(tab, hash);
31 break;
32 }
// key已经存在直接覆盖value
33 if (e.hash == hash &&
34 ((k = e.key) == key || (key != null &&
key.equals(k)))) break;
36 p = e;
37 }
38 }
39
40 if (e != null) { // existing mapping for key
41 V oldValue = e.value;
42 if (!onlyIfAbsent || oldValue == null)
43 e.value = value;
44 afterNodeAccess(e);
45 return oldValue;
46 }
47 }

48 ++modCount;
49 // 步骤⑥:超过最⼤大容量量 就扩容
50 if (++size > threshold)
51 resize();
52 afterNodeInsertion(evict);
53 return null;
54 }
3.⾃

⾃ (resize) HashMap HashMap


⾃ Java
⾃ 就

resize 个 JDK1.8 JDK1.7

1 void resize(int newCapacity) { //传⼊入新的容量量


2 Entry[] oldTable = table; //引⽤用扩容前的Entry数组
3 int oldCapacity = oldTable.length;
4 if (oldCapacity == MAXIMUM_CAPACITY) { //扩容前的数组⼤大⼩小如果已经达到最⼤大
(2^30)了了
5 threshold = Integer.MAX_VALUE; //修改阈值为int的最⼤大值(2^31-1),这样以
后就不不会扩容了了
6 return;
7 }
8
9 Entry[] newTable = new Entry[newCapacity]; //初始化⼀一个新的Entry数组
10 transfer(newTable); //!!将数据转移到新的Entry数
组⾥里里
11 table = newTable; //HashMap的table属性引⽤用新的
Entry数组
12 threshold = (int)(newCapacity * loadFactor);//修改阈值
13 }

transfer() Entry
现 Entry

1 void transfer(Entry[] newTable) {


2 Entry[] src = table; //src引⽤用了了旧的Entry数组
3 int newCapacity = newTable.length;
4 for (int j = 0; j < src.length; j++) { //遍历旧的Entry数组
5 Entry<K,V> e = src[j]; //取得旧Entry数组的每个元素
6 if (e != null) {
7 src[j] = null;//释放旧Entry数组的对象引⽤用(for循环后,旧的Entry数组
不不再引⽤用任何对象)
8 do {
9 Entry<K,V> next = e.next;
10 int i = indexFor(e.hash, newCapacity); //!!重新计算每个元素
在数组中的位置
11 e.next = newTable[i]; //标记[1]
12 newTable[i] = e; //将元素放在数组上
13 e = next; //访问下⼀一个Entry链上的元素
14 } while (e != null);
15 }
16 }
17 }
newTable[i] e.next
又 Entry ( hash
Jdk1.8 Entry

⾃ hash key mod 样


就 table size=2 key = 3然7然5 put 5然7然3 mod
2 table[1] loadFactor=1 size table
⾃ ⽇ 就 resize 4 Node rehash

JDK1.8 2 ⾃ ( ⾃
2 ) 2
n table 样a ⾃ key1 key2 key 样b
⾃ key1 key2 key hash1 key1

hash n 2 n-1 mask 1bit( ) index



⾃ HashMap JDK1.7 hash
hash bit 1 0 0 1 “ +oldCap”
16⾃ 32 resize 知

hash 1bit 0 1
resize bucket
JDK1.8 JDK1.7 rehash 时
JDK1.8
JDK1.8 resize :

1 final Node<K,V>[] resize() {


2 Node<K,V>[] oldTab = table;
3 int oldCap = (oldTab == null) ? 0 : oldTab.length;
4 int oldThr = threshold;
5 int newCap, newThr = 0;
6 if (oldCap > 0) {
7 // 超过最⼤大值就不不再扩充了了,就只好随你碰撞去吧
8 if (oldCap >= MAXIMUM_CAPACITY) {
9 threshold = Integer.MAX_VALUE;
10 return oldTab;
11 }
12 // 没超过最⼤大值,就扩充为原来的2倍
13 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
14 oldCap >= DEFAULT_INITIAL_CAPACITY)
15 newThr = oldThr << 1; // double threshold
16 }
17 else if (oldThr > 0) // initial capacity was placed in threshold
18 newCap = oldThr;
19 else { // zero initial threshold signifies using
defaults
20 newCap = DEFAULT_INITIAL_CAPACITY;
21 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
22 }
23 // 计算新的resize上限
24 if (newThr == 0) {
25
26 float ft = (float)newCap * loadFactor;
27 newThr = (newCap < MAXIMUM_CAPACITY && ft <
(float)MAXIMUM_CAPACITY ?
28 (int)ft : Integer.MAX_VALUE);
29 }
30 threshold = newThr;
31 @SuppressWarnings({"rawtypes","unchecked"})
32 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
33 table = newTab;
34 if (oldTab != null) {
35 // 把每个bucket都移动到新的buckets中
36 for (int j = 0; j < oldCap; ++j) {
37 Node<K,V> e;
38 if ((e = oldTab[j]) != null) {
39 oldTab[j] = null;
40 if (e.next == null)
41 newTab[e.hash & (newCap - 1)] = e;
42 else if (e instanceof TreeNode)
43 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
44 else { // 链表优化重hash的代码块
45 Node<K,V> loHead = null, loTail = null;
46 Node<K,V> hiHead = null, hiTail = null;
47 Node<K,V> next;
48 do {
49 next = e.next;
50 // 原索引
51 if ((e.hash & oldCap) == 0) {
52 if (loTail == null)
53 loHead = e;
54 else
55 loTail.next = e;
56 loTail = e;
57 }
58 // 原索引+oldCap
59 else {
60 if (hiTail == null)
61 hiHead = e;
62 else
63 hiTail.next = e;
64 hiTail = e;
65 }
66 } while ((e = next) != null);
67 // 原索引放到bucket⾥里里
68 if (loTail != null) {
69 loTail.next = null;
70 newTab[j] = loHead;
71 }
72 // 原索引+oldCap放到bucket⾥里里
73 if (hiTail != null) {
74 hiTail.next = null;
75 newTab[j + oldCap] = hiHead;
76 }
77 }
78 }
79 }
80 }
81 return newTab;
82 }

17.HashMap
HashMap ( JDK1.7
)知

public class HashMapInfiniteLoop {

private static HashMap<Integer,String> map = new HashMap<Integer,String>


(2,0.75f);
public static void main(String[] args) {
map.put(5, "C");

new Thread("Thread1") {
public void run() {
map.put(7, "B");
System.out.println(map);
};
}.start();
new Thread("Thread2") {
public void run() {
map.put(3, "A);
System.out.println(map);
};
}.start();
}
}

map 2 loadFactor=0.75 threshold=2*0.75=1 put


key map resize
1 2 debug transfer (3.3 )
thread1 transfer “Entry next = e.next;” 又 2
2 resize

Thread1 e key(3) next key(7) rehash

newTalbe[i] = e e = next e key(7)


next = e.next next key(3)

e.next = newTable[i] key(3).next key(7) 知 key(7).next key(3)


map.get(11) ——Infinite Loop

18.JDK1.8 JDK1.7
HashMap key hash Hash
getKey O(1) Hash Hash
Hash 就
O(n) O(lgn) 个 JDK1.8
JDK1.7

Hash

Key 知

class Key implements Comparable<Key> {

private final int value;

Key(int value) {
this.value = value;
}

@Override
public int compareTo(Key o) {
return Integer.compare(this.value, o.value);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Key key = (Key) o;
return value == key.value;
}

@Override
public int hashCode() {
return value;
}
}

equals hashCode hashCode


value hashcode GC Key

public class Keys {

public static final int MAX_KEY = 10_000_000;


private static final Key[] KEYS_CACHE = new Key[MAX_KEY];
static {
for (int i = 0; i < MAX_KEY; ++i) {
KEYS_CACHE[i] = new Key(i);
}
}

public static Key of(int value) {


return KEYS_CACHE[value];
}
}

size HashMap样1然10然100然……
10000000 ⽤ ⾃ 知

static void test(int mapSize) {

HashMap<Key, Integer> map = new HashMap<Key,Integer>(mapSize);


for (int i = 0; i < mapSize; ++i) {
map.put(Keys.of(i), i);
}

long beginTime = System.nanoTime(); //获取纳秒


for (int i = 0; i < mapSize; i++) {
map.get(Keys.of(i));
}
long endTime = System.nanoTime();
System.out.println(endTime - beginTime);
}

public static void main(String[] args) {


for(int i=10;i<= 1000 0000;i*= 10){
test(i);
}
}

getKey get
key

JDK1.8 JDK1.7 15% size 100%


Hash JDK1.8 Hash

Hash
Key hashCode HashMap

class Key implements Comparable<Key> {

//…

@Override
public int hashCode() {
return 1;
}
}

main 知

size JDK1.7 JDK1.8


HashMap
O(n) O(logn) hash
hash

知 2.2 GHz Intel Core i7 16 GB 1600 MHz DDR3 SSD


JVM 64 OS X 10.10.1

18.HashMap ?
(1) ⾃ HashMap map
map ⾃

(2) 1

(3) HashMap HashMap


ConcurrentHashMap

(4) JDK1.8 HashMap

(5) JDK1.8 HashMap JDK1.8

https://zhuanlan.zhihu.com/p/21673805
https://www.jianshu.com/p/939b8a672070
https://www.jianshu.com/p/c45b6d782e91
https://blog.csdn.net/Mrs_chens/article/details/92761868
https://blog.csdn.net/riemann_/article/details/87217229
https://blog.csdn.net/qq_34626097/article/details/83053004
https://blog.csdn.net/u010887744/article/details/50575735

&

1.error exception
error java
Java 下

exception 爱还然

2. 5 RuntimeException
(1)Java.lang.NullPointerException ; 知

(2)Java.lang.NumberFormatException 为 ; 知 为

(3)Java.lang.IndexOutOfBoundsException

(4)Java.lang.IllegalArgumentException

(5)Java.lang.ClassCastException
3.throw throws ?
throw知

(1)throw

(2)throw throw

throws知

(1)@throws

(2)throws 爱

(3)throws

4.Java
:

( (CheckedException)) ( (UnCheckedException))

5.
Exception RuntimeException
throw

initCause

6.Java
: try catch throws

1. try catch:

try{} catch{} 爱

2.throw throws知

throw throw

throws

7. Java ?
Java 样reflection

Java

8.
1. JDBC 会以
2. Web Sevlet
3. Eclispe 道
4. 发 Spring

9.java




10.Java

java.lang.Class; //类
java.lang.reflect.Constructor;//构造⽅方法
java.lang.reflect.Field; //类的成员变量量
java.lang.reflect.Method;//类的⽅方法
java.lang.reflect.Modifier;//访问权限

11.

知 ⼩知 JVM java

12. ?
1.
Class.forName(“ ”); 知com.mysql.jdbc.Driver Driver jvm

.class; Class<友> clz


.getClass();
2. new
Clazz.getConstructor([String.class]);
Con.newInstance([ ]);
3. class 样 new 样 )
Cls.newInstance();

https://blog.csdn.net/qq_37875585/article/details/89340495
https://www.cnblogs.com/whoislcj/p/6038511.html
IO&NIO
1. IO

(process)

2.java
知 为 然 知 然

3.
1. 为 IO
年 样
2. IO 为 为 为
4.
BufferedInputStream BufferedOutputStream
为 BufferedReader BufferedWriter

5. IO
不 IO然 不 IO然 IO然 以 IO IO

6. IO blocking IO
IO 不 现
recvfrom kernel
IO 我 知 现 样 IO
UDP 我 知
现 kernel block
blocking IO IO block

7. I/O nonblocking IO
不 I/O 不 I/O
I/O
CPU

read kernel block


error error read kernel
read system call kernel 现
又 nonblocking IO kernel

不 IO IO IO
不 IO
CPU 又 CPU (select
poll ) I/O 不
I/O 不 IO IO 不
select select IO
epoll IO 又
8.I/O (IO multiplexing)
I/O IO, select poll epoll
socket socket functon 不
IO不 不 IO IO
IO 又 IO
( )
select

IO IO bloking IO
socket 不 socket select不 不 IO socket IO 不

9. I/O
为 SIGIO sigaction

SIGIO recvfrom
10. I/O(asynchronous IO)
IO ( )
aio_read样Posix I/O aio lio 然 然
样 read 3 然
不 I/0 现

read kernel
asynchronous read block kernel
现 kernel
signal read

11.NIO IO
NIO New IO 会 JDK1.4 NIO IO
NIO NIO IO Java API NIO
NIO NIO
12.NIO IO
 NIO 么 IO ⼈ NIO NIO

   NIO IO 友
  
NIO
   IO

13.NIO
channel然buffer然selector

14. channel
Channel样 然
Java NIO I/O

I/O I/O
FileChannel然SocketChannel

Stream Buffer Buffer


Stream 样 InputStream OutputStream
不 I/O

15.Java NIO ?
FileChannel知
DatagramChannel: UDP
SocketChannel知TCP
ServerSocketChannel知 TCP

16.Buffer ?
NIO byte Buffer API

Java NIO Buffer ByteBuffer然CharBuffer然IntBuffer


17. Buffer
buffer 知ByteBuffer然CharBuffer然DoubleBuffer然FloatBuffer然IntBuffer然
LongBuffer然ShortBuffer 可 样4 8 Boolean buffer
MappedByteBuffer

18.buffer
1 然 buffer
2 然 buffer.flip()
3 然 buffer
4 然 buffer.clear() buffer.compact()

buffer buffer 没 buffer flip() buffer


buffer
   buffer 2 知 clear()
compact()
   知clear buffer compact
buffer

// 创建⼀一个容量量为48的ByteBuffer
ByteBuffer buf = ByteBuffer.allocate(48);
// 从channel中读(取数据然后写)⼊入buffer
int bytesRead = inChannel.read(buf);
// 下⾯面是读取buffer
while (bytesRead != -1) {
buf.flip(); // 转换buffer为读模式
System.out.print((char) buf.get()); // ⼀一次读取⼀一个byte
buf.clear(); //清空buffer准备下⼀一次写⼊入
}
19.Selector ?
Selector样 样
select()

20.
4 知

Accept知
Connect知
Read知
Write知

21. Selector
不 I/O 样 不 I/O 样 CPU Selector
起 不 Selector
Read select()
CPU

22.Selector Channel

Selector Selector Channels Selector select()


不 Channels select()

https://www.cnblogs.com/sharing-java/p/10791802.html
https://blog.csdn.net/zengxiantao1994/article/details/88094910
https://www.cnblogs.com/xueSpring/p/9513266.html

1. ?

2.

3. ?
1. Thread

2. Runnable

3. Callable Future

4.Thread start() run() ?


1.start样 run
又 Thread start()
Thread run() run()
Run CPU
2.run样 run
又 ——

5. NEW
new Thread start
6. RUNNABLE
start runnable
cpu 样RUNNABLE)

7. RUNNING
cpu

8. BLOCKED

BLOCKED sleep, wait


不 io BLOCKED
不 BLOCKED

9. TERMINATED
TERMINATED

TERMINATED :

JVM Crash

10.

11.i—————— System.out.println()
:

public class XkThread extends Thread {

private int i = 5;
@Override
public void run() {
System.out.println("i=" + (i——————) + " threadName=" +
Thread.currentThread().getName());
}

public static void main(String[] args) {


XkThread xk = new XkThread();
Thread t1 = new Thread(xk);
Thread t2 = new Thread(xk);
Thread t3 = new Thread(xk);
Thread t4 = new Thread(xk);
Thread t5 = new Thread(xk);

t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}

i=5 threadName=Thread-1
i=2 threadName=Thread-5
i=5 threadName=Thread-2
i=4 threadName=Thread-3
i=3 threadName=Thread-4

println() i—————— println()

println() :

public void println(String x) {


synchronized (this) {
print(x);
newLine();
}
}

12.

System.out.println(Thread.currentThread().getName());

13.
public class XKThread extends Thread {

@Override
public void run() {
System.out.println("run run run is " + this.isAlive() );
}

public static void main(String[] args) {


XKThread xk = new XKThread();
System.out.println("begin ——— " + xk.isAlive());
xk.start();
System.out.println("end ————— " + xk.isAlive());

}
}

14.sleep()
sleep() “ ” 样

15. ?
jdk1.5 TimeUnit, sleep

2 22 55 899

Thread.sleep(8575899L);
TimeUnit.HOURS.sleep(3);
TimeUnit.MINUTES.sleep(22);
TimeUnit.SECONDS.sleep(55);
TimeUnit.MILLISECONDS.sleep(899);

16.
run

stop() suspend() resume()

Thread.interrupt() ,

17.interrupted isInterrupted
interrupted : ,

isInterrupted 知

18.yield
cpu cpu
cpu

:(cpu )

public class XKThread extends Thread {

@Override
public void run() {
long beginTime = System.currentTimeMillis();
int count = 0;
for (int i = 0; i < 50000000; i++) {
count = count + (i + 1);
}
long endTime = System.currentTimeMillis();
System.out.println("⽤用时 = " + (endTime - beginTime) + " 毫秒! ");
}

public static void main(String[] args) {


XKThread xkThread = new XKThread();
xkThread.start();
}

⽤用时 = 20 毫秒!

yield (cpu )

public class XKThread extends Thread {

@Override
public void run() {
long beginTime = System.currentTimeMillis();
int count = 0;
for (int i = 0; i < 50000000; i++) {
Thread.yield();
count = count + (i + 1);
}
long endTime = System.currentTimeMillis();
System.out.println("⽤用时 = " + (endTime - beginTime) + " 毫秒! ");
}

public static void main(String[] args) {


XKThread xkThread = new XKThread();
xkThread.start();
}

}
:

⽤用时 = 38424 毫秒!

19.
cpu cpu

Java 1 10 5 知
java.lang.IllegalArgumentException

20.
a b b a

21.

public class Run extends Thread{

public static void main(String[] args) {


try {
ThreadLow low = new ThreadLow();
low.setPriority(2);
low.start();

ThreadHigh high = new ThreadHigh();


high.setPriority(8);
high.start();

Thread.sleep(2000);
low.stop();
high.stop();
System.out.println("low = " + low.getCount());
System.out.println("high = " + high.getCount());
} catch (InterruptedException e) {
e.printStackTrace();
}

class ThreadHigh extends Thread {


private int count = 0;

public int getCount() {


return count;
}

@Override
public void run() {
while (true) {
count++;
}
}
}

class ThreadLow extends Thread {


private int count = 0;

public int getCount() {


return count;
}

@Override
public void run() {
while (true) {
count++;
}
}
}

low = 1193854568
high = 1204372373

22.
Java

23.
Java 下
JVM

24.Java
GC样是了

25.
Thread.setDaemon(true)
PS:Daemon

25.Java Daemon finally


Java 下 Daemon finally

public class XKDaemon {


public static void main(String[] args) {
Thread thread = new Thread(new DaemonRunner(),"xkDaemonRunner");
thread.setDaemon(true);
thread.start();

static class DaemonRunner implements Runnable {

@Override
public void run() {
try {
SleepUtils.sleep(10);
} finally {
System.out.println("Java⼩小咖秀 daemonThread finally run …");
}

}
}
}

finally

26.

public ClassLoader getContextClassLoader()

样 Java

public void setContextClassLoader(ClassLoader cl)

27.join
join join a, b , a
b blocked

28. synchronized?
synchronized

29.synchronized jvm
monitor enter monitor exit

30.synchronized ?

31.synchronized ?
—————>

—————> Class

—————> synchonized

32.Java
synchronized Java 下 3 (Word)
2

Tips:32 下 4

33.Java

34.Java
32 JVM Mark Word

35.Mark Word
Mark Word
64 下 Mark Word 64bit

36.
Java SE 1.6 “ ” “

Java SE 1.6 4 知 然 然 然

37.

吃 ID, cas
Mark Word
Mark Word
1样 ), cas cas

38.
java6 7

-XX:BiasedLockingStartupDelay=0

39.
JVM :-XX:-UseBiasedLocking=false,

Tips:

40.
jvm 吃 Mark
Word cas Mark Word

41.
cas displaced Mark Word

42.

43.

44.Java
Java cas JVM CAS CMPXCHG
到CAS CAS

45.CAS 3
ABA

46. ABA

cas A, B,
A, cas

A-B-A —> 1A-2B-3A

jdk1.5 ,Atomic AtomicStampedReference ABA

47.CAS
jvm pause

然 (de-pipeline), cpu
0

然 cpu cpu

48.CAS

然 ,x=1,k=a, xk=1a cas xk

Tips:java 1.5 ,jdk AtomicReference


cas

49.volatile
volatile synchronized, “ “

Java 3 volatile Java⼼


volatile,Java

50. /

51.wait
wait() wait() Object
“ ” wait()

wait
wait()

52.notify
notify() Object
wait
notify

53.notify/notifyAll
notify notifyAll

54. /
synchronized(obj) {
while(条件不不满⾜足) {
obj.wait();
}
执⾏行行对应逻辑
}

synchronized(obj) {
改变条件
obj.notifyAll();
}

55.ThreadLocal

56.ThreadLocal

get(), set(T)

public class XKThreadLocal {

public static ThreadLocal threadLocal = new ThreadLocal();

public static void main(String[] args) {


if (threadLocal.get() == null) {
System.out.println("未设置过值");
threadLocal.set("Java⼩小咖秀");
}
System.out.println(threadLocal.get());
}

未设置过值
Java⼩小咖秀

Tips: null

57. get() null


initialValue()


public class ThreadLocalExt extends ThreadLocal{

static ThreadLocalExt threadLocalExt = new ThreadLocalExt();

@Override
protected Object initialValue() {
return "Java⼩小咖秀";
}

public static void main(String[] args) {


System.out.println(threadLocalExt.get());
}
}

Java⼩小咖秀

58.Lock
Java5 synchronized Java5
Lock

59.Lock synchronized

60. ReentrantLock

61.

然 n n

62.ReentrantLock
:

final boolean nonfairTryAcquire(int acquires) {


final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}

63.

FIFO

64.

Java ReentrantReadWriteLock

65.LockSupport

66.Condition
Object Lock /

67.Condition
:

public class XKCondition {


Lock lock = new ReentrantLock();
Condition cd = lock.newCondition();

public void await() throws InterruptedException {


lock.lock();
try {
cd.await();//相当于Object ⽅方法中的wait()
} finally {
lock.unlock();
}
}

public void signal() {


lock.lock();
try {
cd.signal(); //相当于Object ⽅方法中的notify()
} finally {
lock.unlock();
}
}

68.ArrayBlockingQueue?
不 FIFO

69.PriorityBlockingQueue?
不 不 不

70.DelayQueue?
不 Delayed
Comparable

71.Java
ConcurrentHashMap然CopyOnWriteArrayList 然CopyOnWriteArraySet 然
ConcurrentLinkedQueue然
ConcurrentLinkedDeque然ConcurrentSkipListMap然ConcurrentSkipListSet然ArrayBlockingQueue然

LinkedBlockingQueue然LinkedBlockingDeque然PriorityBlockingQueue然SynchronousQueue然

LinkedTransferQueue然DelayQueue

72.ConcurrentHashMap
HashMap,java7 16 Java8
CAS 8 样 jdk

73.ConcurrentLinkedQueue

cas
样 jdk

74.
不 不

1然 不 知 不

2然 不 知

75.

76.Java

ArrayBlockingQueue: 数组结构组成的 |有界阻塞队列列


LinkedBlockingQueue: 链表结构组成的|有界阻塞队列列
PriorityBlockingQueue: ⽀支持优先级排序|⽆无界阻塞队列列
DelayQueue: 优先级队列列实现|⽆无界阻塞队列列
SynchronousQueue: 不不存储元素| 阻塞队列列
LinkedTransferQueue: 链表结构组成|⽆无界阻塞队列列
LinkedBlockingDeque: 链表结构组成|双向阻塞队列列

77.Fork/Join
java7 发

78.


他 他
79.

80.Java Atomic ?
AtomicBoolean:

AtomicInteger:

AtomicLong:

81.Java Atomic ?
AtomicIntegerArray:

AtomicLongArray:

AtomicReferenceArray:

AtomicIntegerArray:

82.Java Atomic ?

AtomicReference :

AtomicReferenceFieldUpdater:

AtomicMarkableReference: boolean
AtomicMarkableReference(V initialRef,boolean initialMark)

83.Java Atomic ?
AtomiceIntegerFieldUpdater:

AtomiceLongFieldUpdater:

AtomiceStampedFieldUpdater:

84.JDK
: CountDownLatch然CyclicBarrier然Semaphore

: Exchanger

85.CountDownLatch

CountDownLatch int n n
:

countDown() : n 1

await() : 不 n 0

await(long time,TimeUnit unit) : 不

tips: 0 0 await 不

86.CyclicBarrier

样 不

CyclicBarrier CyclicBarrier(int parities) , 吧


await CyclicBarrier 不

87.CountDownLatch CyclicBarrier
CountDownLatch知

知 n

CyclicBarrier知

知 样 reset() )

知n

88.Semaphore

89.Exchanger
Exchanger
exchange() exchange

exchange(V x,long timeout,TimeUnit unit),

Exchanger

90.


知 然 然

91.
1然 -> ->

2然 -> ->

3然 ->

->

4然

92.

public ThreadPoolExecutor( int corePoolSize,


int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)

1.corePoolSize:

2.maximumPoolSize: ⼼

3.keepAliveTime:

4.unit: 样DAYS)然 (HOURS)然 (MINUTES然


MILLISECONDS)然 (MICROSECONDS)然 (NANOSECONDS)

5.workQueue: 不

不 知

ArrayBlockingQueue: 不

LinkedBlockingQueue: 不

SynchronizedQueue: 不

PriorityBlockingQueue: 不
6.threadFactory知

7. handler:
AbortPolicy
AbortPolicy:
CallerRunsPolicy:
DiscardOldestPolicy:
DiscardPolicy:
RejectedExecutionHandler

93.
execute() submit()

execute():

submit(): future future


future get() get() 不
get(long timeout,TimeUnit unit)

94.
shutdown() shutdownNow()
interrupt

shutdownNow STOP,

shutdown shutdown

isShutdown true, isTerminaed true

shutdown shutdownNow

95.

cpu 然IO


cpu , n+1
io 2n
io cpu
->
->
Runtime.getRuntime().availableProcessors() cpu

96.Executor
JDK5 Runnable Callable, Executor发

97.Executor
ThreadPoolExecutor : Executors

3 ThreadPoolExecutor知SingleThreadExecutor然FixedThreadPool然
CachedThreadPool

ScheduledThreadPoolExecutor 知 Executors

2 ScheduledThreadPoolExecutor知ScheduledThreadPoolExecutor然
SingleThreadScheduledExecutor

Future :Future Future FutureTask

Runnable Callable: ThreadPoolExecutor ScheduledThreadPoolExecutor


Runnable Callable

98.FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {


return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());}

corePoolSize maxPoolSize nThreads

corePoolSize ,keepAliveTime
0

1. corePoolSize,

2. corePoolSize, LinkedBlockingQueue

3. 1 LinkedBlockingQueue

LinkedBlockingQueue 样 Integer.MAX_VALUE)
1. corePoolSize corePoolSize

2.maxnumPoolSize

3.keepAliveTime

4. FixedThreadPool( shundown shundownNow))

5. OOM

99.SingleThreadExecutor
worker Executor

public static ExecutorService newSingleThreadExecutor() {


return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}

corePoolSize maxnumPoolSize 1 FixedThreadPool

FixedThreadPool.

100.CachedThreadPool

public static ExecutorService newCachedThreadPool() {


return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());

corePoolSize 0 maxmumPoolSize Integer.MAX_VALUE keepAliveTime 60

1. SynchronousQueue.offer (Runnable task) maximumPool S


ynchronousQueue.poll(keepAliveTIme,TimeUnit.NANOSECONDS) offer
poll ,execute ;
⽇2

2. maximumPool maximumPool
SynchronousQueue.poll (keepAliveTime TimeUnit.NANOSECONDS) ⽇1
CachedThreadPool execute()
3. ⽇2 SynchronousQueue.poll (keepAliveTime
TimeUnit.NANOSECONDS) poll SynchronousQueue 60
60 ( ⽇1)
; 60 ,
CachedThreadPool

太Java 感
太Java 感
太Java 感

JVM

1.JDK JRE JVM


Jdk (Java Development Kit) : java Java Jre

Jre 样Java Runtime Environment) :Java Jvm

Jvm (Java Virtual Machine) :

Java Java Java 下 ⽤


Java Java 下 样

Jdk Jre Jre jvm

2.
java -XX:+TraceClassLoading

Java -verbose

3. class 10 ?
MagicNumber
Version
Constant_pool
Access_flag
This_class
Super_class
Interfaces
Fields
Methods
Attributes

4. jvm

5.


然 然 然 也 们

6.Java
下 Java 又
然 然 然
吃 下

7.
下 下 下 Java
下 Native

8.Java
Java 下 Java 下

Tips知 JIT 然

9.
下 然 然 然

10.
Class 然 然 然
样Constant PoolTable 为

11. StackOverflowError?
下 ⼼ StackOverflowError

12.Java7 Java8
Java8 样Metaspace 样Native memory)

13.
(Heap) 样Stack) Java 后
Java

14.
下 Java 下
OutOfMemoryError

Tips:JDK1.4 NIO样new input/output) (Channe) 样Buffer)


I/O Native 会 , Java
DirectByteBuffer

15.
OutOfMemoryError

16.
gc roots 是了

17.

public class Cat {

public static void main(String[] args) {


List list = new ArrayList();
while (true) {
list.add(new Cat());
}
}

18. OutOfMemoryError
下 ⾃ OutOfMemoryError

19. StrackOverflowError?

public static void main(String[] args) {


eat();
}

public static void eat () {


eat();
}

20. ?
-XX:MaxDirectMemorySize Java

21.Java
= + Java8 Permanent Generation

(Young) Eden S0样from) S1(to)

22.Edem : from : to ?
Edem : from : to = 8 : 1 : 1

–XX:SurvivorRatio

23.
GC 是了 GC 是了
是了 我

24. ?
a, a, a 1 1
0

25.
(
)
instanceOopDesc Mark World 是了

26.JVM
- 样Mark_Sweep)

(Copying)

- 好 样Mark-Compact)

27. -

是了

28.
:

29. -
30.
下 是了 “ ”

31.
是了 是了
32.Stop The World?
是了 Sun "Stop The World"

33.Serial ?
stop the world 是了 stop the world ,

34.PartNew ?
Serial Serial

“-XX:+UseParNewGC” ParNew

36.Parallel Scavenge?
PartNew
(Thoughput CPU /CPU
= /( +是了 ))
CPU

2 , cpu
: -XX:MaxCcPauseMillis -XX:GCTimeRatio

37.Parallel Old ?
Parallel Scavenge - JDK 1.6

38.CMS ?
Concurrent Mar Sweep
- 是了

39.CMS ?
1. (stop the world)
2.
3. (stop the world)
4.
GC Roots
Gc Roots Tracing

41.CMS

cpu
是了

42.G1 ?
Garbage First jdk 1.6_update14 g1

G1 -

M 是了
N java(rtsj) 是了

42. G1
是了 g1 Java
样 然 没 是了
⼼ 是了
43.
jps (Jvm process status tool ), ps

下 (Main Class,main()
下 ID

知 jps [options] [hostid]

-q lvmid,

-m 下 main()

-l Jar Jar

-v 下 JVM

44.
jstat(JVM Statistics Montoring Tool) 下
下 然 然是了 然jit

jstat [option vmid [interval[s|ms] [count]] ]

interval

count

option 下 3 知

是了

45.jstat
-class 然 然

-gc Java Eden 2 survivor 然

-gccapacity -gc Java

-gcutil -gc

-gccause -gcutil GC

-gcnew GC

-gcnewcapacity -gcnew

-gcold GC

-gcoldcapacity -gcold
-compiler jit 然

45. ?
jinfo(Configuration Info for Java) 下

jps -v 下

jinfo : jinfo [option] pid

46.
jmap(Memory Map for Java) 样 heapdump dump

知jmap [option] vmid

finalize Java 然

-dump Java live dump


-finalizerinfo F -Queue Finalizer finalize Linux/Solaris

-heap Java 然 然
-histo 然 然
-F 下 -dump dump

47.
jhat ( JVM Heap Analysis Tool) jmap

48.
jstack(Stack Trace for Java) 下 样 thread dump
javacore 下

jstack [option] vmid

-F

-l

-m C/C++

49.
JConsole VisualVM JDK

50. ?
-感 -感 -感 -感 -感 -感


太 JVM & G1 GC感
太 Java 下 知JVM ⼦感
太 Java 下 知JVM 最 感

Linux
1. Linux
UNIX · · 1991
Minix Unix POSIX Unix 然 然
CPU Unix 然 32 64

2.Linux

3.

4. shell
GNU bash shell linux
shell

5.bash
linux shell GNU man linux
man

6.

7. ?
知 下 下

着 (/) /usr/local

知⼼

: /usr/local

➜ local ls
Caskroom Frameworks bin go lib sbin var
Cellar Homebrew etc include opt share
➜ local cd go

( ):

为(.) : ;
为(..) :

8.
pwd

[root@iz2ze76ybn73dvwmdij06zz local]# pwd


/usr/local

9.
: cd destination

destination :

10. ? ?
ls 知

➜ local ls
Caskroom Frameworks bin go lib sbin var
Cellar Homebrew etc include opt share

ls , ls -F
样 /) 样 /)

ls -R

11. ?
:touch

: touch …

➜ test touch a
➜ test ls
a
➜ test touch b c
➜ test ls
a b c

知mkdir

: mkdir …

➜ test mkdir aa
➜ test mkdir bb cc
➜ test ls
a aa b bb c cc
➜ test ls -F
a aa/ b bb/ c cc/

12. ? ?
: rm destination

-i ,-r -f

rm ,

➜ xktest rm jdk
rm: jdk: is a directory
➜ xktest rm -r jdk
➜ xktest ls

rm -i , -i

➜ xktest touch tomcat


➜ xktest rm -i tomcat
remove tomcat? n

rm -rf 说**

13.

➜ xktest ls java*
javaxiaokaxiu
javaxiaokaxiu java (tab) javaxiaokaxiu,

14.
: cp source target

target -i
,n y

➜ xktest cp a c
➜ xktest cp -i a c
overwrite c? (y/n [n]) y
➜ xktest ls
a c

15.
知 mv soucre target

➜ xktest ls
➜ xktest touch java
➜ xktest ls
java
➜ xktest mv java java1.8
➜ xktest ls
java1.8

jdk java1.8 jdk

➜ xktest ls
java1.8
➜ xktest mkdir jdk
➜ xktest mv java1.8 jdk
➜ xktest ls -R
jdk

./jdk:
java1.8

16.

下 下

17. ?
: file destination

➜ apache file tomcat


tomcat: ASCII text

file text 为 ASCII

18.
: cat destination

-n -b 样 )

➜ apache cat -n tomcat


1 text
2 text
3
4 start
5 stop
6 restart
7 end
➜ apache cat -b tomcat
1 text
2 text

3 start
4 stop
5 restart
6 end

19.
: tail destination

10 -n n

➜ apache tail -n 2 tomcat


restart
end

: head destination

10 -n n

➜ apache head -n 2 tomcat


text
text

20. ?
sort sort

: sort destination

sort -n -n

sort -M Jan然Feb然Mar -M

21.
: grep [options] pattern [file]

➜ apache grep start tomcat


start
restart

-v

➜ apache grep -v start tomcat


text
text

stop
end

-n

-c

22. ?

23. ?
.gz

好 : gzip destination

➜ apache gzip tomcat


➜ apache ls
tomcat.gz

: gunzip destination
➜ apache gunzip tomcat.gz
➜ apache ls
tomcat

24.Linux ?
zip 好 ⽣ tar

: tar function [options] obj1 obj2

➜ apache tar -cvf service.tar service1 service2 // 创建规定⽂文件service.tar


a service1
a service2
➜ apache tar -tf service.tar //查看⽂文件中的⽬目录内容
service1
service2
➜ apache tar zxvf service.tar //解压
x service1
x service2

25. ?
history

4463 touch service1 service2


4464 ls
4465 tar -cvf service.tar service1 service2
4466 tar -tf service.tar
4467 tar zxvf service
4468 tar zxvf service.t
4469 tar zxvf service.tar
4470 ls
4471 tar -zxvf service.tar
4472 ls

26. ? ?
alias -p
[root@iz2ze76ybn73dvwmdij06zz ~]# alias -p
alias cp='cp -i'
alias egrep='egrep —color=auto'
alias fgrep='fgrep —color=auto'
alias grep='grep —color=auto'
alias l.='ls -d .* —color=auto'
alias ll='ls -l —color=auto'

alias li = 'ls -li'

27.
bash shell (environment variable) shell
⼼ shell

bash shell :

知 shell shell
知 shell

28. ?
/etc/passwd

[root@iz2ze76ybn73dvwmdij06zz ~]# cat /etc/passwd


root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin

UID( )
ID(GID)( )
( )
HOME
shell

29.
[root@iz2ze76ybn73dvwmdij06zz ~]# useradd -D//查看系统默认创建⽤用户信息
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
[root@iz2ze76ybn73dvwmdij06zz ~]# useradd xiaoka//添加⽤用户

[root@iz2ze76ybn73dvwmdij06zz /]# userdel xiaoka//删除⽤用户

30.

[root@iz2ze76ybn73dvwmdij06zz ~]# cat /etc/group


root:x:0:
bin:x:1:
daemon:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
[root@iz2ze76ybn73dvwmdij06zz ~]# groupadd java //创建组
[root@iz2ze76ybn73dvwmdij06zz ~]# groupdel java //创建组

31. ? ?

[root@iz2ze76ybn73dvwmdij06zz xiaoka]# ls -l
总⽤用量量 0
-rw-r—r— 1 root root 0 4⽉月 21 13:17 a
-rw-r—r— 1 root root 0 4⽉月 21 13:17 b
-rw-r—r— 1 root root 0 4⽉月 21 13:17 c
-rw-r—r— 1 root root 0 4⽉月 21 13:17 d
-rw-r—r— 1 root root 0 4⽉月 21 13:17 e

1然 :

-
d
l
c 为
b
n

2然 为 :

r
w
x
3然 3 3 :

31. ?
chmod options mode file

[root@xiaoka ~]# chmod +x filename

32. ?

[root@xiaoka ~]# sh sleep.sh


hello,xiaoka
[root@xiaoka ~]# ./sleep.sh
hello,xiaoka

33. ?
: yum list installed

: yum install package_name

: yum update package_name

:yum remove package_name //

:yum erase package_name

34. ?

tar -zxvf xx.gz //解包


cd xx
./configure
make
make install

35.vim ?
:
们 :

h: 为
j: ( )
k: ( )
l: 为

vim :

PageDown( Ctrl+F):
PageUp( Ctrl+B):
G:
num G: num
gg:

vim:

q:
q!:
w filename:
wq:

36. ?
df 年

-m 快 G g

[root@iz2ze76ybn73dvwmdij06zz ~]# df
⽂文件系统 1K-块 已⽤用 可⽤用 已⽤用% 挂载点
devtmpfs 1931568 0 1931568 0% /dev
tmpfs 1940960 0 1940960 0% /dev/shm
tmpfs 1940960 720 1940240 1% /run
tmpfs 1940960 0 1940960 0% /sys/fs/cgroup
/dev/vda1 41152812 9068544 30180560 24% /
tmpfs 388192 0 388192 0% /run/user/0

du 然 然 年

[root@iz2ze76ybn73dvwmdij06zz src]# du
4 ./debug
4 ./kernels
12

37. ?
ps

ps
[root@iz2ze76ybn73dvwmdij06zz ~]# ps
PID TTY TIME CMD
10102 pts/0 00:00:00 bash
10131 pts/0 00:00:00 ps

38.
ps top

3 : 1 然 5 15
1 15

39. ?
Ctrl + c

40.

[root@iz2ze76ybn73dvwmdij06zz ~]# ./sleep.sh &

Ctrl + c

41. ?
kill TERM(

: kill [-signal] PID …


####

42.
ping ping ( IMCP ECHO REQUEST)

ping 样 1

43. ?
netstat -ntulp|grep 8080

[root@iz2ze76ybn73dvwmdij06zz ~]# netstat -ntulp|grep 8080


tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN
4517/java

-t (tcp) tcp
-u (udp) udp
-n
-l Listen( )
-p

44.
find ( )

find

name :

[root@iz2ze76ybn73dvwmdij06zz ~]# find -name xiaoka


./xiaoka

[root@iz2ze76ybn73dvwmdij06zz ~]# find ~|wc -l


17130

:
[root@iz2ze76ybn73dvwmdij06zz ~]# find ~ -type d | wc -l
7340

find :b 然c 为 然d 然f 然l 为

45.

[root@iz2ze76ybn73dvwmdij06zz ~]# hostname//查看当前主机名


iz2ze76ybn73dvwmdij06zz
[root@iz2ze76ybn73dvwmdij06zz ~]# hostname xiaoka//修改当前主机名
[root@iz2ze76ybn73dvwmdij06zz ~]# hostname
xiaoka

centos7

[root@iz2ze76ybn73dvwmdij06zz ~]# hostnamectl set-hostname xiaoka


[root@iz2ze76ybn73dvwmdij06zz ~]# hostname
xiaoka
[root@xiaoka ~]#

然 :/etc/hostname

[root@xiaoka ~]# vim /etc/hostname

46. ip 8080 ?

iptables -I INPUT -s ip -p tcp —dport 8080 -j REJECT

47. ip ?
/etc/hosts

48. sed 5 ? ?
5 :

➜ apache sed -n "5p" tomcat


stop

:
[root@xiaoka ~]# cat story
Long ago a lion and a bear saw a kid.
They sprang upon it at the same time.
The lion said to the bear, “I caught this kid first, and so this is mine.”
[root@xiaoka ~]# cat story
They sprang upon it at the same time.
The lion said to the bear, “I caught this kid first, and so this is mine.”

为 :

➜ apache cat story


Long ago a lion and a bear saw a kid.
They sprang upon it at the same time.
The lion said to the bear, “I caught this kid first, and so this is mine.”
➜ apache sed 's#this#that#g' story
Long ago a lion and a bear saw a kid.
They sprang upon it at the same time.
The lion said to the bear, “I caught that kid first, and so that is mine.”

49. ?
tomcat :

➜ apache cat tomcat


text21
text22
text23
start
stop
restart
end

➜ apache head -3 tomcat


text21
text22
text23
➜ apache sed -n '1,3p' tomcat
text21
text22
text23
➜ apache awk 'NR>=1&&NR<=3' tomcat
text21
text22
text23

50. awk 2 3 ?
➜ apache awk 'NR==3{print $(NF-2)}' story
this
➜ apache cat story
Long ago a lion and a bear saw a kid.
They sprang upon it at the same time.
The lion said to the bear, “I caught this kid first, and so this is mine.”

太 Linux 感
太 感
太Linux shell ( 3 感
太Linux 感

Mysql

1. ?
会 “ 然 得会” 然 然

2. ?

mysql> ? create table


Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,…)
[table_options]
[partition_options]
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,…)]
[table_options]
[partition_options]
[IGNORE | REPLACE]
[AS] query_expression

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name

3.MySql ?
MyISAM然 InnoDB然BDB然MEMORY然MERGE然EXAMPLE然NDB Cluster然 ARCHIVE然CSV然
BLACKHOLE然FEDERATED

Tips:InnoDB BDB

4. 2
1.Myisam Mysql create
Myisam

MyISAM 年 ⾃ .frm ( )
然.MYD (MYData )然.MYI (MYIndex )

io

2.InnoDB 然 这 也 Myisam
InnoDB 年

6.
, ENGINE=xxx

create table person(


id int primary key auto_increment,
username varchar(32)
) ENGINE=InnoDB

6.
: ,
.
:

1. MyISAM: MySQL , Web然 得

2. InnoDB: ACID
3. Memory: RAM
4. Merge:⼼ MySQL DBA MyISAM , 1
得 VLDB

7.
:

: , :

1. MyISAM
MyISAM
2. MEMORY
MEMORY CHAR VARCHAR
CHAR
3. InnoDB
VARCHAR
InnoDB (
) CHAR VARCHAR
CHAR
VARCHAR VARCHAR 年 I/O

8.char & varchar

9.Mysql
mysql 为 ( show character set mysql 为 )
然 会然 为

mysql 为 为 (CHARACTER) (COLLATION)

10. ?
, 为 为 然
,

为 utf8然gb2312然gbk然latin1 gb2312 gbk


gb2312 会 gbk 会 ⾥ ( :学) 为 ⼀
⾥ gbk

11.
会 然 会

12.
1. WHERE
SELECT
2. ⼰ ⼰

3. ,
CHAR(200) 10 20 为 ⼰

4. n MySQL n
(
n 为 )
5. 年
, ,

MySQL

MySQL

6. “ <”然“ < = ”然“ = ”然“ > =”然“ > ” BETWEEN


LIKE (
STRCMP( ))

13.MySql ?

1. BTREE
2. HASH
3. FULLTEXT
4. R-Tree

1然 样clustered index

2然 样non-clustered index

1. 知
2. 知 + 样 null
3. 知 + 样 null +
4. 知
5. 知

14.Hash B+ :
hash hash , , hash ,
.B+ ⼀ . ,
, .

hash ( ), .

hash hash , , .
B+ 来 ( , , ), .

hash , .
hash . hash .AAAA
AAAAB .
hash , B+ 为 ( 什 , )
.
hash , . , , hash
, . B+ , ,
.

, , B+ . hash .

15. ?
, 多 , ,
.

, , select age from employee


where age < 20 , , age , .

16. ?

select * from table_name order by id desc limit 1;

17.MySQL id ?

id

18.sql
: 为 sql sql

19. 3NF ?
1NF 会
2NF ⼰ ⼰ ⼰
3NF 今 今

20. NULL ?
NULL , ''( 为) NOT NULL ⼼

NULL IS NULL IS NOT NULL

21. ?
会 MySQL

22. 4
4 样ACID 知

Atomicity
Consistency
Isolation 会⼼

Durability

23.
READ_UNCOMMITTED

然 然
READ_COMMITTED


REPEATABLE_READ

然 然
SERIALIZABLE
然 然

24.InnoDB ?
样REPEATABLE-READ

mysql> select @@global.tx_isolation;


+———————————+
| @@global.tx_isolation |
+———————————+
| REPEATABLE-READ |
+———————————+
1 row in set, 1 warning (0.01 sec)

25.


26.

27.

28.
:

CREATE USER 'username'@'host' IDENTIFIED BY 'password';

GRANT privileges ON databasename.tablename TO 'username'@'host';

username知
host知 localhost 为%
password知
databasename: 会
tablename: *

29.
desc table_name;

mysql> desc zipkin_spans;


+———————+———————+———+——+————+———+
| Field | Type | Null | Key | Default | Extra |
+———————+———————+———+——+————+———+
| trace_id_high | bigint(20) | NO | PRI | 0 | |
| trace_id | bigint(20) | NO | PRI | NULL | |
| id | bigint(20) | NO | PRI | NULL | |
| name | varchar(255) | NO | MUL | NULL | |
| parent_id | bigint(20) | YES | | NULL | |
| debug | bit(1) | YES | | NULL | |
| start_ts | bigint(20) | YES | MUL | NULL | |
| duration | bigint(20) | YES | | NULL | |
+———————+———————+———+——+————+———+
8 rows in set (0.01 sec)

30.Mysql
1.delete : 很

delete from table_name;


2.truncate: 很 delete

truncate table table_name;

3.drop:

drop table table_name;

31.like ?
Xxx% %xxx

32.

33.

34.
( ) ‘ ’

35.

36.

样 +

-感 什 -> 什
37. ?

SELECT * FROM table_name ORDER BY rand() LIMIT 1;

38.Mysql

39.

show index from table_name;

40.

NULL

为 like 为. %xxx
mysql .
, , 为 , .

41.MVVC
MVCC InnoDB MVCC

样system version number
42.sql

sql

sql “ ”

sql

43. select ?
explain sql;

44.explain

然 id

SQL

id

然select_type
然table

<unionM,N>: id M N UNION
: id N FROM
: id N

然type

system const eq_ref ref fulltext ref_or_null index_merge unique_subquery


index_subquery range index ALL

1然system

const myisam memory


Innodb type all index

2然const

join const

3然eq_ref

join system const


NULL join
eq_ref '=' 为

ref ref

eq_ref ref

4然ref

ref 样

ref '=' '<=>' 为

5然 fulltext

mysql

6然ref_or_null

ref null

7然index_merge

and or
ref_or_null range

8然unique_subquery

where in
IN ref知
value IN (SELECT primary_key FROM single_table WHERE some_expr)

9然index_subquery

unique_subquery

10然range

=, <>, >, >=, <, <=, IS NULL, <=>, BETWEEN, IN() like 为

11然index

extra Using index


Using index

12然all

然possible_keys
然Key

key MySQL 样 )

MySQL possible_keys FORCE INDEX然USE INDEX


IGNORE INDEX

select_type index_merge select_type

然key_len

key_len where key_len

然ref

然rows

rows mysql 样

然Extra

MySQL , 知

Using where:
mysql

Using temporary知 MySQL
Using filesort知MySQL “ ”
Using join buffer知

Impossible where知 where 为


Select tables optimized away知

知https://www.jianshu.com/p/8fab76bbf448

45.MySql
16

46. ?
会 , ,
ID . , .

47. not null?


MySQL :

NULL columns require additional space in the rowto record whether their values are NULL. For
MyISAM tables, each NULL columntakes one bit extra, rounded up to the nearest byte.

null , 为 .

48.varchar(10) int(10)
varchar 10 , , int 10 ,
10 0新 . ,int(1) int(10) ,

49. ?
(View) 下 会

: 然

: ⼼

: ⽤
;

50.count(*) ?
MyISAM : 年 count(*)

InnoDB : count(*)

太 MySQL感
太 MySql感
太MySQL 样 5 )感
太MySQL 感
知MySQL 45
Spring
1.Spring ?
Spring发 Spring JavaBean
EJB 然 更 Java Spring

2.Spring

20

3.Spring
4.Spring ?

Spring
IOC Spring, 更 更

5. Spring5
spring5 发 java8
http/2
Spring Web MVC API
Spring WebFlux
Kotlin

6.IOC?
然 ( )然 然

7. ?
Spring IoC

8.IOC
1.

2.setter

3. 样

9.IOC

更 然


样 Spring

10.bean ?
1.Spring bean

2.Spring bean bean

3. bean BeanNameAware Spring bean ID setBeanName()

4. bean BeanFactoryAware Spring setBeanFactory() bean

5. bean ApplicationContextAware Spring setApplicationContext() bean

6. bean BeanPostProcessor Spring post-ProcessBeforeInitalization()

7. bean InitializingBean Spring after-PropertiesSet()


bean init-method

8. bean BeanPostProcessor Spring post-ProcessAfterInitialization()

9. bean ,

10. bean DisposableBean Spring destory() bean


destroy-method

11.Spring
xml
Java

12.Spring bean scope?


singleton: bean
prototype bean
request HTTP bean HTTP
session http session bean bean
global session: http session bean bean

13. AOP( )
AOP Aspect Oriented Programming 好 知

14.
(Before):

(After):

(After-returning):

(After-throwing):

要 (Around):

15. Join point)?


然 然

16. Pointcut)?

AOP发 ⼼
( )

17. (Aspect)?

18. (Weaving)?

19. Introduction
︎ ⼼

20.
知 AspectJ
知 JVM
AspectJ 5 (load-time weaving LTW)
知 AOP
Spring AOP

21.AOP
JDK CgLib AOP
CgLib

22. MVC
MVC Model View Controller (model)次 (view)次 (controller) 好
然 然

MVC 然

23. SpringMVC?
SpringMVC Spring发 MVC 发

24.SpringMVC
DispatcherServlet

25.SpringMVC
DispatcherServlet : 的

HandlerMapping : URL Handler

HandlerAdapter : HandlerAdapter Handler

Handler : ,

ViewResolver :

View : 样freeMaker JSP

26.SpringMVC
1. DispatcherServlet

2. DispatcherServlet HandlerMapping Handler

3. 吧

4. Handler HandlerAdapter, Handler,

5. Handler

6.Handler ModelAndView DispatcherServlet


7. ModelAndView DispatcherServlet

8. ViewResolver View

9. View DispatcherServlet

10.DispatcherServlet View 给

11.DispatcherServlet

27.SpringMVC
1. Spring

2. (jsp,freemaker)

3.

4.

5. 去

Tips:Jsp

28. bean

29.Spring
(component scanning):Spring bean

(autowiring):Spring bean

30.
no -

byName 知

byType 知

constructor 知 Bean Bean Bean

autodetect 知 constructor byType

default知 default-autowire

31. Bean
@Component
@Service
@Repository
@Controller
32. Java


String
< map >

33.Spring ORM
1. Hibernate
2. iBatis
3. JPA (Java Persistence API)
4. TopLink
5. JDO (Java Data Objects)
6. OJB

34.@Repository
Dao bean

35.@Value ?
然 然

36.@Controller ?

37.
@Aspect

38. web
@RequestMapping

39.@ResponseBody
response body json然xml

40.@ResponseBody + @Controller =?
@RestController

41.
@PathVariable

42.@Cacheable
43.
@CacheEvict

44.@Component

45.BeanFactory ApplicationContext

46.@Qualifier
bean
@Qualifier @Autowired bean

47. ?
@Transaction

48.Spring

xml
样 @Transaction

49.

50.Spring

太Spring in action 4感
太SPRING 感
太Spring 感
太Spring5 感
https://spring.io

Mybatis
1. Mybatis?
MyBatis SQL 然 发
JDBC MyBatis XML
MyBatis SQL SQL SQL
Java

2.Hibernate
Hibernate POJO 会 xml 会
pojo 会

xml
会 xml
Session
Session

3.Hibernate

sql
sql sql pojo

hql, sql hibernate

4.Mybatis
1. sql
2. jdbc sql
3. sql Java sql
4. jdbc, sql
5. 会orm

5.Mybatis ?
sql sql
sql 会 会

6. Mybatis?
然 发 Mybatis

7.Mybatis
SqlSessionFactoryBuilder( ): SqlSessionFactory

SqlSessionFactory样 : SqlSession

SqlSession样 ): sql Mapper

SQL Mapper: Java XML 样


SQl SQL

8.#{} ${}
${} 为 #{} #{} sql

9.Mybatis 9
if
c h o o s e (when 然 oterwise)
trim (where然 set)
foreach
bind

10.xml
select|insert|updae|delete|resultMap|parameterMap|sql|include|selectKey 9
sql sql

11.Mybatis
知 sql

知 sql sql

12.Mybatis sql
Mybatis sql Xml sql
sql

13.Mybatis ? ?
1 Mybatis RowBounds sql
Mybatis
2 知 Mybatis 吧 吧
sql sql
知select from student 吧 sql 知select t. from 样select from student t
limit 0 10

14. ?

@Options(useGeneratedKeys =true, keyProperty =”id”)

int insert( );

Xml知

<insert id=”insert” useGeneratedKeys=”true” keyProperty=” id”>

sql

</insert>

15. Mapper ?
MyBatis Mapper

16. xml ?

sql xml, xml

xml

17.
mapUnderscoreToCamelCase=true
18.
然 : order_num

select order_num orderNum

<result property = “order_Num" column =”order_num"/>

然 真 17

19.
association 让

select: id, MyBatis 让

column: ( ) 让 column={propl=coll ,
prop2=col2}, propl prop2 让

fetch Type: lazy eager


lazyLoadingEnabled

20.like
样1 '%${value}%'

样2 CONCAT('%',#{value},'%')

(3) like '%'|| #{value} || '%'

样4 bind

LIKE #{pattern}

21.Mybatis
EnumTypeHandler EnumOrdinalTypeHandler

<typeHandlers>
<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
javaType="枚举类(com.xx.StateEnum)"/>
</typeHandlers>

22.SqlSessionFactoryBuilder ?
xml Java SqlSessionFactoryBuilder SessionFactory,
SessionFactory,

23. ?
Map < select > flushCache=true
24.

<settings>
〈 !⼀一其他⾃自⼰己直⼀一 〉
<setting name=” cacheEnabled” value=” true ” />
</settings>

true
false

25. Mybatis
1 Mybatis ParameterHandler然ResultSetHandler然StatementHandler然
Executor 4 Mybatis 吧
吧 4 吧
InvocationHandler invoke() 吧 吧
2 Mybatis Interceptor intercept()

26.
eviction ( )

LRU( ):

IFO( 〉:

SOFT( ): 是了

WEAK ( ): 是了

27.Mybatis Xml id ?
namespace id namespace

28. Mybatis java ?


EhCache Java 发 然

EhCache


下 年
RMI然 API
.


太 MyBatis 感
太 MyBatis 感
太MyBatis 感

Nginx
1. nginx?
Nginx HTTP IMAP/POP3/SMTP
:http://nginx.org

2.nginx
; 为 . ⼀
. FastCGI ⼀ . gzipping, byte ranges, chunked
responses, SSI-filter filter FastCGI SSI

SSL TLSSNI.

Nginx Poll , 50,000

Nginx apache 200 web


Nginx 我 CPU nginx
10,000 2.5M DOS nginx

Nginx 博 , 7*24

Nginx master-slave , SMP 年 I/O 不


select()/poll()

Nginx ⾃
Upstream Filter

Nginx os sendfile (Linux2.2+) accept-filter (FreeBSD4.1+)


TCP_DEFER_ACCEPT (Linux 2.4+)


3.nginx ?
nginx
nginx -s stop nginx -s quit
./sbin/nginx -s reload( ) service nginx reload
.nginx -c /usr/local/nginx/conf/nginx.conf
nginx nginx -v
nginx -t
nginx -h

4. ?

events {

use epoll; #epoll 是多路路复⽤用 IO(I/O Multiplexing)中的⼀一种⽅方 式,但是仅⽤用于 linux2.6


以上内核,可以⼤大⼤大提⾼高 nginx 的性能

worker_connections 1024;#单个后台 worker process 进程的最⼤大并发链接数

# multi_accept on;
}

5.nginx
5

1. 样
down
2.
weight
3.IP_hash 样IP
ip hash session
4.url_hash
5.fair

6.nginx ?
master-worker master-worker master
worker

7.
#
error_page 500 502 503 504 /50x.html;

location = /50x.html { root /root;

8. ?
location =

location = /get {
#规则 A }

9.
location
= ^~, /

10.

location = / {

proxy_pass http://tomcat:8080/index

11.

location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
expires 1h;
break;
}
}

12.

location ^~/path/ {
deny all;
}

13.nginx
http upstream webserver proxy-web
webserver 然 ; serverr
下 下 web location url
web web server

14.

Upstream proxy_nginx {

server 192.168.0.254 weight=1max_fails=2 fail_timeout=10s ;


server 192.168.0.253 weight=2 max_fails=2fail_timeout=10s;
server192.168.0.252 backup; server192.168.0.251 down;

server{
listen 80;
server_name xiaoka.com;

location / {

proxy_pass http:// proxy_nginx;


proxy_set_header Host
proxy_set_header X-Real-IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

15.

http {
……….
keepalive_timeout 60; ###设置客户端连接保持会话的超时时间,超过这个时间,服务器器会关闭
该连接。 tcp_nodelay on;
\####打开 tcp_nodelay,在包含了了 keepalive 参数才有效
client_header_timeout 15; ####设置客户端请求头读取超时时间,如果超过这个时间,客户端
还没有发送任何数据, Nginx 将返回“Request time out(408)”错误
client_body_timeout 15;

\####设置客户端请求主体读取超时时间,如果超过这个时间,客户端还没有发送任何数据, Nginx 将
返回“Request time out(408)”错误
send_timeout 15; ####指定响应客户端的超时时间。这个超过仅限于两个连接活动之间的时间,如
果超过这 个时间,客户端没有任何活动,Nginx 将会关闭连接。

…… }

16.
知 好
知 好

太Nginx 感
太Nginx Web 感
太 nginx感

Redis
1.Redis ?
Redis 样BSD 会
NoSQl 会

2.Redis ?

&

3.Redis

4. Redis NoSQL
MongoDB然MemcacheDB然Cassandra然CouchDB然Hypertable然Leveldb
5.Redis Memcache
memcached k/v redis (
6)

memcached 也 redis 年

redis VM

redis value 年

6.Redis
们知 为 样String 然 样hash)然 样list)然 (set)然 (zset)

HyperLogLog然 然

7.Redis
然 然 然 然 然 然 然Sentinel

8. Redis ,
1. Redis 好

2. 好Redis
3. redis
4. redis
5.
6.
docker 那
docker pull redis

9.redis

10. Redis
1. :

./redis-server

2. : redis-server 样

: redis-server ———port 7359

3. :

./redis-server /opt/redis/redis.conf

11.Redis
redis redis.conf

redis

12.Redis
1. :

redis-cli -h 127.0.0.1 -p 6379

redis

2. 知

redis-cli -h 127.0.0.1 -p 6379 get value

13. redis
Kill -9 pid ( , )

redis shutdown

redis-cli shutdown nosave|save

14.
exists key

15.
del key

16.redis
redis I/O
17.
512MB

18.redis
16

19.redis
RDB然AOF然

20.RDB ?
RDB样Redis DataBase)

Tips: 年

21.RDB
:

save: 不 Redis RDB 不

bgsave:redis fork 不

fork我

save xsecends n:

x n RDB

flushall :

22.RDB
rdb Redis

Redis RDB也 AOF

23.RDB
RDB
RDB fork() Redis

24.
config set save ""

25.AOF
AOF(append only file) rdb aof
aof

26. AOF ?

config get appendonly

27. AOF?

config set appendonly

appendonly yes

28.AOF
1. aof_buf

2.AOF

3. AOF AOF 好

4. redis AOF 也

29. AOF (aof_buf)


Redis
redis ⼀

30.AOF

知( )

![image-20200427101221526](https://gitee.com/yizhibuerdai/Imagetools/raw/master/images/imag
e-20200427101221526.png

知样

bgrewriteaof
31.AOF
AOF 3 知 然 然

redis-check-aof

AOF

32.AOF
AOF RDB
AOF RDB你
RDB

33.
redis4.0

天 4.0

34.Redis Java
3 知Jedis然Redisson lettuce

:Jedis|Redisson

Jedis知 然 然 API Redis

Redisson知 Netty
Jedis 为
然 然 然 Redis

35.Redis

36.Redis

37.Redis key
key n

expire key nseconds

key nmilliseconds

pxpire key milliseconds

timestamp

expireat key timespamp

timestamp

pexpireat key millisecondsTimestamp

38.Redis ?

对 知


cpu

39.Pipeline

RTT(Round Trip Time )

pipeline
pipeline

40.
:

config get maxmemory

config set maxmemory 1GB


41.Redis
Redis maxmemory

42.Redis
1.noeviction( ): 样error) OOM command not allowed
when used memory,

2. volatile-lru: LRU 样expire)


noeviction
3. allkeys-lru: LRU
4. allkeys-random:
5. volatile-random:
6. volatile-tth ttl noeviction

43.Redis
Redis Sentinel( )

44.Redis
Twemproxy然Redis Cluster然Codis

45.Redis Cluster
0~16383

46.Redis ?
setnx (set if not exists),

setnx lock true

del lock

这 友

:expire lock 300

, 友

Redis set

: set lock true ex 30 nx

47.
1970 中 中 很

Tips:
48.

1:

2: 中 很

49.

50.
这知

太Redis : ⼦感
太Redis 感
太Redis 感
https://redis.io/

Dubbo
1. Dubbo?
Dubbo Java RPC 发 Apache

知http://dubbo.apache.org/en-us/
2. Dubbo?
:

Web ⾃ 样


netty

3.Dubbo 3

4. Dubbo

5.Dubbo ?
6. Dubbo ?
1.
2.
3.
4.

5. ⼀

6.

7.
8.Dubbo
然 然 好 然

9. jdk
jdk1.6+

10.
Zookeeper

Zookeeper Redis 然Multicast 然Simple

11.Dubbo
12.

JVM -D 博 dubbo 又
XML, XML dubbo.properties 又
Properties

13.

ReferenceConfig<XxxService> reference = new ReferenceConfig<XxxService>(); //


此实例例很重,封装了了与注册中⼼心的连接以及与提供者的连接,请⾃自⾏行行缓存,否则可能造成内存和连接泄漏漏
// 如果点对点直连,可以⽤用reference.setUrl()指定⽬目标地址,设置url后将绕过注册中⼼心,
// 其中,协议对应provider.setProtocol()的值,端⼝口对应provider.setPort()的值,
// 路路径对应service.setPath()的值,如果未设置path,缺省path为接⼝口名
reference.setUrl("dubbo://10.20.130.230:20880/com.xxx.XxxService");

14.Dubbo
4
JVM System Properties -D
Externalized Configuration
ServiceConfig然ReferenceConfig
dubbo.properties

15.

<dubbo:reference interface = "com.foo.BarService" check = "false" />

16.Dubbo
⼀( )
RoundRobin ⼀

17.
(version)

18.
xml

<dubbo:reference id="xxxService" interface="com.alibaba.xxx.XxxService"


url="dubbo://localhost:20890" />

-D

java -Dcom.alibaba.xxx.XxxService=dubbo://localhost:20890

.properties

java -Ddubbo.resolve.file=xxx.properties

com.alibaba.xxx.XxxService=dubbo://localhost:20890

19.
20.Dubbo
1. Spring
2. Java API

21.Dubbo
dubbo://( )
rmi://
hessian://
http://
webservice://
thrift://
memcached://
redis://
rest://

22.Dubbo ?
dubbo netty

23.dubbo http hessian?rmi?


dubbo:20880
http:80
hessian:80
rmi:80

24.Dubbo ?
dubbo hessian2
rmi java
http json

25.
group group

26.Dubbo

Dubbo NIO 不
Future

27.Dubbo ?
Zipkin
Pinpoint
SkyWalking

28.Dubbo Dubbo Dubbox


Apache, apache

Dubbox ⾃

29.Dubbox
REST 样HTTP + JSON/XML)
Kryo FST Java
让 Tomcat HTTP remoting
Spring
ZooKeeper

30.io
cpu +1

31.dubbo://
NIO
32.
zookeeper

33. 2.0.5 dubbo x ?


telnet

34.

telnet localhost 20880

ls :

ls:
ls -l:
ls XxxService:
ls -l XxxService:

35.Dubbo

config 知 ServiceConfig, ReferenceConfig


spring
proxy 知 Stub Skeleton,
ServiceProxy ⾃ ProxyFactory
registry 知 URL ⾃
RegistryFactory, Registry, RegistryService
cluster 知 ⼀ Invoker ⾃
Cluster, Directory, Router, LoadBalance
monitor 知RPC Statistics ⾃
MonitorFactory, Monitor, MonitorService
protocol 知 RPC Invocation, Result ⾃ Protocol,
Invoker, Exporter
exchange 知 Request, Response ⾃
Exchanger, ExchangeChannel, ExchangeClient, ExchangeServer
transport 知 mina netty Message ⾃ Channel,
Transporter, Client, Server, Codec
serialize 知 ⾃ Serialization, ObjectInput,
ObjectOutput, ThreadPool

36. Dubbo
dubbo

知http://dubbo.apache.org/en-us/
SpringBoot
1. SpringBoot?
Spring Boot Spring “ ”
Spring Boot Spring

2.SpringBoot
Spring
让 Tomcat Jetty Undertow样 博WAR
“starter”
Spring 3rd Party会

XML

3. SpringBoot
Web http://start.spring.io
Spring Tool Suite
IntelliJ IDEA
Spring Boot CLI

4.SpringBoot ?
@SpringBootApplication

@SpringBootConfiguration: @Configuration
@EnableAutoConfiguration:
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@ComponentScan:Spring

5. yaml?
YAML样/ˈjæmәl/ camel 真 YAML
知C 然Python然Perl

6.SpringBoot ?
1.properties

java.xiaokaxiu.name = xiaoka

2.yml

java:
xiaokaxiu:
name: xiaoka

7.SpringBoot
1. main
2. java -jar
3. mvn/gradle

8.SpringBoot
Tomcat/Jetty

9.SpringBoot
1.
2. java:comp/env JNDI
3. JVM
4.
5. random.* ( ${random. long})
6. application.properties appliaction.yml
7. application.properties appliaction.yml
8. @PropertySource
9.

tips:

10.application.properties application.yml ? ?
1. /config
2.
3. config
4. Classpath
,

java -jar xiaoka.jar ———spring.config.location=/home/application.yml

11.SpringBoot ?
@EnableAutoConfiguration ( )
AutoConfigurationImportSelector META-
INF/spring.factories jar

12.SpringBoot
spring-boot-devtools
Spring Loaded
Jrebel

13.bootstrap.yml application.yml?
bootstrap.yml application.yml

14.SpringBoot ?
yml :

server :
port : 8888

properties:

server.port = 8888

1:

java -jar xiaoka.jar ——— server.port=8888

2:

java - Dserver.port=8888 -jar xiaoka.jar

15. SpringBoot ?
1. spring-boot-starter-parent
2. spring-boot-dependencies

16.SpringBoot Spring ?
:

@ImportResource(locations = {"classpath:spring.xml"})

17.SpringBoot ?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

18. Bean
/beans

19. ?
/shutdown

endpoints:
shutdown:
enabled: true

properties

20. ?
/info

21.
@PatchMapping

@PostMapping

@GetMapping

@PutMapping

@DeleteMapping

22.SpringBoot starter
starter

23.SpringBoot Mybatis?
mybatis-spring-boot-starter

24. SpringProfiles?
(dev)然 样test 然 (prod)
Spring Profiles ⼼ 样dev test prod bean

25. ?
application-{profile}.properties/yml application.properties,

application.properties知
application-dev.properties知
application-test.properties知
application.prop-properties知

26.

yml知

spring:
profiles:
active: dev

properties:

spring.profiles.active=dev

java -jar xiaoka-v1.0.jar ———spring.profiles.active=dev

27.
@SpringBootTest

28.SpringBoot ?
@ControllerAdvice

@ExceptionHandler

29.SpringBoot 1.x 2.x ?·······


1. SpringBoot 2 Spring5 JDK8 Spring 1x
2.
3. SpringBoot2
4. 2.x
5. Actuator
6. CacheManager
30.SpringBoot
@PropertySource
@Value
@Environment
@ConfigurationProperties

太SpringBoot 样 4 感
太Spring Boot 感
太 Spring Boot 2.x感
https://spring.io/projects/spring-boot

Kafka
1. kafka?
Apache Kafka Apache

2.kafka 3

3.kafka

4.kafka ?
1.
2.
3. ⾃
4.
5. Kafka Streams
6.
7.
8.
9. 好

5.kafka 5 Api?
Producer API
Consumer API
Streams API
Connector API
Admin API

6. Broker ?
Kafka kafka (Broker)

7. Producer ?
Producer

Producer ?

8. Consumer ?
kafka

9. Topic ?
kafka

10. Partition ?
Topic (Partition)

11.
Broker, Broker

12. (Replication)?
样 1

13. (Record)?
kafka

14.kafka
然 然 没然 然 然
15.kafka
SSD 年 年
地年 出 SSD

16. RAID ?
今 年

17.

18.Broker
log.dirs

log.dir

19.
log.dirs

20. ?
auto.create.topics.enable

21. kafka
producer.send(msg) producer.send(msg, callback)
acks = all
retries
unclean.leader.election.enable = false
replication.factor >= 3
min.insync.replicas > 1
replication.factor > min.insync.replicas

22.
partitioner.class
partition

23.kafka
Producer 然Broker

24.kafka

会 样

25. kafka
JMXTool
Kafka Manager
Burrow
JMXTrans + InfluxDB + Grafana
Confluent Control Center

太Kafka 感
太kafka ⼦感
知Kafka
http://kafka.apache.org/

SpringCloud
1. SpringCloud?
Spring Cloud 样

Cloud Foundry

2.
SOA 只

1然

2然 ⾃

3.SpringCloud ?
Spring Cloud ⾃ 样

4.SpringCloud ?
Eureka :

Ribbon 知 ⼀

Hystrix :

Feign: REST

Zuul :

Config :

5.SpringCloud
HTTP

6.SpringCloud Dubbo ?
7.Eureka
REST

8.

9.

10.
REST 样
样DOWN

11.
样 60s)
( 90s)

12.
15 85%,

13.Ribbon ?
⼀ ⼀

14.Ribbon ?
@LoadBalanced

15.Ribbon
RandomRule :

RoundRobinRule :

RetryRule :

WeightedResponseTimeRule :

ClientConfigEnabledRoundRobinRule : choose

BestAvailableRule : ⼀ 很

PredicateBasedRule : 很

AvailabilityFilteringRule 知 很

ZoneAvoidanceRule : PredicateBasedRule 很
ZoneAvoidancePredicate 很 AvailabilityPredicate 很

16.
⼿

17.

18. Hystrix?
⼿ 成 ⼿ 会 ,

19. Hystrix
,
( 这 )
(Failfast) 也
(Fallback)

20.Hystrix
HystrixCommand HystrixObservableCommand

21.
@EnableHystrix

22. Feign?
Feign 然 HTTP

23.Feign
1.feign
2.feign ribbon ⼀
3. Hystrix ⼿

24. Config?
然Git
Subversion

25.Config ?
Config Server :

Config Client :

26. Zuul?
Zuul , , , 发 Zuul Netflix
Web

27. Zuul ?

28.Zuul

29.Zuul
4

pre :

route :

post : route error 很

error :

error 很

30. Sleuth?
Dapper log-based 没 Zipkin HTrace SpringCloud

31.Sleuth

爱还 Zipkin

32. Bus?
然 样 Spring Cloud Config

33.eureka zookeeper
A: C: P:

Zookeeper CP Eureka AP

Eureka Zookeeper
微三

34. Stream?
Redis,Rabbit然Kafka
35.
SpringCloud
太Java 感

太Spring Cloud 感
太Spring Cloud 感
太Spring Cloud 感
https://spring.io/projects/spring-cloud
https://www.springcloud.cc/

https://mp.weixin.qq.com/s/z0k922U6jwXe5VYlz33gaA

:https://www.zhihu.com/question/25002833 ThoughtWorks

种 IT 然 HR
HR “
” 30 知

fashion 然



PDF 天

样eg. 然 上
)

/ / / / / /
:

去 HR

QQ 样

Github 样

&

STAR STAR
友 BAT友 友

样Java, Scala Ruby, React, Vue, Microservice…


( / / /
)

开 1 知

XX样 2013.06 —

会 web

ay 2010.03 — 2013.03

XXX Java — 2016.2 -2017.2

1然MOGU

MOGU app, feed


, , rpc
然 , , redis

2然 JAVA

java server , ,

然ip 然

3然 Solr

, solr java rpc , solr

XXX

java — 2013.4 -2015.12

1然

kafka , kafka , ,
, ,

storm , ,
, pv然uv ,
在 js , go 2然hadoop

2然 CDH ,

MapReduce , , , ,
, , 点

3然 quartz2 , review

4然 会 , 点, mycat , 会 ,
,

5然 java web , , ,
java , ,
, 不

&


1

, 家 过

又 有 又

: , 国 ,
,
: , , 们 ,
们 , , ,
: , Google然Stack over flow
, 然 然 REPL
,
: , Twitter ,Github
Trending Podcast然Hacker News然Reddit TechRadar

: 然 , , 然

出 : , 美 ,么

然 然
Ruby on Rails知
Agile/Lean知
ReactJS知
Docker知
AWS知

1. HR

2. :太 感太 感太 感
3. : Stack Over flow Google Developer Group
4. 然 :

https://github.com/github
http://www.oschina.net/
https://www.cnblogs.com/
https://itunes.apple.com/app/battle-of-crab/id1121917063?l=en&amp;amp;mt=8
: offer

You might also like