Skip to content

Misuse of AsyncTask #41

@cuixiaoyiyi

Description

@cuixiaoyiyi

According to our research, there are misuses about the following servral AsyncTask classes:
( in ru.valle.btc. MainActivity.java)

    @Nullable
    private AsyncTask<Void, Void, KeyPair> addressGenerateTask;
    @Nullable
    private AsyncTask<Void, Void, GenerateTransactionResult> generateTransactionTask;
    @Nullable
    private AsyncTask<Void, Void, KeyPair> switchingCompressionTypeTask;
    @Nullable
    private AsyncTask<Void, Void, KeyPair> switchingSegwitTask;
    @Nullable
    private AsyncTask<Void, Void, KeyPair> decodePrivateKeyTask;
    @Nullable
    private AsyncTask<Void, Void, Object> bip38Task;
    @Nullable
    private AsyncTask<Void, Void, ArrayList<UnspentOutputInfo>> decodeUnspentOutputsInfoTask;

The problems are:

  1. They are anonymous inner classes. They hold strong reference to the GUI element of Activity( MainActivity ), which can lead to memory leak when the Activity is destroyed and the AsyncTask did not finish
  2. Their instances are cancelled before the Activity is destroyed. But in the doInBackground method there are for or while loop without the call of isCancelled() . These loops may not be able to terminate when the task is cancelled. This will cause waste of resources or even flashback

I think we can make following changes to fix the misuse problems:

  1. I think the GUI-related fields should be wrapped into WeakReference. Take
    private final MainActivity _context as example, it can be changed to private final WeakReference<MainActivity> _context.
  2. Every loop should check the status of AsyncTask to break the loop.
while(condition1){
     if(isCancelled()){
          break;
     }
     //blablabla…
     while(condition2){
         if(isCancelled()){
              break;
         }
         //blablabla…
     }
}

These are my suggestions above, thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions