Created
September 29, 2018 10:19
-
-
Save RChehowski/feba531e082d2df6721598177f2e5ddb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vizor.unreal.util.util; | |
import java.time.ZonedDateTime; | |
public class GarbageFreeClock | |
{ | |
private static final int msInSec = 1000; | |
private static final int msInMin = msInSec * 60; | |
private static final int msInHou = msInMin * 60; | |
private static final int msInDay = msInHou * 24; | |
private static final int patternLength = "HH:MM:SS:ZZZ".length(); | |
private static final int msZoneOffset = ZonedDateTime.now().getOffset().getTotalSeconds() * msInSec; | |
private static final long bulkBufferSize = 100; | |
private static final char[] bulkBuffer = new char[(int)(patternLength * bulkBufferSize)]; | |
private static String concatenate(long threadId, int h, int m, int s, int z) | |
{ | |
final char buf[]; | |
final int initOffset; | |
// fail-safe, but true sharing is possible | |
if (threadId < bulkBufferSize) | |
{ | |
buf = bulkBuffer; | |
initOffset = (int)threadId; | |
} | |
else | |
{ | |
buf = new char[patternLength]; | |
initOffset = 0; | |
} | |
int offset = initOffset; | |
// hour | |
buf[offset++] = (char)('0' + h / 10); | |
buf[offset++] = (char)('0' + h % 10); | |
buf[offset++] = ':'; | |
// min | |
buf[offset++] = (char)('0' + m / 10); | |
buf[offset++] = (char)('0' + m % 10); | |
buf[offset++] = ':'; | |
// sec | |
buf[offset++] = (char)('0' + s / 10); | |
buf[offset++] = (char)('0' + s % 10); | |
buf[offset++] = ':'; | |
// ms | |
buf[offset++] = (char)('0' + z / 100); | |
buf[offset++] = (char)('0' + ((z / 10) % 10)); | |
buf[offset ] = (char)('0' + z % 10); | |
return new String(buf, initOffset, patternLength); | |
} | |
private static String computeTime(final int rawMilliseconds) | |
{ | |
int z = rawMilliseconds; | |
// Disintegrate into parts | |
final int h = z / msInHou; | |
z -= (h * msInHou); | |
final int m = z / msInMin; | |
z -= (m * msInMin); | |
final int s = z / msInSec; | |
z -= (s * msInSec); | |
return concatenate(Thread.currentThread().getId(), h, m, s, z); | |
} | |
public static String currentUtcTime() | |
{ | |
final long currentTimeMillis = System.currentTimeMillis(); | |
return computeTime((int)(currentTimeMillis % msInDay)); | |
} | |
public static String currentLocalTime() | |
{ | |
final long currentTimeMillis = System.currentTimeMillis(); | |
return computeTime((int)((currentTimeMillis + msZoneOffset) % msInDay)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment