memory allocated in AsyncTask persists creating leak


Last Updated:

  1. FoxMulder900

    FoxMulder900 Member This Topic's Starter

    Joined:
    Jun 13, 2010
    Messages:
    6
    Likes Received:
    0
    I am working on a small game where I want a loading screen to appear when loading the next level. I have accomplished this using an AsycTask, the idea being that I draw the loading screen first and call invalidate(), then I start an AsyncTask which loads a new map object in the background so that the UI thread can continue and draw the loading screen. When complete, the map is returned and the loading screen is removed.

    Code (Text):
    1.  
    2.  
    3. public class LoadTask extends AsyncTask<String,Integer,Map>{
    4.     protected Map doInBackground(String... mapName) {
    5.         return new Map(mapName[0]);
    6.     }
    7.  
    8.     protected void onPostExecute(Map newMap) {
    9.         //Set newMap as active Map
    10.         //Remove loading screen and draw newMap
    11.     }
    12. }
    13.    
    14. //Draw Loading Screen
    15. //Call invalidate
    16. //Execute a LoadTask to that UI thread can continue to draw loading screen
    17. new LoadTask().execute(mapName);
    18.  
    This works, however; the Map object which i create in doInBackground seems to persist, so after the 4th level, even though I only have references to 1 Map, I have 4 Map objects in memory (I got this information by doing a heap dump after each level load). At this point I get an OutOfMemoryError.

    Something else to note is that after the 4th level load, under the Threads tab in the DDMS i see:
    AsyncTask#1
    AsyncTask#2
    AsyncTask#3
    AsyncTask#4
    all with a status of "wait"

    Any ideas here would be greatly appreciated!
     

    Advertisement
  2. FoxMulder900

    FoxMulder900 Member This Topic's Starter

    Joined:
    Jun 13, 2010
    Messages:
    6
    Likes Received:
    0
    Well I have found a solution that works, although I cannot say I understand why the first way didn't work. All I had to do was set my new map in the doInBackground function instead of passing it through to onPostExecute (which I thought was the whole point of using AsyncTasks)

    Code (Text):
    1. public class LoadTask extends AsyncTask<String,Void,Void>{
    2.     protected Map doInBackground(String... mapName) {
    3.         Map newMap = new Map(mapName[0]);
    4.         //Set newMap as active Map
    5.         return null;
    6.     }
    7.  
    8.     protected void onPostExecute(Void tmp) {
    9.         //Remove loading screen
    10.     }
    11. }
    12.    
    13. //Draw Loading Screen
    14. //Call invalidate
    15. //Execute a LoadTask to that UI thread can continue to draw loading screen
    16. new LoadTask().execute(mapName);
     

Share This Page

Loading...