简体   繁体   中英

Could this code create a potential memory leak?

I'm using a custom Database class in my code to manage my database and handle transactions. Whenever I instantiate it, I pass the application context to it's constructor. Reading up on the articles at the Android developer site makes me wonder if I'm doing something that could cause a huge memory leak in my application. Simplified, my code looks like this, first off an activity:

    public class MyActivity extends Activity
    {

        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.somelayout);

            Database db = new Database(getApplicationContext());
        }

    }

And my database class (in a seperate file) looks like this:

public class Database
{

    Context context;

    public Database(Context context)
    {
        this.context = context;
    }

    public DatabaseHelper extends SQLiteOpenHelper
    {
        // Pass the context to the constructor etc etc.
    }

}

The code might have bugs, I wrote it quickly in notepad. Anyway, this got me worried that the db object keeps the context when the user navigates away from the activity, thus uneccesarily spending a huge amount of resources. If this is indeed the case, how can I avoid this? Is there a way to destroy and object when it is no longer needed?

The object referenced by db is eligible for garbage collection as soon as onCreate finishes. So there is no problem here.

If you made db or Database.context into a static field, that's when you should start to worry.

If the Database object holds resources and is not closed properly you might get into trouble.

If at all possible stay at pure SQL level, and use JDBC pooling to get standard way of handling these things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM