Move sleep skip to utils class

This commit is contained in:
Rui Hu 2024-03-14 10:57:16 +08:00
parent 499413f09a
commit 72ae4c0136
2 changed files with 13 additions and 2 deletions

View File

@ -28,7 +28,6 @@ import static com.cleverthis.interview.padlock.Utils.ensureSleep;
* After create, the input buffer is empty, you have to initialize.
*/
public class PadlockImpl {
private final boolean fast = Boolean.parseBoolean(System.getProperty("fast"));
private final int numpadSize;
private final Integer[] inputBuffer;
private final Integer[] correctPasscode;
@ -66,7 +65,7 @@ public class PadlockImpl {
* @return The old value, null if not initialized.
*/
public synchronized Integer writeInputBuffer(int address, int keyIndex) {
if (!fast) ensureSleep(1000);
ensureSleep(1000);
if (keyIndex < 0 || keyIndex >= numpadSize)
throw new IllegalArgumentException(
"keyIndex out of range. Keypad size: " + numpadSize + ", keyIndex: " + keyIndex);

View File

@ -1,12 +1,24 @@
package com.cleverthis.interview.padlock;
class Utils {
/**
* Check if the sleep is disabled.
* User can use `-Dfast=true` in the jvm args,
* or change it on the fly.
* Might waste sometime on checking this flag, but the effect should be minor.
* */
private static boolean shouldSkipSleep() {
return Boolean.parseBoolean(System.getProperty("fast"));
}
/**
* Ensure we will wait a given amount of time even if there are interruptions.
* Property `-Dfast=true` can disable the sleep.
*
* @param millis The time you want to sleep, measure in millisecond.
*/
public static void ensureSleep(long millis) {
if (shouldSkipSleep()) return;
long endTime = System.currentTimeMillis() + millis;
while (endTime > System.currentTimeMillis()) {
try {