I am exercising my multi-threading skills in java. Below is a piece of code that is supposed to remove a folder and make sure that:
if (freshDB) {
LOG.warn("Refreshing the database!");
ExecutorService executorService = Executors.newSingleThreadExecutor();
final Future<Boolean> result = executorService.submit(new Callable<Boolean>() {
public Boolean call() {
return FileHandler.removeFolder(dbLocation);
}
});
do {
// makes sure the folder is removed
}
while (result.get() == false);
}
Is this the right way to do it? if not why? please elaborate.
No, it’s not.
First of all, the loop at the end doesn’t make much sense.
result.get()will always return the same value: the submitted task is excuted only once, andresult.get()will return the result of this single execution.And anyway, what’s the point of starting a new thread if the initial thread immediately stops, waiting for the started thread to be finished? Doing everything in the initial thread would be much simpler, and more efficient.