Android uses the thread pool to efficiently implement asynchronous tasks

Source: Internet
Author: User

Android uses the thread pool to efficiently implement asynchronous tasks

Asynchronous tasks are often used in both android applications and java applications. Especially, android itself is not secure as a thread. asynchronous tasks are required for a slightly time-consuming operation, in the past, general asynchronous task development for java and android was implemented only by using Thread and Runnable. The android system itself also has its own AsyncTask to handle asynchronous tasks. however, these are not the most efficient asynchronous task processing methods, especially when there are multiple tasks, the above methods need to constantly create new threads in the background, we also need to manage the thread lifecycle by ourselves, otherwise it will easily cause memory leakage.

Since jdk1.5, we can use the thread pool to efficiently create multiple asynchronous tasks without having to manage the thread lifecycle. we only need to focus on the business logic code of asynchronous tasks and disable the thread pool as a whole when appropriate, which can greatly improve the performance of the entire application.

Next, let's take a look at some frequently used classes related to thread pools, including Executor, ExecutorService, AbstractExecutorService, ThreadPoolExecutorService, ScheduledExecutirService, Callable, Runnable, etc, the commonly used classes are the above. next we will analyze the functions of these classes.

1. Executor, an interface that provides only one method executor (Runnable command); provides the most basic functions of the thread pool to execute asynchronous tasks.

2. ExecutorService is also an interface that inherits the Executor interface and extends the lifecycle methods that some thread pools should have. The source code (Part) is as follows:

Public interface ExecutorService extends Executor {/*** function: closes the thread pool and does not stop existing tasks, but cannot add new tasks to it. */void shutdown ();/***** @ return list of tasks that never commenced execution * function: immediately close the entire thread pool and stop the tasks in the pool. */List
 
  
ShutdownNow (); boolean isShutdown ();/*** function: Add a Callable task to the thread pool .*/
  
   
Future
   
    
Submit (Callable
    
     
Task );/***
     
* Function: Add a Runnable task to the thread pool.
*/ Future Submit (Runnable task, T result); Future Submit (Runnable task );}

 

3. AbstractExecutorService, a thread pool abstract class, provides the basic implementation of all thread pool classes. Some code is as follows:
       

 

 

Public abstract class implements actexecutorservice implements ExecutorService {/*** converts a Runnable task to a RunnableFutrue task **/protected
        
         
RunnableFuture
         
          
NewTaskFor (Runnable runnable, T value) {return new FutureTask
          
           
(Runnable, value );}
           
/*** Convert a Callable task to a RunnableFutrue task **/protected
            
             
RunnableFuture
             
              
NewTaskFor (Callable
              
               
Callable) {return new FutureTask
               
                
(Callable );}
                
/*** Add a Runnable task to the thread pool to convert the task to a RunnableFuture task in the internal part **/public Future
                 Submit (Runnable task) {if (task = null) throw new NullPointerException (); RunnableFuture
                 
                  
Ftask = newTaskFor (task, null); execute (ftask); return ftask;} public
                  
                   
Future
                   
                    
Submit (Runnable task, T result) {if (task = null) throw new NullPointerException (); RunnableFuture
                    
                     
Ftask = newTaskFor (task, result); execute (ftask); return ftask ;}
                     

                     

                     
/*** Add a Callable task to the thread pool to convert the task to a RunnableFuture task in the internal part **/

 


                     
Public
                     
                      
Future
                      
                        Submit (Callable
                       
                         Task) {if (task = null) throw new NullPointerException (); RunnableFuture
                        
                          Ftask = newTaskFor (task); execute (ftask); return ftask ;}}
                         

                         

                         
By reading the source code, we can know that all tasks processed in the thread are of the FutureTask type.
                         
3. Executors: provides a series of static methods to create different types of thread pools. The source code will not be copied.

 

These classes basically constitute the entire framework of the java thread pool. Using these classes, we can easily Implement Asynchronous tasks in the thread pool. The following uses a Demo to explain the basic usage.

A recent requirement is as follows: Download a large zip package from the server to the local client. notifycation is used to notify users of the progress of file download. idea: to download something from the server, start a Service dedicated for downloading, enable asynchronous download tasks in the Service through the thread pool, and create callback interfaces in different States during the download process, used to notify the user of the download progress. in this Demo, to achieve convenience, we first copied the file from one path to another to simulate downloading the file from the server. (the principle is the same. Downloading an object is equivalent to copying an object from the server to a local path ).

The following describes the structure of the entire project:

 

Functions of each class:

1. CopyTask is a class dedicated to implementing the file copy function. There is no other task business. The Code is as follows:

Package copy; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; import java. io. randomAccessFile; /*** @ author rzq * @ functuion android SD card file copy task class */public class CopyTask implements Runnable {/*** file path to be copied */private String sourceFilePath; private File sourceFile;/*** Destination Address File */private String destationFilePath; private File destationFile; /*** Copy process status callback */private IDownloadListener downlaodListener; private long fileContentLength; private long currentLenght = 0; public CopyTask (String sourceFilePath, String destationFilePath, IDownloadListener downloadListener) {this. sourceFilePath = sourceFilePath; this. destationFilePath = destationFilePath; this. downlaodListener = downloadListener;} private boolean prepare () {sourceFile = new File (source FilePath); fileContentLength = sourceFile. length ();/*** if the File length is greater than 0, you have prepared */if (fileContentLength> 0) {destationFile = new File (destationFilePath); downlaodListener. onPrepared (fileContentLength); return true;} return false;} @ Overridepublic void run () {if (prepare ()) {/*** Start copying the file after preparation */RandomAccessFile randomAccessFile = null; FileInputStream in = null; try {in = new FileInputStream (sourceFile); byte [] buf Fer = new byte [2048]; int length =-1; randomAccessFile = new RandomAccessFile (destationFile, rwd); while (length = in. read (buffer ))! =-1) {randomAccessFile. write (buffer, 0, length); currentLenght + = length; downlaodListener. onProgressChanged (int) (currentLenght/fileContentLength * 100); if (currentLenght = fileContentLength) {downlaodListener. onFinished (int) currentLenght) ;}} catch (FileNotFoundException e1) {downlaodListener. onFailure (); e1.printStackTrace ();} catch (IOException e2) {downlaodListener. onFailure (); e2.printStackTrace ();} finally {try {in. close (); randomAccessFile. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}}
2. The CopyManager class is used to create a thread pool and add tasks to it. The Code is as follows:
package copy;import java.lang.ref.WeakReference;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.ThreadPoolExecutor;public class CopyManager {private static CopyManager manager;private CopyTask copyTask;private ThreadPoolExecutor threadPool;private CopyManager() {threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();}static {manager = new CopyManager();}public static CopyManager getInstance() {return manager;}public void startCopyFile(String sourceFile, String destiationFile,IDownloadListener listener) {copyTask = new CopyTask(sourceFile, destiationFile, listener);Future
                           request = threadPool.submit(copyTask);new WeakReference
                          
                           >(request);}}
                          
3. IDownloadListener: listens for different callback executions in different States. The Code is as follows:
Package copy; public interface IDownloadListener {/*** start request callback */public void onStarted ();/*** the request is successful, the preparation callback before the download ** @ param contentLength * file length * @ param downloadUrl **/public void onPrepared (long contentLength);/*** is downloading, update progress callback ** @ param progress * Current download progress * @ param completeSize * length of downloaded completion * @ param downloadUrl **/public void onProgressChanged (int progress ); /*** callback paused during download ** @ param completeSize * @ param downloadUrl */public void onPaused (int progress, int completeSize ); /*** download completed callback */public void onFinished (int completeSize);/*** download failed callback */public void onFailure ();}
4. CopyService: file download service. You can call CopyManager to start the download task. The source code is no longer pasted, and the entire Demo source code will be uploaded later.

 

Related Article

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.