0

In the past, my app is record app I use ArrayList ,but ArrayList occur memory leak

`private ArrayList<OutputInputPair>> pairs = new ArrayList<OutPutInputPair>();`

so, when I click record stop button execute pairs.clear(); pairs = null;

but if user never click record stop button. always occur memory leak.

so I use WeakHashMap in reference this site

ArrayList<WeakReference<Runnable>> - How to tidy up best?

in the past, I declare on global variable

private ArraytList<OutputInputPair> pairs = new ArrayList<OutputInputPair>();

I changed

private WeakHaspMap<OutputInputPair, Void> pairs = new WeahHashMap<OutputInputPair, Void>();

and Iterator<OutputInputPair> iterator = pairs.keySet().iterator(); declare on global variable

According to my plan, execute my method. but if I declare WeakHashMap on global variable not execute my method.

my method source

public void process() {
     while(iterator.hasNext()) {
         OutputInputPair pair = iterator.next();
         //data insert on queue
     }
     while (!stopped) { //when I click record stop button, stopped is true 
         while(iterator.hasNext()) {
            OutputInputPair pair = iterator.next();
            Log.d(TAG, "<<<<<process>>>>"); //not show this log
            recordstart(pair);
         }
     }
   }

but if write Iterator<OutputInputPair> iterator = pairs.keySet().iterator();on my method, execute my method.

@Override
public void process() {
  Iterator<OutputInputPair> iterator = pairs.keySet().iterator(); // 
   while(iterator.hasNext()) {
         OutputInputPair pair = iterator.next();
         //data insert on queue
     }
     while (!stopped) { //when I click record stop button, stopped is true 
         while(iterator.hasNext()) {
            OutputInputPair pair = iterator.next();
            Log.d(TAG, "<<<<<process>>>>"); //not show this log
            recordstart(pair);
         }
     }
  }

this source execute my method.

in other words,why add 'Iterator iterator = pairs.keySet().iterator();` on global variable, not execute my method?

Why I want to be a global variable, if I add in my method, It runs indefinitely. because while(!stopped) .

please help me thanks.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
hyunwook cho
  • 85
  • 1
  • 10

1 Answers1

0

It's hard to say for sure without knowing more context to your code, but if you look at the docs for HashMap.keySet it reads

If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined.

So if you initialize an iterator over the keySet in a static variable (what you're calling "global" I guess), and then some other part of your code modifies the entries in the hash map, it could have unpredictable results.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63