0
// waiting/pausing
    static class Waits {
        // vars
        private static long waiter, timerStart;
        private static double implicitWaitTime, restoreImplicitWaitTime;
        private long _waiter;
        private double _implicitWaitTime, _restoreImplicitWaitTime;

        // timer
        static void startTimer(){
            timerStart = System.currentTimeMillis();
        }
        @SuppressWarnings("unused")
    static String getTimerElapsedTime(){
            long millis = System.currentTimeMillis() - timerStart;
            long second = (millis / 1000) % 60;
            long minute = (millis / (1000 * 60)) % 60;
            long hour = (millis / (1000 * 60 * 60)) % 24;

            return String.format("%02d:%02d", minute, second);
        }

From the looks of it, this is not thread-safe correct? I need it to be thread-safe and I am not sure how to go about this. What else is there besides AtomicInteger? I need each thread to be able to have its own timer. EDIT: just found that AtomicInteger can't even be used for long values

mastercool
  • 290
  • 2
  • 17
  • See [How do I measure time elapsed in Java?](https://stackoverflow.com/questions/1770010/how-do-i-measure-time-elapsed-in-java/1776053#1776053) for insight into the difference between System.currentTimeMills() and System.nanoTime(). – dnault Aug 31 '20 at 20:47
  • 3
    It's really not clear what the issue is. In what sense does this code need to be thread safe? Are you asking if one thread can start the timer and then another thread can check elapsed time? – David Schwartz Aug 31 '20 at 20:48
  • I need to be able to start a timer when a test begins and end it, but each thread needs to keep track of their own timer – mastercool Aug 31 '20 at 20:48
  • Then you probably don't want to use static methods. Instead, use something like Guava's `Stopwatch` or Apache Commons-Lang's `StopWatch` (or look to their source code for inspiration) – dnault Aug 31 '20 at 20:50
  • 1
    Since you said “test”, the test framework’s builtin timers would be a natural choice… – Holger Sep 01 '20 at 07:28
  • 1
    Besides that, there is no need to do time conversions by hand, especially as you’re already using `String.format`. Just use `String.format("%tM:%1$tS%n", millis)` – Holger Sep 01 '20 at 07:51
  • 1
    “*just found that AtomicInteger can't even be used for long values*”…What a surprise. I guess, that’s why there’s also an `AtomicLong`. But neither is for having a different value per thread. – Holger Sep 01 '20 at 07:54

0 Answers0