実験課題2

Exercise 2(課題2) See the section 6.3.1. "Analysis of Memory Usage". Show the memory-leaking method in the program as described below as a screenshot and a reason. Follow instructions below to show the memory leak.

  1. create the Java application project named chapter6kadai.
  2. create PPAPGenerator class and main method as below.
  3. run the profiler with Object mode and the profiling target to All classes.
    • If the profiler does not show the dialog of Figure 29, must increase size parameter more than 100000 described in the 9th line of PPAPGenerator class program.
  4. check the memory-leaking class object except byte[] class according to the huge number of live objects.
  5. specify its class object by using profiling class in right-clicked menu.
  6. re-run the profiler with it.
  7. check the memory-leaking method according to the larger number of Generation about live objects.
/**
 * PPAPの歌詞をランダムに作成します。
 * @author Me
 */
public class PPAPGenerator {
    
    private String[] words = {"I", "have", "a", "an", "Ah", "pie", "pen", "pineapple", "apple"};
    
    private ArrayList<String> randomList = new ArrayList<String>();
    
    private Random rng;
    
    private int startIndex;
    
    private int endIndex;
    
    public PPAPGenerator() {
        
        this.rng = new Random(); 
        this.startIndex = 0;
        
        this.endIndex = 0;
    }
    
    public void generate() {
        
        int wordnum = this.rng.nextInt(this.words.length);
        
        this.randomList.add(this.words[wordnum] + " ");
        
        this.endIndex++;
    }
    
    public void print() {
        
        while (this.startIndex != this.endIndex) {
            
            System.out.print(this.randomList.get(this.startIndex));
            
            this.startIndex++;
        }
        System.out.println();
    }
    
}
Figure:PPAPGenerator class
public static void main(String[] args) {
    
    // 9単語からランダムに文字列を作成するオブジェクトです。
    PPAPGenerator ppap = new PPAPGenerator();
    
    Random rng = new Random();
    
    // 10万回個の単語を出力します。
    int size = 100000;
    
    for (int i = 0; i < size; i = i + 1) {
        
        // 90%の確率で文字列を作成します。
        while(rng.nextDouble()<0.9) {
            // 呼び出すたびに文字列に単語を1つ追加します。
            ppap.generate();
        }
        
        // 文字列を表示します。
        ppap.print();
    }
}
Figure:`main` method for PPAPGenerator

(6.3.1.節をよく読み、プロジェクトchapter6kadai2を作成し、以下に示すPPAPGeneratorクラスとmainメソッドを実装しなさい。その後、プロファイリングを行って、メモリリークしていそうなライブオブジェクトを選定し、さらに「選択したクラスに限定したプロファイリング」を実施して、世代数から最も怪しいメソッドをプロファイリング結果のスクリーンショットを用いて示しなさい。なお、図28のプロファイル設定においては、プロジェクトのクラスを選択するのではなく、すべてのクラスを選択した状態で行いなさい。ここで、byte[]クラスを選択したクラスの対象としないように注意すること。なお、図29のようにスナップショットを取得するかどうかのダイアログが表示されない場合は、mainメソッドの9行目のsizeの値を増やして表示されるように調整して、課題を実施しなさい。)