From 72ae4c013627df5f9b5b3cc1fe659d1a275b5f85 Mon Sep 17 00:00:00 2001 From: Rui Hu Date: Thu, 14 Mar 2024 10:57:16 +0800 Subject: [PATCH] Move sleep skip to utils class --- .../cleverthis/interview/padlock/PadlockImpl.java | 3 +-- .../java/com/cleverthis/interview/padlock/Utils.java | 12 ++++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/padlock-impl/src/main/java/com/cleverthis/interview/padlock/PadlockImpl.java b/padlock-impl/src/main/java/com/cleverthis/interview/padlock/PadlockImpl.java index f9ccaea..fbe49f9 100644 --- a/padlock-impl/src/main/java/com/cleverthis/interview/padlock/PadlockImpl.java +++ b/padlock-impl/src/main/java/com/cleverthis/interview/padlock/PadlockImpl.java @@ -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); diff --git a/padlock-impl/src/main/java/com/cleverthis/interview/padlock/Utils.java b/padlock-impl/src/main/java/com/cleverthis/interview/padlock/Utils.java index 118f6a3..b3834ba 100644 --- a/padlock-impl/src/main/java/com/cleverthis/interview/padlock/Utils.java +++ b/padlock-impl/src/main/java/com/cleverthis/interview/padlock/Utils.java @@ -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 {