How to use ExecutorSevice
For example:
new Thread(new Runnable() {
@Override
public void run() {
readManyFiles(path);
}
}).start();
However, weaknesses of using Thread directly is overhead.
If attacker requested this code repeatedly, app could have been exposed to exhaustion of resource.
So, App could not respond user's request.
To solve this problem, we can use ExecutorService.
If using ExecutorService, we can limit system's request using ThreadPool and manage Thread's lifecycle.
For example:
public class YourClass {
private static final String TAG = "YourClass";
private static final int THREAD_PRIORITY_MIN = 1; // Example priority
private final ExecutorService executorService = Executors.newSingleThreadExecutor(); // Or a fixed/cached thread pool
public void exampleFunction(final String filePath) {
executorService.execute(new Runnable() {
@Override
public void run() {
readManyFiles(filePath);
}
});
}
// Remember to shut down the ExecutorService when it's no longer needed
public void shutdownExecutor() {
executorService.shutdown();
}
}
Limiting count of Thread, application can manage the irregular requests.
The other use of ExecutorService
We learned execute method of ExecutorService.
ExecutorService has submit method, too.
The difference of submit method compared to execute method is that submit method can return value.
1) submit(Runnable task) : This method returns a Future<?> object. The Future represents the result of the asynchronous computation. In the case of a Runnable, the get() method of the Future will return null upon successful completion.
2) submit(Callable<T> task): This overloaded submit() method accepts a Callable and returns a Future<T>. The Callable interface is similar to Runnable but allows the task to return a result of type T and throw checked exceptions. The get() method of the returned Future<T> will return the result of the Callable's execution.
For example:
private void submitFetchAndParseTask(final String url) {
Future<String> futureResult = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Log.d(TAG, "Starting to fetch and parse data from: " + url);
// Simulate network fetch and parsing
TimeUnit.SECONDS.sleep(5);
if (url.contains("error")) {
throw new Exception("Failed to fetch data from URL: " + url);
}
String result = "Successfully fetched and parsed data from: " + url;
Log.d(TAG, "Fetch and parse finished: " + result);
return result;
}
});
// Get the result from the Callable
new Thread(() -> {
try {
String result = futureResult.get(); // Blocks until the result is available
Log.d(TAG, "Fetch and parse result: " + result);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Log.e(TAG, "Interrupted while waiting for fetch and parse", e);
} catch (ExecutionException e) {
Log.e(TAG, "Exception during fetch and parse", e.getCause()); // Get the original exception
}
}).start();
}
0 댓글