Stop The World
Stop一the一World,簡稱STW,指的是Gc事件發生過程中,會產生應用程序的停頓。停頓產生時整個應用程序線程都會被暫停,沒有任何響應,有點像卡死的感覺,這個停頓稱為STW。.
舉例:
➢可達性分析算法中枚舉根節點(GC Roots)會導致所有Java執行線程停頓。.
停頓的原因
分析工作必須在一個能確保一致性的快照 中進行
一致性指整個分析期間整個執行系統看起來像被凍結在某個時間點上V
如果出現分析過程中對象引用關系還在不斷變化,則分析結果的准確性無法保證
示例代碼:
被STW中斷的應用程序線程會在完成GC之后恢復,頻繁中斷會讓用戶感覺像是網速不快造成電影卡帶一樣, 所以我們需要減少STW的發生。
STW事件和采用哪款GC無關,所有的GC都有這個事件。
哪怕是G1也不能完全避免Stop一the一world情況發生,只能說垃圾回收器越來越優秀,回收效率越來越高,盡可能地縮短了暫停時間。
STW是JVM在后台自動發起和自動完成的。在用戶不可見的情況下,把用戶正常的工作線程全部停掉。
開發中采用System.gc();會導致Stop一the一world的發生。
public class StopTheWorldDemo { public static class WorkThread extends Thread { List<byte[]> list = new ArrayList<byte[]>(); public void run() { try { while (true) { for(int i = 0;i < 1000;i++){ byte[] buffer = new byte[1024]; list.add(buffer); } if(list.size() > 10000){ list.clear(); System.gc();//會觸發full gc,進而會出現STW事件 } } } catch (Exception ex) { ex.printStackTrace(); } } } public static class PrintThread extends Thread { public final long startTime = System.currentTimeMillis(); public void run() { try { while (true) { // 每秒打印時間信息 long t = System.currentTimeMillis() - startTime; System.out.println(t / 1000 + "." + t % 1000); Thread.sleep(1000); } } catch (Exception ex) { ex.printStackTrace(); } } } public static void main(String[] args) { WorkThread w = new WorkThread(); PrintThread p = new PrintThread(); w.start(); p.start(); } }
W線程當中的GC觸發了STW,進而干擾了P線程有規律性打印。打印變得雜亂無章
打印輸出:
