AsyncTask learning, asynctask

Source: Internet
Author: User

AsyncTask learning, asynctask

Record the learning experience of AsyncTask:

The AsyncTask class is used to process asynchronous requests. When we perform time-consuming operations in the UI thread (main thread) (obtain data from the network, obtain data from the database, or read files) it will block the running of the main thread and cause the interface to become non-smooth. In this case, we need to execute these time-consuming operations in another thread and try to execute the UI operations in the main thread.

In general, we use Thread + handler to process time-consuming operations and deal with the aftermath. AsyncTask encapsulates Thread and Handler to simplify code writing and facilitate our use.

The architecture of AsyncTask is to create an Executor to execute Runnable objects in ArrayDeque. This Executor can be customized or SerialExecutor implemented by AsyncTask by default.

 private static class SerialExecutor implements Executor {        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();        Runnable mActive;        public synchronized void execute(final Runnable r) {            mTasks.offer(new Runnable() {                public void run() {                    try {                        r.run();                    } finally {                        scheduleNext();                    }                }            });            if (mActive == null) {                scheduleNext();            }        }        protected synchronized void scheduleNext() {            if ((mActive = mTasks.poll()) != null) {                THREAD_POOL_EXECUTOR.execute(mActive);            }        }    }

The above code SerialExecutor implements the execute method in Executor. execute adds a Runnable object (in this class, it is a FutureTask) to the queue, and then judges whether there is an active Runnable, if not, take one from the Queue, set it as the Runnable of the current activity, and execute this Runnable.

Now let's take a look at what a Runnable has done. First, he executes the Runnable run method and finally executes the sheduleNext () function to enter this function, he pulls the first element of the Queue and runs it as the current active Runnable. If it is not empty, the Executor executes the Runnable object in the Queue in sequence. Of course, you can also customize your Executor. For example, you can assign weights to the queue. runnable with a higher weight can be executed first.

