Interface TimeService

  • All Known Implementing Classes:
    ClockTimeService
    Functional Interface:
    This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

    @Deprecated
    @FunctionalInterface
    public interface TimeService
    Deprecated.
    Provides time related methods for computing durations, for providing the now instant and other use cases.

    Why using a service interface instead of JVM provided time methods?

    Simply because you gain better control over the time understood by the application. For example, if you would have to code an expiration time logic, you would check periodically if the computed expiration timestamp is greater than the now timestamp. So far, so good.

    When it comes to testing, things gets worst: you typically have to use Thread.sleep(long) to wait for a given amount of time so that your expiration date is reached. That makes tests much longer to execute and somehow brittle when you're testing short timeouts.

    Using a TimeService helps you to keep your code readable and provides a way to better control how the time is flowing for your application (especially useful in the tests).

    For example, now() is used in place of System.currentTimeMillis(). in your code and you can easily mock it and make it return controlled values. Here is an example with Mockito:

     @Mock
     private TimeService time;
    
     @BeforeMethod
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
     }
    
     @Test
     public shouldAdvanceInTime() throws Exception {
         // Mimics steps in the future at each call
         when(time.now()).thenReturn(0L, 1000L, 10000L);
    
         assertThat(time.now()).isEqualTo(0L);
         assertThat(time.now()).isEqualTo(1000L);
         assertThat(time.now()).isEqualTo(10000L);
     }
     
    TimeService provides a default service implementation using the System provided time methods for ease of use.
    Since:
    1.3.4
    See Also:
    System.currentTimeMillis()
    • Method Detail

      • now

        long now()
        Deprecated.
        Returns a value that represents "now" since the epoch.
        Returns:
        a value that represents "now" since the epoch.
        Since:
        1.3.4
      • since

        default long since​(long past)
        Deprecated.
        Computes the elapsed time between now and past.
        Parameters:
        past - time value to compare to now.
        Returns:
        the elapsed time
        Since:
        1.3.4