Unable to create new native thread ……html
問題1:Java中建立一個線程消耗多少內存?java
每一個線程有獨自的棧內存,共享堆內存程序員
問題2:一臺機器能夠建立多少線程?shell
CPU,內存,操做系統,JVM,應用服務器數據庫
咱們編寫一段示例代碼,來驗證下線程池與非線程池的區別:安全
//線程池和非線程池的區別 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線程池中核心線程數 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(); } }
啓動不一樣數量的線程,而後比較線程池和非線程池的執行結果:服務器
非線程池 | 線程池 | |
---|---|---|
100次 | 16毫秒 | 5ms的 |
1000次 | 90毫秒 | 28ms |
10000次 | 1329ms | 164ms |
結論:不要new Thread(),採用線程池併發
非線程池的缺點:dom
每次建立性能消耗大tcp
無序,缺少管理。容易無限制建立線程,引發OOM和死機
避免死鎖,請儘可能使用CAS
咱們編寫一個樂觀鎖的實現示例:
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沒有外部強引用來引用它,那麼系統 GC 的時候,這個ThreadLocal勢必會被回收,這樣一來,ThreadLocalMap中就會出現key爲null的Entry,就沒有辦法訪問這些key爲null的Entry的value,若是當前線程再遲遲不結束的話,這些key爲null的Entry的value就會一直存在一條強引用鏈:Thread Ref -> Thread -> ThreaLocalMap -> Entry -> value永遠沒法回收,形成內存泄漏。
咱們編寫一個ThreadLocalMap正確使用的示例:
//ThreadLocal應用實例 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(); } } }
經典的HashMap死循環形成CPU100%問題
咱們模擬一個HashMap死循環的示例:
//HashMap死循環示例 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死循環發生後,咱們能夠在線程棧中觀測到以下信息:
/HashMap死循環產生的線程棧 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)
應用停滯的死鎖,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(); } }
死鎖發生後,咱們能夠在線程棧中觀測到以下信息:
//死鎖時產生堆棧 "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.
一個計數器的優化,咱們分別用Synchronized,ReentrantLock,Atomic三種不一樣的方式來實現一個計數器,體會其中的性能差別
//示例代碼 public class SynchronizedTest { public static int threadNum = 100; public static int loopTimes = 10000000; public static void userSyn() { //線程數 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(); } //等待全部線程結束 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() { //線程數 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(); } //等待全部線程結束 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() { //線程數 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(); } //等待全部線程結束 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); } }
結論,在併發量高,循環次數多的狀況,可重入鎖的效率高於Synchronized,但最終Atomic性能最好。
OIO | NIO | AIO | |
---|---|---|---|
類型 | 阻塞 | 非阻塞 | 非阻塞 |
使用難度 | 簡單 | 複雜 | 複雜 |
可靠性 | 差 | 高 | 高 |
吞吐量 | 低 | 高 | 高 |
結論:我性能有嚴苛要求下,儘可能應該採用NIO的方式進行通訊。
反應:常常性的請求失敗
獲取鏈接狀況 netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
TIME_WAIT:表示主動關閉,優化系統內核參數可。
CLOSE_WAIT:表示被動關閉。
ESTABLISHED:表示正在通訊
解決方案:二階段完成後強制關閉
結論:
管道鏈接的性能最優異,持久化是在串行鏈接的基礎上減小了打開/關閉鏈接的時間。
管道化鏈接使用限制:
一、HTTP客戶端沒法確認持久化(通常是服務器到服務器,非終端使用);
二、響應信息順序必須與請求信息順序一致;
三、必須支持冪等操做纔可使用管道化鏈接.
必需要有索引(特別注意按時間查詢)
單條操做or批量操做
注:不少程序員在寫代碼的時候隨意採用了單條操做的方式,但在性能要求前提下,要求採用批量操做方式。
單個CPU佔用率高,首先從GC查起。
若是IO的CPU佔用很高,排查涉及到IO的程序,好比把OIO改形成NIO。
緣由:字節碼轉爲機器碼須要佔用CPU時間片,大量的CPU在執行字節碼時,致使CPU長期處於高位;
現象:「C2 CompilerThread1」 daemon,「C2 CompilerThread0」 daemon CPU佔用率最高;
解決辦法:保證編譯線程的CPU佔比。
做者:梁鑫
來源:宜信技術學院