PriorityBlockingQueue<PriorityRunnable> mTasks=new PriorityBlockingQueue<PriorityRunnable>();  private static class PriorityRunnable implements Comparable<PriorityRunnable>{        private Runnable mRunnable;            private  Priority mPriority;            private Integer mSequence;             private AtomicInteger mSequenceGenerator = new AtomicInteger();public  PriorityRunnable(final Runnable r){            mRunnable=new Runnable() {                public void run() {                    try {                        r.run();                    } finally {                        scheduleNext();                    }                }            };                this.setmSequence(getSequenceNumber());               // this.setmPriority();            } public int getSequenceNumber() {        return mSequenceGenerator.incrementAndGet(); }public Runnable getRunnable(){return mRunnable;}public void setmRunnable(Runnable mRunnable) {this.mRunnable = mRunnable;}public Priority getmPriority() {return mPriority;}public void setmPriority(Priority mPriority) {this.mPriority = mPriority;}public Integer getmSequence() {return mSequence;}public void setmSequence(Integer mSequence) {this.mSequence = mSequence;}@Overridepublic int compareTo(PriorityRunnable another) {// TODO Auto-generated method stub Priority left = this.getmPriority();      Priority right = another.getmPriority();      return left == right ?                this.mSequence - another.mSequence :                right.ordinal() - left.ordinal();}        }

The above Runnable is customized and implements the compareable interface, because we use PriorityBlockingQueue to accommodate Runnable.

As mentioned above, Runnable in the execute parameter is a FutureTask, and FutrueTask is used to execute asynchronous computation. It can encapsulate a Callable or Runnable and obtain the Callable calculation result and running status. In AsyncTask, a new FutureTask is created for each time-consuming request. The initialization of FutureTask is in new AsyncTask.

   public AsyncTask() {        mWorker = new WorkerRunnable<Params, Result>() {            public Result call() throws Exception {                mTaskInvoked.set(true);                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);                //noinspection unchecked                return postResult(doInBackground(mParams));            }        };        mFuture = new FutureTask<Result>(mWorker) {            @Override            protected void done() {                try {                    postResultIfNotInvoked(get());                } catch (InterruptedException e) {                    android.util.Log.w(LOG_TAG, e);                } catch (ExecutionException e) {                    throw new RuntimeException("An error occured while executing doInBackground()",                            e.getCause());                } catch (CancellationException e) {                    postResultIfNotInvoked(null);                }            }        };    }

In AsyncTask initialization, a new WorkRunnable is first created, and WorkRunnable implements the Callable <Result> abstract class. In the call method body, mTaskInvoked is first created. set (true). mTaskInvoked is an AutomicBoolean variable used to track the status of a Task. When the current Task is executed, set the status to true, used to determine whether a Task is canceled. After mTaskInvoked is set, the thread priority for the Task is set to Process. THREAD_PRIORITY_BACKGROUND level. Finally, the postResult function value is returned and the result is postResult ():

  private Result postResult(Result result) {        @SuppressWarnings("unchecked")        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,                new AsyncTaskResult<Result>(this, result));        message.sendToTarget();        return result;    }

The postResult function parameter is the execution result of the doInBackground () function. The doInBackground () function here is the abstract method of AsyncTask. We need to implement this function in the Custom AsyncTask class, the main logic of our asynchronous request is executed here. The Return Value Type of doInBackground () function is Result and Result is generic. The postResult () function is used to create a Message and encapsulate the Result as AsyncTaskResult, the Message is carried to the Handler of the corresponding thread for processing. Let's take a look at the data structure of AsyncTaskResult:

 private static class AsyncTaskResult<Data> {        final AsyncTask mTask;        final Data[] mData;        AsyncTaskResult(AsyncTask task, Data... data) {            mTask = task;            mData = data;        }    }

It has two fields: mTask and mDate. mTask is used to save your reference and mData is used to save the value of mFuture. get (). The usage of this class will be further analyzed below.

New WorkRunnable is followed by new FutureTask, and mWorker is passed in as the parameter to the FutureTask as the source for obtaining data. FutureTask can control the thread execution and obtain the data returned by the thread. After Callable in FutureTask is executed, the done function of FutureTask is triggered. If the thread is Cancle before execution, run the done function of FutureTask directly. The status of the FutureTask is isDone, And the postResultIfNotInvoked () function is mainly used to handle the situation where the task is cancel. When the Task is cancel, the call function of WorkRunnable will not be executed, and the mTaskInvoked value will, then execute the postResult function to ensure that tasks can be processed, whether executed or cancel.

  private void postResultIfNotInvoked(Result result) {        final boolean wasTaskInvoked = mTaskInvoked.get();        if (!wasTaskInvoked) {            postResult(result);        }    }

Now let's look at InternalHandler, which is a sub-class of Handler. He accepts the data sent from the Message and judges based on msg. what for different logic processing. Msg. what has two types: MESSAGE_POST_RESULT, which indicates processing the message sent after mWorkRunnable is executed, and executing the AsyncTask finish function. The other is MESSAGE_POST_PROGRESS, which indicates processing the message sent when mWorkRunnable is updated, and executing the onProgressUpdate function of AsyncTask.

Finish function:

private void finish(Result result) {        if (isCancelled()) {            onCancelled(result);        } else {            onPostExecute(result);        }        mStatus = Status.FINISHED;    }

The function body first checks whether the current task is canceled. If isCancelled is used, the onCacelled (result) function is executed.

OnCancelled functions:

 protected void onCancelled(Result result) {        onCancelled();    }  protected void onCancelled() {    }

We can override this function to execute our own operations.

If the current task is not canceled, execute the onPostExecute (result) function. We can also override this function in the AsyncTask subclass, which is executed in the UI thread, you can operate on the UI elements.

Here, a variable mStatus is displayed and its definition is as follows:

   public enum Status {        /**         * Indicates that the task has not been executed yet.         */        PENDING,        /**         * Indicates that the task is running.         */        RUNNING,        /**         * Indicates that {@link AsyncTask#onPostExecute} has finished.         */        FINISHED,    }

It has three States. One is Pendding, which is clearly stated to mark tasks that have not been executed.SRunning is used to identify the status of a Running task, and Finished is used to identify the status of a task that has been executed.

Now let's take a look at how AsyncTask is executed. We usually use new myasynctask(.exe cutef ();

Let's take a look at the true nature of the execute function:

public final AsyncTask<Params, Progress, Result> execute(Params... params) {        return executeOnExecutor(sDefaultExecutor, params);    }

 

 public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,            Params... params) {        if (mStatus != Status.PENDING) {            switch (mStatus) {                case RUNNING:                    throw new IllegalStateException("Cannot execute task:"                            + " the task is already running.");                case FINISHED:                    throw new IllegalStateException("Cannot execute task:"                            + " the task has already been executed "                            + "(a task can be executed only once)");            }        }        mStatus = Status.RUNNING;        onPreExecute();        mWorker.mParams = params;        exec.execute(mFuture);        return this;    }

First, the function determines the status of the current task. If the status is not Running, an exception is thrown. If execute () is executed, the current task is Running, throw the "cannot execute task: the task is already running" exception,

My guess is:

The Future method can only retrieve results when the computation is complete. If the computation is not complete, the get method is blocked. Once the calculation is complete, you cannot start or cancel the calculation again.

As long as you re-create AsyncTask (), you will get a brand new task.

Return to the Code. If the status of the current task is pending, update it to Running. Then, execute the onPreExecute () function, which is the same as the onPostExecute and onBackground () functions. You can define your own business logic in the client override. After the execution is complete, assign the variable parameter params from the client to the mParams member variable of mWorkRunnable for saving. Finally, call the execute () function of the thread pool. Previously, the execute () function adds the current task queue to the queue. If no task is being executed, the newly created task is executed, if a task is being executed, it is first cached in the queue and waiting for the task to be executed.

Finally, let's take a look at the thread pool:

 private static final ThreadFactory sThreadFactory = new ThreadFactory() {        private final AtomicInteger mCount = new AtomicInteger(1);        public Thread newThread(Runnable r) {            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());        }    }; private static final BlockingQueue<Runnable> sPoolWorkQueue =            new LinkedBlockingQueue<Runnable>(10); public static final Executor THREAD_POOL_EXECUTOR            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

The ThreadFactory class is used to create threads. You can simply override the newThread method to define your own ThreadFactory.

The ThreadPoolExecutor class has several important parameters: core_pool_size: Number of threads stored in the pool, including Idle threads ., Maximum_pool_size: Maximum number of threads allowed in the pool. keep_alive: when the number of threads exceeds the core, this is the maximum time for redundant Idle threads to wait for new tasks before termination. Unit-keepAliveTime parameter time unit. WorkQueue-the queue used to keep the task before execution. This queue only keeps Runnable tasks submitted by the execute method. ThreadFactory-the factory used by the execution program to create a new thread.

This is the end of the general analysis of AsycnTask. Let's talk about my thoughts on AsycnTask:

1. AsycnTask uses the responsibility chain mode in the design mode during the SerialExecutor design.

2. When you frequently obtain network data or perform time-consuming operations, new AsycnTask () may cause a large number of temporary objects, affect the performance, and cause a choppy interface.

3. AsycnTask is not suitable for uploading large files. Generally, to upload large files, use socket or resumable upload, and use RandomAceccsFile.

4AsycnTask uses the Thread pool to manage threads, which saves more memory than creating a separate Thread each time.

The above is not correct.

About ThreadPoolExecutor, point this http://blog.sina.com.cn/s/blog_70bcd7c10101a1w7.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.