2017-06-13 27 views
1

在我們的項目的一部分,我們有一些原型豆。我希望對執行該部分過程中發生的事情有清楚的瞭解。在Spring應用程序中創建和銷燬Prototype-beans期間跟蹤內存情況的方法?

是否有任何方式跟蹤在創建prototype-beans期間的情況,他們開始使用多少內存以及跟蹤這些bean是否被成功銷燬?

我不僅需要在控制檯上打印信息,但我想看到實際情況與內存或現有的內存原型bean的列表。

回答

2

我已經找到一種方法來看到有關創建原型豆實際的圖片。 我使用免費VisualVM內存分析器。

採樣器標籤中,您可以看到創建的類的所有實例,包括singleton和prototype bean。

你會看到你自己的軟件包和類的名稱。在這種情況下:

  • 原型是我的原型豆一包。

  • singleton是與我的單身豆包。

  • newclasses是與我通過運算符創建類的包。

另外,垃圾收集將清理內存後,你將在這裏看到的結果。

enter image description here

+1

接受你自己的答案:P – AnthonyJClink

1

任何標準配置文件將幫助您收集您正在查找的數據。對於快速和骯髒的外觀:http://docs.oracle.com/javase/7/docs/technotes/guides/management/jconsole.html

但是我可以幫助解釋原型生命週期,這可能會澄清你的一些問題。

在大多數軟件解決方案中,您擁有的管理對象通常以單例實現,並且您通常會根據需要實例化數據對象。

在春天,所有創建的bean都被標記爲singletons,並在spring內部進行管理。

當你創建一個原型bean時,spring只是返回該bean的一個新實例,但它確實管理該bean的依賴注入。

這樣:

@Bean 
public String importantString(){ 
    return "Super Important String used throughout the system"; 
} 

當你需要在原型中的重要的字符串:

春天將緩存中的重要字符串,但您的應用程序將現在處理的原型生命週期,因爲它負責將任何新的MyObject()

public static void main(String[] args){ 

    MyProtoTypeBean myPrototypeBean = context.getBean(MyPrototypeBean.class); 

    MyProtoTypeBean myPrototypeBean2 = context.getBean(MyPrototypeBean.class); 

    String importantString = myPrototypeBean.getString(); 

    // each prototoype is reconstructed 
    assert myProtoTypeBean != myPrototypeBean2;  

    myPrototypeBean = null; 
    myPrototypeBean2 = null; 

    // Since we are now handling the lifecycle of the prototype beans, as soon 
    //as we clear them and set them to null garbage collection will clear the 
    //prototype beans but not the importantString singleton 
    //however spring will still have reference to the singleton string 

    assert importantString == context.getBean("importantString"); 
} 

我希望這有助於!

+0

謝謝。其實我有一些單身人士和原型豆生命週期的知識。我的問題是我如何能夠獲得原型 - 豆類使用的明確信息或統計信息。 –

+1

如上所述,任何標準的分析器會給你這個信息:http://docs.oracle.com/javase/7/docs/technotes/guides/management/jconsole.html – AnthonyJClink

+0

Anthony,在內存分析器中,我看到垃圾收集器從內存中清理所有的原型bean。您能否詳細解釋一下是否有任何理由通過「= null」手動銷燬這些bean,如示例所示。 –

2

如果您需要以編程方式做到這一點,試試這個public interface Instrumentation

這個類提供所需 檢測Java編程語言代碼的服務。儀器是 字節碼添加到方法的目的是收集數據到 由工具使用。由於這些更改純粹是相加的,因此這些工具不會修改應用程序狀態或行爲。這種良性工具的示例包括監測代理,分析器,覆蓋分析器,事件記錄器和事件記錄器。有兩種方法可以獲得 Instrumentation接口的實例:

當以指示代理類的方式啓動JVM時。在那個 的情況下,一個Instrumentation實例被傳遞給代理類的premain方法 。

當JVM在啓動JVM 後的某個時間提供啓動代理的機制時。在這種情況下,Instrumentation實例被傳遞給代理程序代碼的代理主方法 。

例如Instrumentation: querying the memory usage of a Java object

public class MyAgent { 
    private static volatile Instrumentation globalInstr; 
    public static void premain(String args, Instrumentation inst) { 
    globalInstr = inst; 
    } 
    public static long getObjectSize(Object obj) { 
    if (globalInstr == null) 
     throw new IllegalStateException("Agent not initted"); 
    return globalInstr.getObjectSize(obj); 
    } 
} 
+0

這是好東西,我忘了這個。儘管如此,我仍然會在生產應用程序中使用它。 – AnthonyJClink

+0

@ AnthonyJClink +1) – xyz

相關問題