Unable to create new native thread ……
創(chuàng)新互聯(lián)建站是一家專業(yè)提供云溪企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站制作、網(wǎng)站設(shè)計、H5高端網(wǎng)站建設(shè)、小程序制作等業(yè)務(wù)。10年已為云溪眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)的建站公司優(yōu)惠進行中。
問題1:Java中創(chuàng)建一個線程消耗多少內(nèi)存?
每個線程有獨自的棧內(nèi)存,共享堆內(nèi)存
問題2:一臺機器可以創(chuàng)建多少線程?
CPU,內(nèi)存,操作系統(tǒng),JVM,應(yīng)用服務(wù)器
我們編寫一段示例代碼,來驗證下線程池與非線程池的區(qū)別:
//線程池和非線程池的區(qū)別
public class ThreadPool {
public static int times = 100;//100,1000,10000
public static ArrayBlockingQueue arrayWorkQueue = new ArrayBlockingQueue(1000);
public static ExecutorService threadPool = new ThreadPoolExecutor(5, //corePoolSize線程池中核心線程數(shù)
10,
60,
TimeUnit.SECONDS,
arrayWorkQueue,
new ThreadPoolExecutor.DiscardOldestPolicy()
);
public static void useThreadPool() {
Long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
threadPool.execute(new Runnable() {
public void run() {
System.out.println("說點什么吧...");
}
});
}
threadPool.shutdown();
while (true) {
if (threadPool.isTerminated()) {
Long end = System.currentTimeMillis();
System.out.println(end - start);
break;
}
}
}
public static void createNewThread() {
Long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
new Thread() {
public void run() {
System.out.println("說點什么吧...");
}
}.start();
}
Long end = System.currentTimeMillis();
System.out.println(end - start);
}
public static void main(String args[]) {
createNewThread();
//useThreadPool();
}
}
啟動不同數(shù)量的線程,然后比較線程池和非線程池的執(zhí)行結(jié)果:
非線程池 | 線程池 | |
---|---|---|
100次 | 16毫秒 | 5ms的 |
1000次 | 90毫秒 | 28ms |
10000次 | 1329ms | 164ms |
結(jié)論:不要new Thread(),采用線程池
非線程池的缺點:
每次創(chuàng)建性能消耗大
避免死鎖,請盡量使用CAS
我們編寫一個樂觀鎖的實現(xiàn)示例:
public class CASLock {
public static int money = 2000;
public static boolean add2(int oldm, int newm) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (money == oldm) {
money = money + newm;
return true;
}
return false;
}
public synchronized static void add1(int newm) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
money = money + newm;
}
public static void add(int newm) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
money = money + newm;
}
public static void main(String args[]) {
Thread one = new Thread() {
public void run() {
//add(5000)
while (true) {
if (add2(money, 5000)) {
break;
}
}
}
};
Thread two = new Thread() {
public void run() {
//add(7000)
while (true) {
if (add2(money, 7000)) {
break;
}
}
}
};
one.start();
two.start();
try {
one.join();
two.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(money);
}
}
使用ThreadLocal要注意
ThreadLocalMap使用ThreadLocal的弱引用作為key,如果一個ThreadLocal沒有外部強引用來引用它,那么系統(tǒng) GC 的時候,這個ThreadLocal勢必會被回收,這樣一來,ThreadLocalMap中就會出現(xiàn)key為null的Entry,就沒有辦法訪問這些key為null的Entry的value,如果當前線程再遲遲不結(jié)束的話,這些key為null的Entry的value就會一直存在一條強引用鏈:Thread Ref -> Thread -> ThreaLocalMap -> Entry -> value永遠無法回收,造成內(nèi)存泄漏。
我們編寫一個ThreadLocalMap正確使用的示例:
//ThreadLocal應(yīng)用實例
public class ThreadLocalApp {
public static final ThreadLocal threadLocal = new ThreadLocal();
public static void muti2() {
int i[] = (int[]) threadLocal.get();
i[1] = i[0] * 2;
threadLocal.set(i);
}
public static void muti3() {
int i[] = (int[]) threadLocal.get();
i[2] = i[1] * 3;
threadLocal.set(i);
}
public static void muti5() {
int i[] = (int[]) threadLocal.get();
i[3] = i[2] * 5;
threadLocal.set(i);
}
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
new Thread() {
public void run() {
int start = new Random().nextInt(10);
int end[] = {0, 0, 0, 0};
end[0] = start;
threadLocal.set(end);
ThreadLocalApp.muti2();
ThreadLocalApp.muti3();
ThreadLocalApp.muti5();
//int end = (int) threadLocal.get();
System.out.println(end[0] + " " + end[1] + " " + end[2] + " " + end[3]);
threadLocal.remove();
}
}.start();
}
}
}
經(jīng)典的HashMap死循環(huán)造成CPU100%問題
我們模擬一個HashMap死循環(huán)的示例:
//HashMap死循環(huán)示例
public class HashMapDeadLoop {
private HashMap hash = new HashMap();
public HashMapDeadLoop() {
Thread t1 = new Thread() {
public void run() {
for (int i = 0; i < 100000; i++) {
hash.put(new Integer(i), i);
}
System.out.println("t1 over");
}
};
Thread t2 = new Thread() {
public void run() {
for (int i = 0; i < 100000; i++) {
hash.put(new Integer(i), i);
}
System.out.println("t2 over");
}
};
t1.start();
t2.start();
}
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
new HashMapDeadLoop();
}
System.out.println("end");
}
}
https://coolshell.cn/articles/9606.html
HashMap死循環(huán)發(fā)生后,我們可以在線程棧中觀測到如下信息:
/HashMap死循環(huán)產(chǎn)生的線程棧
Thread-281" #291 prio=5 os_prio=31 tid=0x00007f9f5f8de000 nid=0x5a37 runnable [0x0000700006349000]
java.lang.Thread.State: RUNNABLE
at java.util.HashMap$TreeNode.split(HashMap.java:2134)
at java.util.HashMap.resize(HashMap.java:713)
at java.util.HashMap.putVal(HashMap.java:662)
at java.util.HashMap.put(HashMap.java:611)
at com.example.demo.HashMapDeadLoop$2.run(HashMapDeadLoop.java:26)
應(yīng)用停滯的死鎖,Spring3.1的deadlock 問題
我們模擬一個死鎖的示例:
//死鎖的示例
public class DeadLock {
public static Integer i1 = 2000;
public static Integer i2 = 3000;
public static synchronized Integer getI2() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return i2;
}
public static void main(String args[]) {
Thread one = new Thread() {
public void run() {
synchronized (i1) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (i2) {
System.out.println(i1 + i2);
}
}
}
};
one.start();
Thread two = new Thread() {
public void run() {
synchronized (i2) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (i1) {
System.out.println(i1 + i2);
}
}
}
};
two.start();
}
}
死鎖發(fā)生后,我們可以在線程棧中觀測到如下信息:
//死鎖時產(chǎn)生堆棧
"Thread-1":
at com.example.demo.DeadLock$2.run(DeadLock.java:47)
- waiting to lock (a java.lang.Integer)
- locked (a java.lang.Integer)
"Thread-0":
at com.example.demo.DeadLock$1.run(DeadLock.java:31)
- waiting to lock (a java.lang.Integer)
- locked (a java.lang.Integer)
Found 1 deadlock.
一個計數(shù)器的優(yōu)化,我們分別用Synchronized,ReentrantLock,Atomic三種不同的方式來實現(xiàn)一個計數(shù)器,體會其中的性能差異
//示例代碼
public class SynchronizedTest {
public static int threadNum = 100;
public static int loopTimes = 10000000;
public static void userSyn() {
//線程數(shù)
Syn syn = new Syn();
Thread[] threads = new Thread[threadNum];
//記錄運行時間
long l = System.currentTimeMillis();
for (int i = 0; i < threadNum; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < loopTimes; j++) {
//syn.increaseLock();
syn.increase();
}
}
});
threads[i].start();
}
//等待所有線程結(jié)束
try {
for (int i = 0; i < threadNum; i++)
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("userSyn" + "-" + syn + " : " + (System.currentTimeMillis() - l) + "ms");
}
public static void useRea() {
//線程數(shù)
Syn syn = new Syn();
Thread[] threads = new Thread[threadNum];
//記錄運行時間
long l = System.currentTimeMillis();
for (int i = 0; i < threadNum; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < loopTimes; j++) {
syn.increaseLock();
//syn.increase();
}
}
});
threads[i].start();
}
//等待所有線程結(jié)束
try {
for (int i = 0; i < threadNum; i++)
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("userRea" + "-" + syn + " : " + (System.currentTimeMillis() - l) + "ms");
}
public static void useAto() {
//線程數(shù)
Thread[] threads = new Thread[threadNum];
//記錄運行時間
long l = System.currentTimeMillis();
for (int i = 0; i < threadNum; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < loopTimes; j++) {
Syn.ai.incrementAndGet();
}
}
});
threads[i].start();
}
//等待所有線程結(jié)束
try {
for (int i = 0; i < threadNum; i++)
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("userAto" + "-" + Syn.ai + " : " + (System.currentTimeMillis() - l) + "ms");
}
public static void main(String[] args) {
SynchronizedTest.userSyn();
SynchronizedTest.useRea();
SynchronizedTest.useAto();
}
}
class Syn {
private int count = 0;
public final static AtomicInteger ai = new AtomicInteger(0);
private Lock lock = new ReentrantLock();
public synchronized void increase() {
count++;
}
public void increaseLock() {
lock.lock();
count++;
lock.unlock();
}
@Override
public String toString() {
return String.valueOf(count);
}
}
結(jié)論,在并發(fā)量高,循環(huán)次數(shù)多的情況,可重入鎖的效率高于Synchronized,但最終Atomic性能最好。
OIO | NIO | AIO | |
---|---|---|---|
類型 | 阻塞 | 非阻塞 | 非阻塞 |
使用難度 | 簡單 | 復(fù)雜 | 復(fù)雜 |
可靠性 | 差 | 高 | 高 |
吞吐量 | 低 | 高 | 高 |
結(jié)論:我性能有嚴苛要求下,盡量應(yīng)該采用NIO的方式進行通信。
反應(yīng):經(jīng)常性的請求失敗
獲取連接情況 netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
TIME_WAIT:表示主動關(guān)閉,優(yōu)化系統(tǒng)內(nèi)核參數(shù)可。
CLOSE_WAIT:表示被動關(guān)閉。
解決方案:二階段完成后強制關(guān)閉
結(jié)論:
管道連接的性能最優(yōu)異,持久化是在串行連接的基礎(chǔ)上減少了打開/關(guān)閉連接的時間。
管道化連接使用限制:
1、HTTP客戶端無法確認持久化(一般是服務(wù)器到服務(wù)器,非終端使用);
2、響應(yīng)信息順序必須與請求信息順序一致;
3、必須支持冪等操作才可以使用管道化連接.
必須要有索引(特別注意按時間查詢)
單條操作or批量操作
注:很多程序員在寫代碼的時候隨意采用了單條操作的方式,但在性能要求前提下,要求采用批量操作方式。
單個CPU占用率高,首先從GC查起。
如果IO的CPU占用很高,排查涉及到IO的程序,比如把OIO改造成NIO。
原因:字節(jié)碼轉(zhuǎn)為機器碼需要占用CPU時間片,大量的CPU在執(zhí)行字節(jié)碼時,導(dǎo)致CPU長期處于高位;
現(xiàn)象:“C2 CompilerThread1” daemon,“C2 CompilerThread0” daemon CPU占用率最高;
解決辦法:保證編譯線程的CPU占比。
作者:梁鑫
來源:宜信技術(shù)學(xué)院