Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.tectonica.util;
 
 
 public class NewId
 {
 	private static Random rand = new Random();

returns a so-called Time-UUID, i.e. a UUID that guarantees no conflicts at the following probabilities:
  • 99.9999973% (or 1 - 2.7e-8) if called 1,000,000 times in every millisecond
  • value of (1 - 2.7e-14) if called once in every microsecond
  • either way, UUIDs within different milliseconds have 0% probability of conflicting
The resulting UUID when used in sort retains order of creation
	public static String generate()
	{
		String timePart = Long.toHexString(System.currentTimeMillis());
		// all dates between 2004 and and 2527 are taking up 11 hex digits, so the following is unnecessary
//		timePart = leftPadded(timePart, 11, '0');
		String randomPart = leftPadded(Long.toHexString(.nextLong()), 16, '0');
		return timePart + randomPart;
	}
	private static String leftPadded(String strint targetLengthchar padChar)
	{
		int padsCount = targetLength - str.length();
		if (padsCount <= 0)
			return str// returns original String if longer than target length
		final char[] pad = new char[padsCount];
		for (int i = 0; i < pad.lengthi++)
			pad[i] = padChar;
		return (new String(pad)).concat(str);
	}

convenience method for adding prefix to the generated id
	public static String generate(String prefix)
	{
		return prefix + generate();
	}
New to GrepCode? Check out our FAQ X