Created
November 9, 2019 15:07
-
-
Save iRYO400/82fbda2ddf52f440a066c27fbe12f351 to your computer and use it in GitHub Desktop.
ThreadExecutor example, stolen from here https://github.com/dmilicic/Android-Clean-Boilerplate/blob/master/app/src/main/java/com/kodelabs/boilerplate/domain/executor/impl/ThreadExecutor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kodelabs.boilerplate.domain.executor.impl; | |
import com.kodelabs.boilerplate.domain.executor.Executor; | |
import com.kodelabs.boilerplate.domain.interactors.base.AbstractInteractor; | |
import java.util.concurrent.BlockingQueue; | |
import java.util.concurrent.LinkedBlockingQueue; | |
import java.util.concurrent.ThreadPoolExecutor; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* This singleton class will make sure that each interactor operation gets a background thread. | |
* <p/> | |
*/ | |
public class ThreadExecutor implements Executor { | |
// This is a singleton | |
private static volatile ThreadExecutor sThreadExecutor; | |
private static final int CORE_POOL_SIZE = 3; | |
private static final int MAX_POOL_SIZE = 5; | |
private static final int KEEP_ALIVE_TIME = 120; | |
private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; | |
private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<Runnable>(); | |
private ThreadPoolExecutor mThreadPoolExecutor; | |
private ThreadExecutor() { | |
long keepAlive = KEEP_ALIVE_TIME; | |
mThreadPoolExecutor = new ThreadPoolExecutor( | |
CORE_POOL_SIZE, | |
MAX_POOL_SIZE, | |
keepAlive, | |
TIME_UNIT, | |
WORK_QUEUE); | |
} | |
@Override | |
public void execute(final AbstractInteractor interactor) { | |
mThreadPoolExecutor.submit(new Runnable() { | |
@Override | |
public void run() { | |
// run the main logic | |
interactor.run(); | |
// mark it as finished | |
interactor.onFinished(); | |
} | |
}); | |
} | |
/** | |
* Returns a singleton instance of this executor. If the executor is not initialized then it initializes it and returns | |
* the instance. | |
*/ | |
public static Executor getInstance() { | |
if (sThreadExecutor == null) { | |
sThreadExecutor = new ThreadExecutor(); | |
} | |
return sThreadExecutor; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment