0
public static void main(String[] args)
{
    Map<Long, Long> map = IntStream.range(0, 1_000_000)
        .parallel()
        .mapToObj(i -> System.nanoTime())
        .collect(Collectors.groupingBy(x -> x, Collectors.counting()));

    map.entrySet()
        .stream()
        .max(Entry.comparingByValue())
        .ifPresent(e -> System.out.printf("%X => %d\r\n", e.getKey(), e.getValue()));
}

prints (i.e.):

69C57829077 => 24

I thought that two calls in the same VM (even if in different threads) should return two different values.

In this case, a single value is returned by 24 (!!) invocations.

How can this happen?

P.S. I'm on Win10 x64

Michele Mariotti
  • 7,372
  • 5
  • 41
  • 73
  • 2
    [This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis()](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime()) – Jack Flamp Sep 14 '18 at 12:19
  • OK, I see. *This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time*. But this method cannot be used to measure elapsed time (since we don't know the resolution, we don't know if it would change between two measures). So, is this method useless? – Michele Mariotti Sep 14 '18 at 12:53
  • I don't know :) [Googling](https://www.google.com/search?q=java+is+nanotime+useless&oq=java+is+nanotime+useless&aqs=chrome..69i57j69i64.4110j0j4&sourceid=chrome&ie=UTF-8) doesn't help me. – Jack Flamp Sep 14 '18 at 13:58
  • Google always has the answer... the wrong one ;) – Michele Mariotti Sep 14 '18 at 16:25
  • It can be used to measure elapsed time, there's just a limit to the resolution of the measurement. (In particular, you probably can't use it to measure very small operations, but larger operations should be fine.) – Louis Wasserman Sep 15 '18 at 22:08

0 Answers0