2016年3月9日 星期三

關於資源回收題目

Which statement is true?

A. Programs will not run out of memory.
B. Objects that will never again be used are eligible for garbage collection.
C. Objects that are referred to by other objects will never be garbage collected.
D. Objects that can be reached from a live thread will never be garbage collected.

A 是錯的,GC不能保證可以釋放出足夠的記憶體。
B 是錯的,陷阱答案,"never again be used"=>不再使用的物件並不代表不被參考到的物件
(有一說法是可能會在finalize()中重新被參考到,但我認為Finalize()被呼叫也就代表GC已經被啟動了,個人看法。)
C 是錯的,考孤島型的參照一樣會被回收。
D 是對的

2016年1月14日 星期四

常見的執行緒池--Executors.newCachedThreadPool()

Executors.newCachedThreadPool()

    建立一個執行緒池,當有需求時(也就是有實現runnable 介面的物件需要執行時),會建立新的執行緒(建立Thread 物件),但若舊有的執行緒是空閒的(有Thread物件沒有在執行runnable 物件),就使用舊有的執行緒。這種執行緒池通常可以改善生命週期短的非同步任務的效能

    由於執行緒若空閒時間達到60秒,便會被回收掉。所以執行緒池可以長時間存在而不消耗資源,畢竟可能根本沒有執行緒在執行。