Obviously, you want to move the dream to a finally block so that it also occurs if the task throws an exception (for example, PasswordExpiredException?).
Another problem is handling the elapsed > duration case. You say it never happens, but are you sure? What if your database query is blocked by a lock? Assuming that you want to refuse authentication in such an event, you can do:
ExecutorService exec = Executors.newFixedThreadPool(10); <T> T doInConstantTime(Callable<T> task, long millis, T defaultResponse) { Future<T> future = exec.submit(task); Thread.sleep(millis); if (future.isDone()) { return future.get(); } else { future.cancel(false);
(Of course, you will need to add the correct exception handling)
I'm not sure, although this is a good way to protect against brute force attacks. Instead, we will cancel the user login after the third unsuccessful login attempt (for a certain period of time or until the administrator unlocks the account). Mention somewhere that you are doing this, and no one has a reason to brute force passwords.
source share