--- old/hotspot/make/aix/makefiles/mapfile-vers-debug 2015-01-12 12:01:23.000000000 +0100 +++ new/hotspot/make/aix/makefiles/mapfile-vers-debug 2015-01-12 12:01:23.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,6 +132,7 @@ JVM_GetMethodIxSignatureUTF; JVM_GetMethodParameters; JVM_GetMethodTypeAnnotations; + JVM_GetNanoTimeAdjustment; JVM_GetPrimitiveArrayElement; JVM_GetProtectionDomain; JVM_GetStackAccessControlContext; --- old/hotspot/make/aix/makefiles/mapfile-vers-product 2015-01-12 12:01:23.000000000 +0100 +++ new/hotspot/make/aix/makefiles/mapfile-vers-product 2015-01-12 12:01:23.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -130,6 +130,7 @@ JVM_GetMethodIxNameUTF; JVM_GetMethodIxSignatureUTF; JVM_GetMethodParameters; + JVM_GetNanoTimeAdjustment; JVM_GetPrimitiveArrayElement; JVM_GetProtectionDomain; JVM_GetStackAccessControlContext; --- old/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug 2015-01-12 12:01:24.000000000 +0100 +++ new/hotspot/make/bsd/makefiles/mapfile-vers-darwin-debug 2015-01-12 12:01:24.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -130,6 +130,7 @@ _JVM_GetMethodIxSignatureUTF _JVM_GetMethodParameters _JVM_GetMethodTypeAnnotations + _JVM_GetNanoTimeAdjustment _JVM_GetPrimitiveArrayElement _JVM_GetProtectionDomain _JVM_GetStackAccessControlContext --- old/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product 2015-01-12 12:01:24.000000000 +0100 +++ new/hotspot/make/bsd/makefiles/mapfile-vers-darwin-product 2015-01-12 12:01:24.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -130,6 +130,7 @@ _JVM_GetMethodIxSignatureUTF _JVM_GetMethodParameters _JVM_GetMethodTypeAnnotations + _JVM_GetNanoTimeAdjustment _JVM_GetPrimitiveArrayElement _JVM_GetProtectionDomain _JVM_GetStackAccessControlContext --- old/hotspot/make/bsd/makefiles/mapfile-vers-debug 2015-01-12 12:01:25.000000000 +0100 +++ new/hotspot/make/bsd/makefiles/mapfile-vers-debug 2015-01-12 12:01:25.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,6 +132,7 @@ JVM_GetMethodIxSignatureUTF; JVM_GetMethodParameters; JVM_GetMethodTypeAnnotations; + JVM_GetNanoTimeAdjustment; JVM_GetPrimitiveArrayElement; JVM_GetProtectionDomain; JVM_GetStackAccessControlContext; --- old/hotspot/make/bsd/makefiles/mapfile-vers-product 2015-01-12 12:01:25.000000000 +0100 +++ new/hotspot/make/bsd/makefiles/mapfile-vers-product 2015-01-12 12:01:25.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,6 +132,7 @@ JVM_GetMethodIxSignatureUTF; JVM_GetMethodParameters; JVM_GetMethodTypeAnnotations; + JVM_GetNanoTimeAdjustment; JVM_GetPrimitiveArrayElement; JVM_GetProtectionDomain; JVM_GetStackAccessControlContext; --- old/hotspot/make/linux/makefiles/mapfile-vers-debug 2015-01-12 12:01:26.000000000 +0100 +++ new/hotspot/make/linux/makefiles/mapfile-vers-debug 2015-01-12 12:01:26.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,6 +132,7 @@ JVM_GetMethodIxSignatureUTF; JVM_GetMethodParameters; JVM_GetMethodTypeAnnotations; + JVM_GetNanoTimeAdjustment; JVM_GetPrimitiveArrayElement; JVM_GetProtectionDomain; JVM_GetStackAccessControlContext; --- old/hotspot/make/linux/makefiles/mapfile-vers-product 2015-01-12 12:01:26.000000000 +0100 +++ new/hotspot/make/linux/makefiles/mapfile-vers-product 2015-01-12 12:01:26.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,6 +132,7 @@ JVM_GetMethodIxSignatureUTF; JVM_GetMethodParameters; JVM_GetMethodTypeAnnotations; + JVM_GetNanoTimeAdjustment; JVM_GetPrimitiveArrayElement; JVM_GetProtectionDomain; JVM_GetStackAccessControlContext; --- old/hotspot/make/solaris/makefiles/mapfile-vers 2015-01-12 12:01:27.000000000 +0100 +++ new/hotspot/make/solaris/makefiles/mapfile-vers 2015-01-12 12:01:27.000000000 +0100 @@ -1,5 +1,5 @@ # -# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -132,6 +132,7 @@ JVM_GetMethodIxSignatureUTF; JVM_GetMethodParameters; JVM_GetMethodTypeAnnotations; + JVM_GetNanoTimeAdjustment; JVM_GetPrimitiveArrayElement; JVM_GetProtectionDomain; JVM_GetStackAccessControlContext; --- old/hotspot/src/os/aix/vm/os_aix.cpp 2015-01-12 12:01:27.000000000 +0100 +++ new/hotspot/src/os/aix/vm/os_aix.cpp 2015-01-12 12:01:27.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright 2012, 2014 SAP AG. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -1115,6 +1115,15 @@ return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); } +void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { + timeval time; + int status = gettimeofday(&time, NULL); + assert(status != -1, "aix error at gettimeofday()"); + seconds = jlong(time.tv_sec); + nanos = jlong(time.tv_usec) * 1000; +} + + // We need to manually declare mread_real_time, // because IBM didn't provide a prototype in time.h. // (they probably only ever tested in C, not C++) --- old/hotspot/src/os/bsd/vm/os_bsd.cpp 2015-01-12 12:01:28.000000000 +0100 +++ new/hotspot/src/os/bsd/vm/os_bsd.cpp 2015-01-12 12:01:28.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -984,6 +984,14 @@ return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); } +void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { + timeval time; + int status = gettimeofday(&time, NULL); + assert(status != -1, "bsd error"); + seconds = jlong(time.tv_sec); + nanos = jlong(time.tv_usec) * 1000; +} + #ifndef __APPLE__ #ifndef CLOCK_MONOTONIC #define CLOCK_MONOTONIC (1) --- old/hotspot/src/os/linux/vm/os_linux.cpp 2015-01-12 12:01:28.000000000 +0100 +++ new/hotspot/src/os/linux/vm/os_linux.cpp 2015-01-12 12:01:28.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1322,6 +1322,15 @@ return jlong(time.tv_sec) * 1000 + jlong(time.tv_usec / 1000); } +void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { + timeval time; + int status = gettimeofday(&time, NULL); + assert(status != -1, "linux error"); + seconds = jlong(time.tv_sec); + nanos = jlong(time.tv_usec) * 1000; +} + + #ifndef CLOCK_MONOTONIC #define CLOCK_MONOTONIC (1) #endif --- old/hotspot/src/os/solaris/vm/os_solaris.cpp 2015-01-12 12:01:29.000000000 +0100 +++ new/hotspot/src/os/solaris/vm/os_solaris.cpp 2015-01-12 12:01:29.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1475,6 +1475,16 @@ return jlong(t.tv_sec) * 1000 + jlong(t.tv_usec) / 1000; } +void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { + timeval t; + if (gettimeofday(&t, NULL) == -1) { + fatal(err_msg("os::javaTimeSystemUTC: gettimeofday (%s)", strerror(errno))); + } + seconds = jlong(t.tv_sec); + nanos = jlong(t.tv_usec) * 1000; +} + + jlong os::javaTimeNanos() { return (jlong)getTimeNanos(); } --- old/hotspot/src/os/windows/vm/os_windows.cpp 2015-01-12 12:01:29.000000000 +0100 +++ new/hotspot/src/os/windows/vm/os_windows.cpp 2015-01-12 12:01:29.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -839,6 +839,11 @@ return (a - offset()) / 10000; } +jlong windows_time_stamp(FILETIME wt) { + jlong a = jlong_from(wt.dwHighDateTime, wt.dwLowDateTime); + return (a - offset()); +} + FILETIME java_to_windows_time(jlong l) { jlong a = (l * 10000) + offset(); FILETIME result; @@ -874,6 +879,15 @@ } } +void os::javaTimeSystemUTC(jlong &seconds, jlong &nanos) { + FILETIME wt; + GetSystemTimeAsFileTime(&wt); + jlong ts = windows_time_stamp(wt); // 10th of micros + jlong secs = jlong(ts / 10000000); // 10000 * 1000 + seconds = secs; + nanos = jlong(ts - (secs*10000000)) * 100; +} + jlong os::javaTimeNanos() { if (!win32::_has_performance_count) { return javaTimeMillis() * NANOSECS_PER_MILLISEC; // the best we can do. --- old/hotspot/src/share/vm/prims/jvm.cpp 2015-01-12 12:01:30.000000000 +0100 +++ new/hotspot/src/share/vm/prims/jvm.cpp 2015-01-12 12:01:30.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -300,6 +300,48 @@ return os::javaTimeNanos(); JVM_END +// The function below is actually exposed by sun.misc.VM and not +// java.lang.System, but we choose to keep it here so that it stays next +// to JVM_CurrentTimeMillis and JVM_NanoTime + +const jlong MAX_DIFF_SECS = 0x0100000000; // 2^32 +const jlong MIN_DIFF_SECS = -MAX_DIFF_SECS; // -2^32 + +JVM_LEAF(jlong, JVM_GetNanoTimeAdjustment(JNIEnv *env, jclass ignored, jlong offset_secs)) + JVMWrapper("JVM_GetNanoTimeAdjustment"); + jlong seconds; + jlong nanos; + + os::javaTimeSystemUTC(seconds, nanos); + + // We're going to verify that the result can fit in a long. + // For that we need the difference in seconds between 'seconds' + // and 'offset_secs' to be such that: + // |seconds - offset_secs| < (2^63/10^9) + // We're going to approximate 10^9 ~< 2^30 (1000^3 ~< 1024^3) + // which makes |seconds - offset_secs| < 2^33 + // and we will prefer +/- 2^32 as the maximum acceptable diff + // as 2^32 has a more natural feel than 2^33... + // + // So if |seconds - offset_secs| >= 2^32 - we return a special + // sentinel value (-1) which the caller should take as an + // exception value indicating that the offset given to us is + // too far from range of the current time - leading to too big + // a nano adjustment. The caller is expected to recover by + // computing a more accurate offset and calling this method + // again. (For the record 2^32 secs is ~136 years, so that + // should rarely happen) + // + jlong diff = seconds - offset_secs; + if (diff >= MAX_DIFF_SECS || diff <= MIN_DIFF_SECS) { + return -1; // sentinel value: the offset is too far off the target + } + + // return the adjustment. If you compute a time by adding + // this number of nanoseconds along with the number of seconds + // in the offset you should get the current UTC time. + return (diff * (jlong)1000000000) + nanos; +JVM_END JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos, jobject dst, jint dst_pos, jint length)) --- old/hotspot/src/share/vm/prims/jvm.h 2015-01-12 12:01:31.000000000 +0100 +++ new/hotspot/src/share/vm/prims/jvm.h 2015-01-12 12:01:30.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -131,6 +131,9 @@ JNIEXPORT jlong JNICALL JVM_NanoTime(JNIEnv *env, jclass ignored); +JNIEXPORT jlong JNICALL +JVM_GetNanoTimeAdjustment(JNIEnv *env, jclass ignored, jlong offset_secs); + JNIEXPORT void JNICALL JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos, jobject dst, jint dst_pos, jint length); --- old/hotspot/src/share/vm/runtime/os.hpp 2015-01-12 12:01:31.000000000 +0100 +++ new/hotspot/src/share/vm/runtime/os.hpp 2015-01-12 12:01:31.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -172,10 +172,10 @@ static jlong javaTimeMillis(); static jlong javaTimeNanos(); static void javaTimeNanos_info(jvmtiTimerInfo *info_ptr); + static void javaTimeSystemUTC(jlong &seconds, jlong &nanos); static void run_periodic_checks(); static bool supports_monotonic_clock(); - // Returns the elapsed time in seconds since the vm started. static double elapsedTime(); --- old/jdk/src/java.base/share/classes/java/time/Clock.java 2015-01-12 12:01:32.000000000 +0100 +++ new/jdk/src/java.base/share/classes/java/time/Clock.java 2015-01-12 12:01:31.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -61,12 +61,15 @@ */ package java.time; +import java.io.IOException; +import java.io.ObjectInputStream; import static java.time.LocalTime.NANOS_PER_MINUTE; import static java.time.LocalTime.NANOS_PER_SECOND; import java.io.Serializable; import java.util.Objects; import java.util.TimeZone; +import sun.misc.VM; /** * A clock providing access to the current instant, date and time using a time-zone. @@ -446,10 +449,22 @@ */ static final class SystemClock extends Clock implements Serializable { private static final long serialVersionUID = 6740630888130243051L; + private static final long OFFSET_SEED = + System.currentTimeMillis()/1000 - 1024; // initial offest private final ZoneId zone; + // We don't actually need a volatile here. + // We don't care if offset is set or read concurrently by multiple + // threads - we just need a value which is 'recent enough' - in other + // words something that has been updated at least once in the last + // 2^32 secs (~136 years). And even if we by chance see an invalid + // offset, the worst that can happen is that we will get a -1 value + // from getNanoTimeAdjustment, forcing us to update the offset + // once again. + private transient long offset; SystemClock(ZoneId zone) { this.zone = zone; + this.offset = OFFSET_SEED; } @Override public ZoneId getZone() { @@ -464,11 +479,50 @@ } @Override public long millis() { + // System.currentTimeMillis() and VM.getNanoTimeAdjustment(offset) + // use the same time source - System.currentTimeMillis() simply + // limits the resolution to milliseconds. + // So we take the faster path and call System.currentTimeMillis() + // directly - in order to avoid the performance penalty of + // VM.getNanoTimeAdjustment(offset) which is less efficient. return System.currentTimeMillis(); } @Override public Instant instant() { - return Instant.ofEpochMilli(millis()); + // Take a local copy of offset. offset can be updated concurrently + // by other threads (even if we haven't made it volatile) so we will + // work with a local copy. + long localOffset = offset; + long adjustment = VM.getNanoTimeAdjustment(localOffset); + + if (adjustment == -1) { + // -1 is a sentinel value returned by VM.getNanoTimeAdjustment + // when the offset it is given is too far off the current UTC + // time. In principle, this should not happen unless the + // JVM has run for more than ~136 years (not likely) or + // someone is fiddling with the system time, or the offset is + // by chance at 1ns in the future (very unlikely). + // We can easily recover from all these conditions by bringing + // back the offset in range and retry. + + // bring back the offset in range. We use -1024 to make + // it more unlikely to hit the 1ns in the future condition. + localOffset = System.currentTimeMillis()/1000 - 1024; + + // retry + adjustment = VM.getNanoTimeAdjustment(localOffset); + + if (adjustment == -1) { + // Should not happen: we just recomputed a new offset. + // It should have fixed the issue. + throw new InternalError("Offset " + localOffset + " is not in range"); + } else { + // OK - recovery succeeded. Update the offset for the + // next call... + offset = localOffset; + } + } + return Instant.ofEpochSecond(localOffset, adjustment); } @Override public boolean equals(Object obj) { @@ -485,6 +539,12 @@ public String toString() { return "SystemClock[" + zone + "]"; } + private void readObject(ObjectInputStream is) + throws IOException, ClassNotFoundException { + // ensure that offset is initialized + is.defaultReadObject(); + offset = OFFSET_SEED; + } } //----------------------------------------------------------------------- --- old/jdk/src/java.base/share/classes/java/util/Formatter.java 2015-01-12 12:01:32.000000000 +0100 +++ new/jdk/src/java.base/share/classes/java/util/Formatter.java 2015-01-12 12:01:32.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,7 @@ import java.time.temporal.ChronoField; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalQueries; +import java.time.temporal.UnsupportedTemporalTypeException; import sun.misc.DoubleConsts; import sun.misc.FormattedFloatingDecimal; @@ -4056,7 +4057,12 @@ break; } case DateTime.NANOSECOND: { // 'N' (000000000 - 999999999) - int i = t.get(ChronoField.MILLI_OF_SECOND) * 1000000; + int i; + try { + i = t.get(ChronoField.NANO_OF_SECOND); + } catch (UnsupportedTemporalTypeException u) { + i = t.get(ChronoField.MILLI_OF_SECOND) * 1000000; + } Flags flags = Flags.ZERO_PAD; sb.append(localizedMagnitude(null, i, flags, 9, l)); break; --- old/jdk/src/java.base/share/classes/sun/misc/VM.java 2015-01-12 12:01:33.000000000 +0100 +++ new/jdk/src/java.base/share/classes/sun/misc/VM.java 2015-01-12 12:01:33.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -402,6 +402,36 @@ */ public static native long getegid(); + /** + * Get a nanosecond time stamp adjustment in the form of a single long. + * + * This value can be used to create an instant using + * {@link java.time.Instant#ofEpochSecond(long, long) + * java.time.Instant.ofEpochSecond(offsetInSeconds, + * getNanoTimeAdjustment(offsetInSeconds))}. + *

+ * The value returned has the best resolution available to the JVM on + * the current system. + * This is usually down to microseconds - or tenth of microseconds - + * depending on the OS/Hardware and the JVM implementation. + * + * @param offsetInSeconds The offset in seconds from which the nanosecond + * time stamp should be computed. + * + * @apiNote The offset should be recent enough - so that + * {@code offsetInSeconds} is within {@code +/- 2^32} seconds of the + * current UTC time. If the offset is too far off, {@code -1} will be + * returned. As such, {@code -1} must not be considered as a valid + * nano time adjustment, but as an exception value indicating + * that an offset closer to the current time should be used. + * + * @return A nanosecond time stamp adjustment in the form of a single long. + * If the offset is too far off the current time, this method returns -1. + * In that case, the caller should call this method again, passing a + * more accurate offset. + */ + public static native long getNanoTimeAdjustment(long offsetInSeconds); + static { initialize(); } --- old/jdk/src/java.base/share/native/include/jvm.h 2015-01-12 12:01:34.000000000 +0100 +++ new/jdk/src/java.base/share/native/include/jvm.h 2015-01-12 12:01:34.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,6 +104,9 @@ JNIEXPORT jlong JNICALL JVM_NanoTime(JNIEnv *env, jclass ignored); +JNIEXPORT jlong JNICALL +JVM_GetNanoTimeAdjustment(JNIEnv *env, jclass ignored, jlong offset_secs); + JNIEXPORT void JNICALL JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos, jobject dst, jint dst_pos, jint length); --- old/jdk/src/java.base/share/native/libjava/VM.c 2015-01-12 12:01:34.000000000 +0100 +++ new/jdk/src/java.base/share/native/libjava/VM.c 2015-01-12 12:01:34.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,6 +33,11 @@ #include "sun_misc_VM.h" +/* Only register the performance-critical methods */ +static JNINativeMethod methods[] = { + {"getNanoTimeAdjustment", "(J)J", (void *)&JVM_GetNanoTimeAdjustment} +}; + JNIEXPORT jobject JNICALL Java_sun_misc_VM_latestUserDefinedLoader(JNIEnv *env, jclass cls) { return JVM_LatestUserDefinedLoader(env); @@ -49,6 +54,14 @@ return; } + // Registers implementations of native methods described in methods[] + // above. + // In particular, registers JVM_GetNanoTimeAdjustment as the implementation + // of the native sun.misc.VM.getNanoTimeAdjustment - avoiding the cost of + // introducing a Java_sun_misc_VM_getNanoTimeAdjustment wrapper + (*env)->RegisterNatives(env, cls, + methods, sizeof(methods)/sizeof(methods[0])); + func_p = (GetJvmVersionInfo_fp) JDK_FindJvmEntry("JVM_GetVersionInfo"); if (func_p != NULL) { jvm_version_info info; --- old/jdk/test/java/time/tck/java/time/TCKLocalDateTime.java 2015-01-12 12:01:35.000000000 +0100 +++ new/jdk/test/java/time/tck/java/time/TCKLocalDateTime.java 2015-01-12 12:01:35.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -292,7 +292,8 @@ expected = LocalDateTime.now(Clock.system(zone)); test = LocalDateTime.now(zone); } - assertEquals(test, expected); + assertEquals(test.truncatedTo(ChronoUnit.SECONDS), + expected.truncatedTo(ChronoUnit.SECONDS)); } //----------------------------------------------------------------------- --- old/jdk/test/java/time/tck/java/time/TCKLocalTime.java 2015-01-12 12:01:36.000000000 +0100 +++ new/jdk/test/java/time/tck/java/time/TCKLocalTime.java 2015-01-12 12:01:36.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -246,7 +246,8 @@ expected = LocalTime.now(Clock.system(zone)); test = LocalTime.now(zone); } - assertEquals(test, expected); + assertEquals(test.truncatedTo(ChronoUnit.SECONDS), + expected.truncatedTo(ChronoUnit.SECONDS)); } //----------------------------------------------------------------------- --- old/jdk/test/java/time/tck/java/time/TCKZonedDateTime.java 2015-01-12 12:01:37.000000000 +0100 +++ new/jdk/test/java/time/tck/java/time/TCKZonedDateTime.java 2015-01-12 12:01:36.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -260,7 +260,8 @@ expected = ZonedDateTime.now(Clock.system(zone)); test = ZonedDateTime.now(zone); } - assertEquals(test, expected); + assertEquals(test.truncatedTo(ChronoUnit.SECONDS), + expected.truncatedTo(ChronoUnit.SECONDS)); } //----------------------------------------------------------------------- --- old/jdk/test/java/time/test/java/time/TestClock_System.java 2015-01-12 12:01:37.000000000 +0100 +++ new/jdk/test/java/time/test/java/time/TestClock_System.java 2015-01-12 12:01:37.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -62,7 +62,9 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertSame; +import java.lang.reflect.Field; import java.time.Clock; +import java.time.Instant; import java.time.ZoneId; import org.testng.annotations.Test; @@ -87,4 +89,298 @@ assertEquals(test.toString(), "SystemClock[Europe/Paris]"); } + //----------------------------------------------------------------------- + + private static String formatTime(String prefix, Instant time) { + return prefix + ": " + time + " - seconds: " + + time.getEpochSecond() + ", nanos: " + + time.getNano(); + } + + public void test_ClockResolution() { + Clock highestUTC = Clock.systemUTC(); + + Instant start = Instant.ofEpochMilli(System.currentTimeMillis()); + + try { + // smoke test + Instant system1 = Instant.ofEpochMilli(System.currentTimeMillis()); + Instant system2 = Instant.ofEpochMilli(System.currentTimeMillis()); + Instant highest1 = highestUTC.instant(); + Instant highest2 = highestUTC.instant(); + System.out.println(formatTime("\nsystemUTC #1 ", system1)); + System.out.println(formatTime("systemUTC #2 ", system2)); + System.out.println(formatTime("highestResolutionUTC #1 ", highest1)); + System.out.println(formatTime("highestResolutionUTC #2 ", highest2)); + + if (system2.isBefore(system1)) { + System.err.println("system2 is before system1!"); + System.err.println(formatTime("\n\tsystem1", system1)); + System.err.println(formatTime("\n\tsystem2", system2)); + throw new RuntimeException("system2 is before system1!" + + formatTime("\n\tsystem1", system1) + + formatTime("\n\tsystem2", system2)); + } + if (highest2.isBefore(highest1)) { + System.err.println("highest2 is before highest1!"); + System.err.println(formatTime("\n\thighest1", system1)); + System.err.println(formatTime("\n\tsystem2", highest2)); + throw new RuntimeException("highest2 is before system1!" + + formatTime("\n\thighest1", system1) + + formatTime("\n\tsystem2", highest2)); + } + + // better test - but depends on implementation details. + // we're not rounding - so highest1 should be greater or equal to + // system1 + system1 = Instant.ofEpochMilli(System.currentTimeMillis()); + highest1 = highestUTC.instant(); + + System.out.println(formatTime("\nsystemUTC ", system1)); + System.out.println(formatTime("highestResolutionUTC ", highest1)); + + if (highest1.isBefore(system1)) { + System.err.println("highest1 is before system1!"); + System.err.println(formatTime("\n\tsystem1", system1)); + System.err.println(formatTime("\n\thighest1", highest1)); + throw new RuntimeException("highest1 is before system1!" + + formatTime("\n\tsystem1", system1) + + formatTime("\n\thighest1", highest1)); + } + + int count=0; + // let's preheat the system a bit: + for (int i = 0; i < 1000 ; i++) { + system1 = Instant.ofEpochMilli(System.currentTimeMillis()); + highest1 = highestUTC.instant(); + final int sysnan = system1.getNano(); + final int nanos = highest1.getNano(); + if ((nanos % 1000000) > 0) { + count++; // we have micro seconds + } + if ((sysnan % 1000000) > 0) { + throw new RuntimeException("Expected only millisecconds " + + "precision for systemUTC, found " + + (sysnan % 1000000) + " remainder."); + } + } + System.out.println("\nNumber of time stamps which had better than" + + " millisecond precision: "+count+"/"+1000); + System.out.println(formatTime("\nsystemUTC ", system1)); + System.out.println(formatTime("highestResolutionUTC ", highest1)); + if (count == 0) { + System.err.println("Something is strange: no microsecond " + + "precision with highestResolutionUTC?"); + throw new RuntimeException("Micro second preccision not reached"); + } + + // check again + if (highest1.isBefore(system1)) { + System.err.println("highest1 is before system1!"); + System.err.println(formatTime("\n\tsystem1", system1)); + System.err.println(formatTime("\n\thighest1", highest1)); + throw new RuntimeException("highest1 is before system1!" + + formatTime("\n\tsystem1", system1) + + formatTime("\n\thighest1", highest1)); + } + + // leap of faith: ensure that highest1 is from within 10 secs of + // system1 + if (highest1.toEpochMilli() != system1.toEpochMilli()) { + long delta = highest1.getEpochSecond() - system1.getEpochSecond(); + if (delta > 10) { + throw new RuntimeException("Unexpected long delay between two clocks (" + + delta + " seconds)" + + formatTime("\n\t system1", system1) + + formatTime("\n\t highest1", highest1)); + + } + } else { + System.out.println("You won the lottery: the two dates are within 1 millisecond!\n"); + } + + } finally { + Instant stop = Instant.ofEpochMilli(System.currentTimeMillis()); + if (start.isAfter(stop)) { + // This should not happen - but can (un)probably be observed + // when switching to summer time, or if another application + // is switching the system date... + System.err.println("Cannot test - date was setback: " + + formatTime("\n\tstarted at", start) + + formatTime("\n\tstopped at", stop) + "\n"); + return; // will prevent exceptions from being propagated. + } + } + } + + static final long MAX_OFFSET = 0x0100000000L; + static final long MIN_OFFSET = -MAX_OFFSET; + + // A helper class to test that SystemClock correctly recomputes + // its offset. + static class SystemClockOffset { + + static final int MILLIS_IN_SECOND = 1000; + static final int NANOS_IN_MILLI = 1000_000; + static final int NANOS_IN_MICRO = 1000; + static final int NANOS_IN_SECOND = 1000_000_000; + + static final boolean verbose = true; + static final Clock systemUTC = Clock.systemUTC(); + static final Field offsetField; + + static { + try { + offsetField = Class.forName("java.time.Clock$SystemClock").getDeclaredField("offset"); + offsetField.setAccessible(true); + } catch (ClassNotFoundException | NoSuchFieldException ex) { + throw new ExceptionInInitializerError(ex); + } + } + + static enum Answer { + + YES, // isOffLimit = YES: we must get -1 + NO, // isOffLimit = NO: we must not not get -1 + MAYBE // isOffLimit = MAYBE: we might get -1 or a valid adjustment. + }; + + static long distance(long one, long two) { + return one > two ? Math.subtractExact(one, two) + : Math.subtractExact(two, one); + } + + static Answer isOffLimits(long before, long after, long offset) { + long relativeDistanceBefore = distance(before, offset); + long relativeDistanceAfter = distance(after, offset); + if (relativeDistanceBefore >= MAX_OFFSET && relativeDistanceAfter >= MAX_OFFSET) { + return Answer.YES; + } + if (relativeDistanceBefore < MAX_OFFSET && relativeDistanceAfter < MAX_OFFSET) { + if (relativeDistanceBefore == 0 || relativeDistanceAfter == 0) { + return Answer.MAYBE; // unlucky case where + } + return Answer.NO; + } + return Answer.MAYBE; + } + + static void testWithOffset(String name, long offset) + throws IllegalAccessException { + testWithOffset(name, offset, systemUTC); + } + + static void testWithOffset(String name, long offset, Clock clock) + throws IllegalAccessException { + offsetField.set(clock, offset); + long beforeMillis = System.currentTimeMillis(); + final Instant instant = clock.instant(); + long afterMillis = System.currentTimeMillis(); + long actualOffset = offsetField.getLong(clock); + long instantMillis = instant.getEpochSecond() * MILLIS_IN_SECOND + + instant.getNano() / NANOS_IN_MILLI; + if (instantMillis < beforeMillis || instantMillis > afterMillis) { + throw new RuntimeException(name + + ": Invalid instant: " + instant + + " (~" + instantMillis + "ms)" + + " when time in millis is in [" + + beforeMillis + ", " + afterMillis + + "] and offset in seconds is " + offset); + } + Answer isOffLimits = isOffLimits(beforeMillis / MILLIS_IN_SECOND, + afterMillis / MILLIS_IN_SECOND, offset); + switch (isOffLimits) { + case YES: + if (actualOffset == offset) { + throw new RuntimeException(name + + ": offset was offlimit but was not recomputed " + + " when time in millis is in [" + + beforeMillis + ", " + afterMillis + + "] and offset in seconds was " + offset); + } + break; + case NO: + if (actualOffset != offset) { + throw new RuntimeException(name + + ": offset was not offlimit but was recomputed."); + } + break; + default: + break; + } + if (distance(actualOffset, instant.getEpochSecond()) >= MAX_OFFSET) { + throw new RuntimeException(name + ": Actual offset is too far off:" + + " offset=" + actualOffset + + "instant.seconds=" + instant.getEpochSecond()); + } + long adjustment = (instant.getEpochSecond() - actualOffset) * NANOS_IN_SECOND + + instant.getNano(); + validateAdjustment(name, actualOffset, beforeMillis, afterMillis, adjustment); + } + + static void validateAdjustment(String name, long offset, long beforeMillis, + long afterMillis, long adjustment) { + System.out.println("Validating adjustment: " + adjustment); + long expectedMax = distance(offset, beforeMillis / MILLIS_IN_SECOND) + * NANOS_IN_SECOND + + (beforeMillis % MILLIS_IN_SECOND) * NANOS_IN_MILLI + + (afterMillis - beforeMillis + 1) * NANOS_IN_MILLI; + long absoluteAdjustment = distance(0, adjustment); + if (absoluteAdjustment > expectedMax) { + long adjSec = absoluteAdjustment / NANOS_IN_SECOND; + long adjMil = (absoluteAdjustment % NANOS_IN_SECOND) / NANOS_IN_MILLI; + long adjMic = (absoluteAdjustment % NANOS_IN_MILLI) / NANOS_IN_MICRO; + long adjNan = (absoluteAdjustment % NANOS_IN_MICRO); + long expSec = expectedMax / NANOS_IN_SECOND; + long expMil = (expectedMax % NANOS_IN_SECOND) / NANOS_IN_MILLI; + long expMic = (expectedMax % NANOS_IN_MILLI) / NANOS_IN_MICRO; + long expNan = (expectedMax % NANOS_IN_MICRO); + System.err.println("Excessive adjustment: " + adjSec + "s, " + + adjMil + "ms, " + adjMic + "mics, " + adjNan + "ns"); + System.err.println("Epected max: " + expSec + "s, " + + expMil + "ms, " + expMic + "mics, " + expNan + "ns"); + + throw new RuntimeException(name + + ": Excessive adjustment: " + adjustment + + " when time in millis is in [" + + beforeMillis + ", " + afterMillis + + "] and offset in seconds is " + offset); + } + } + } + + public void test_OffsetRegular() throws IllegalAccessException { + System.out.println("*** Testing regular cases ***"); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000", + System.currentTimeMillis()/1000); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 - 1024", + System.currentTimeMillis()/1000 - 1024); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 + 1024", + System.currentTimeMillis()/1000 + 1024); + } + + public void test_OffsetLimits() throws IllegalAccessException { + System.out.println("*** Testing limits ***"); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 - MAX_OFFSET + 1", + System.currentTimeMillis()/1000 - MAX_OFFSET + 1); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 + MAX_OFFSET - 1", + System.currentTimeMillis()/1000 + MAX_OFFSET - 1); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 - MAX_OFFSET", + System.currentTimeMillis()/1000 - MAX_OFFSET); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 + MAX_OFFSET", + System.currentTimeMillis()/1000 + MAX_OFFSET); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 - MAX_OFFSET - 1024", + System.currentTimeMillis()/1000 - MAX_OFFSET - 1024); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 + MAX_OFFSET + 1024", + System.currentTimeMillis()/1000 + MAX_OFFSET + 1024); + SystemClockOffset.testWithOffset("0", 0); + SystemClockOffset.testWithOffset("-1", -1); + SystemClockOffset.testWithOffset("Integer.MAX_VALUE + System.currentTimeMillis()/1000", + ((long)Integer.MAX_VALUE) + System.currentTimeMillis()/1000); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 - Integer.MIN_VALUE", + System.currentTimeMillis()/1000 - Integer.MIN_VALUE); + SystemClockOffset.testWithOffset("Long.MAX_VALUE", Long.MAX_VALUE); + SystemClockOffset.testWithOffset("System.currentTimeMillis()/1000 - Long.MIN_VALUE", + (Long.MIN_VALUE + System.currentTimeMillis()/1000)*-1); + } } --- old/jdk/test/java/time/test/java/util/TestFormatter.java 2015-01-12 12:01:38.000000000 +0100 +++ new/jdk/test/java/time/test/java/util/TestFormatter.java 2015-01-12 12:01:38.000000000 +0100 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -38,6 +38,7 @@ import java.time.temporal.ChronoField; import java.time.temporal.TemporalQueries; import java.time.temporal.TemporalAccessor; +import java.time.temporal.UnsupportedTemporalTypeException; import java.util.*; @@ -153,6 +154,44 @@ if (verbose) { System.out.printf("%-24s : %s%n", getClassName(dt), out); } + + // expected usually comes from Calendar which only has milliseconds + // precision. So we're going to replace it's N:[nanos] stamp with + // the correct value for nanos. + if ((dt instanceof TemporalAccessor) && expected != null) { + try { + // Get millis & nanos from the dt + final TemporalAccessor ta = (TemporalAccessor) dt; + final int nanos = ta.get(ChronoField.NANO_OF_SECOND); + final int millis = ta.get(ChronoField.MILLI_OF_SECOND); + final String nanstr = String.valueOf(nanos); + final String mistr = String.valueOf(millis); + + // Compute the value of the N:[nanos] field that we expect + // to find in 'out' + final StringBuilder sb = new StringBuilder(); + sb.append("N:["); + for (int i=nanstr.length(); i<9; i++) { + sb.append('0'); + } + sb.append(nanos).append("]"); + + // Compute the truncated value of N:[nanos] field that might + // be in 'expected' when expected was built from Calendar. + final StringBuilder sbm = new StringBuilder(); + sbm.append("N:["); + for (int i=mistr.length(); i<3; i++) { + sbm.append('0'); + } + sbm.append(mistr).append("000000]"); + + // if expected contains the truncated value, replace it with + // the complete value. + expected = expected.replace(sbm.toString(), sb.toString()); + } catch (UnsupportedTemporalTypeException e) { + // nano seconds unsupported - nothing to do... + } + } if (expected != null && !out.equals(expected)) { System.out.printf("%-24s actual: %s%n FAILED; expected: %s%n", getClassName(dt), out, expected); --- /dev/null 2015-01-12 12:01:39.000000000 +0100 +++ new/jdk/test/sun/misc/VM/GetNanoTimeAdjustment.java 2015-01-12 12:01:39.000000000 +0100 @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.util.Objects; +import sun.misc.VM; + +/** + * @test + * @bug 8068730 + * @summary tests that VM.getgetNanoTimeAdjustment() works as expected. + * @run main GetNanoTimeAdjustment + * @author danielfuchs + */ +public class GetNanoTimeAdjustment { + + static final int MILLIS_IN_SECOND = 1000; + static final int NANOS_IN_MILLI = 1000_000; + static final int NANOS_IN_MICRO = 1000; + static final int NANOS_IN_SECOND = 1000_000_000; + + static final boolean verbose = true; + + static final class TestAssertException extends RuntimeException { + TestAssertException(String msg) { super(msg); } + } + + private static void assertEquals(long expected, long received, String msg) { + if (expected != received) { + throw new TestAssertException("Unexpected result for " + msg + + ".\n\texpected: " + expected + + "\n\tactual: " + received); + } else if (verbose) { + System.out.println("Got expected " + msg + ": " + received); + } + } + + private static void assertEquals(Object expected, Object received, String msg) { + if (!Objects.equals(expected, received)) { + throw new TestAssertException("Unexpected result for " + msg + + ".\n\texpected: " + expected + + "\n\tactual: " + received); + } else if (verbose) { + System.out.println("Got expected " + msg + ": " + received); + } + } + + static final long MAX_OFFSET = 0x0100000000L; + static final long MIN_OFFSET = -MAX_OFFSET; + static enum Answer { + YES, // isOffLimit = YES: we must get -1 + NO, // isOffLimit = NO: we must not not get -1 + MAYBE // isOffLimit = MAYBE: we might get -1 or a valid adjustment. + }; + static long distance(long one, long two) { + return one > two ? Math.subtractExact(one, two) + : Math.subtractExact(two, one); + } + + + static Answer isOffLimits(long before, long after, long offset) { + long relativeDistanceBefore = distance(before, offset); + long relativeDistanceAfter = distance(after, offset); + if (relativeDistanceBefore >= MAX_OFFSET && relativeDistanceAfter >= MAX_OFFSET) { + return Answer.YES; + } + if (relativeDistanceBefore < MAX_OFFSET && relativeDistanceAfter < MAX_OFFSET) { + if (relativeDistanceBefore == 0 || relativeDistanceAfter == 0) { + return Answer.MAYBE; // unlucky case where + } + return Answer.NO; + } + return Answer.MAYBE; + } + + static void testWithOffset(String name, long offset) { + System.out.println("Testing with offset: " + name); + long beforeMillis = System.currentTimeMillis(); + long adjustment = VM.getNanoTimeAdjustment(offset); + long afterMillis = System.currentTimeMillis(); + + if (offset >= beforeMillis/MILLIS_IN_SECOND + && offset <= afterMillis/MILLIS_IN_SECOND) { + if (adjustment == -1) { + // it's possible that we have fallen in the unlucky case + // where -1 was the genuine result. let's go backward a bit. + offset = offset - 10; + beforeMillis = System.currentTimeMillis(); + adjustment = VM.getNanoTimeAdjustment(offset); + afterMillis = System.currentTimeMillis(); + if (adjustment == -1) { + throw new RuntimeException(name + ": VM says " + offset + + " secs is too far off, " + + " when time in seconds is in [" + + beforeMillis/MILLIS_IN_SECOND + ", " + + afterMillis/MILLIS_IN_SECOND + + "]"); + } + } + } + + Answer isOffLimit = isOffLimits(beforeMillis/MILLIS_IN_SECOND, + afterMillis/MILLIS_IN_SECOND, offset); + switch (isOffLimit) { + case YES: + if (adjustment != -1) { + throw new RuntimeException(name + + ": VM should have returned -1 for " + + offset + + " when time in seconds is in [" + + beforeMillis/MILLIS_IN_SECOND + ", " + + afterMillis/MILLIS_IN_SECOND + "]"); + } + System.out.println("Got expected exception value: " + adjustment); + break; + case NO: + if (adjustment == -1) { + throw new RuntimeException(name + + "VM says " + offset + + " secs is too far off, " + + " when time in seconds is in [" + + beforeMillis/MILLIS_IN_SECOND + ", " + + afterMillis/MILLIS_IN_SECOND + + "]"); + } + break; + case MAYBE: + System.out.println("Adjustment: " + adjustment); + System.out.println("Can't assert for -1 with offset " + + offset + "(" + name + ")" + + " when time in seconds is in [" + + beforeMillis/MILLIS_IN_SECOND + ", " + + afterMillis/MILLIS_IN_SECOND + + "]"); + // not conclusive + } + + if (isOffLimit == Answer.NO || adjustment != -1) { + System.out.println("Validating adjustment: " + adjustment); + long expectedMax = distance(offset, beforeMillis/MILLIS_IN_SECOND) + * NANOS_IN_SECOND + + (beforeMillis % MILLIS_IN_SECOND) * NANOS_IN_MILLI + + (afterMillis - beforeMillis + 1) * NANOS_IN_MILLI; + long absoluteAdjustment = distance(0, adjustment); + if (absoluteAdjustment > expectedMax) { + long adjSec = absoluteAdjustment / NANOS_IN_SECOND; + long adjMil = (absoluteAdjustment % NANOS_IN_SECOND) / NANOS_IN_MILLI; + long adjMic = (absoluteAdjustment % NANOS_IN_MILLI) / NANOS_IN_MICRO; + long adjNan = (absoluteAdjustment % NANOS_IN_MICRO); + long expSec = expectedMax / NANOS_IN_SECOND; + long expMil = (expectedMax % NANOS_IN_SECOND) / NANOS_IN_MILLI; + long expMic = (expectedMax % NANOS_IN_MILLI) / NANOS_IN_MICRO; + long expNan = (expectedMax % NANOS_IN_MICRO); + System.err.println("Excessive adjustment: " + adjSec + "s, " + + adjMil + "ms, " + adjMic + "mics, " + adjNan + "ns"); + System.err.println("Epected max: " + expSec + "s, " + + expMil + "ms, " + expMic + "mics, " + expNan + "ns"); + + throw new RuntimeException(name + + ": Excessive adjustment: " + adjustment + + " when time in millis is in [" + + beforeMillis + ", " + afterMillis + + "] and offset in seconds is " + offset); + } + } + + } + + static void regular() { + System.out.println("*** Testing regular cases ***"); + final long start = System.currentTimeMillis(); + long offset = start/1000; + long adjustment = VM.getNanoTimeAdjustment(offset); + if (start != offset*1000) { + if (adjustment == -1) { + throw new RuntimeException("VM says " + offset + + " secs is too far off, but time millis is " + + System.currentTimeMillis()); + } + } + if (adjustment == -1) { + offset = System.currentTimeMillis()/1000 - 1024; + adjustment = VM.getNanoTimeAdjustment(offset); + if (adjustment == -1) { + throw new RuntimeException("VM says " + offset + + " secs is too far off, but time millis is " + + System.currentTimeMillis()); + } + } + if (adjustment > (start/1000 - offset + 20)*NANOS_IN_SECOND) { + throw new RuntimeException("Excessive adjustment: " + adjustment); + } + testWithOffset("System.currentTimeMillis()/1000", + System.currentTimeMillis()/1000); + testWithOffset("System.currentTimeMillis()/1000 - 1024", + System.currentTimeMillis()/1000 - 1024); + testWithOffset("System.currentTimeMillis()/1000 + 1024", + System.currentTimeMillis()/1000 + 1024); + } + + static void testLimits() { + System.out.println("*** Testing limits ***"); + testWithOffset("System.currentTimeMillis()/1000 - MAX_OFFSET + 1", + System.currentTimeMillis()/1000 - MAX_OFFSET + 1); + testWithOffset("System.currentTimeMillis()/1000 + MAX_OFFSET - 1", + System.currentTimeMillis()/1000 + MAX_OFFSET - 1); + testWithOffset("System.currentTimeMillis()/1000 - MAX_OFFSET", + System.currentTimeMillis()/1000 - MAX_OFFSET); + testWithOffset("System.currentTimeMillis()/1000 + MAX_OFFSET", + System.currentTimeMillis()/1000 + MAX_OFFSET); + testWithOffset("System.currentTimeMillis()/1000 - MAX_OFFSET - 1024", + System.currentTimeMillis()/1000 - MAX_OFFSET - 1024); + testWithOffset("System.currentTimeMillis()/1000 + MAX_OFFSET + 1024", + System.currentTimeMillis()/1000 + MAX_OFFSET + 1024); + testWithOffset("0", 0); + testWithOffset("-1", -1); + testWithOffset("Integer.MAX_VALUE + System.currentTimeMillis()/1000", + ((long)Integer.MAX_VALUE) + System.currentTimeMillis()/1000); + testWithOffset("System.currentTimeMillis()/1000 - Integer.MIN_VALUE", + System.currentTimeMillis()/1000 - Integer.MIN_VALUE); + testWithOffset("Long.MAX_VALUE", Long.MAX_VALUE); + testWithOffset("System.currentTimeMillis()/1000 - Long.MIN_VALUE", + (Long.MIN_VALUE + System.currentTimeMillis()/1000)*-1); + } + + public static void main(String[] args) throws Exception { + regular(); + testLimits(); + } + +}