Java – generate meaningful random id


import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This shows how to generate meaningful random id for application. If we need
 * to work in clustered environment, we need to add host name or IP address of
 * system.
 * 
 * @author Bhavani P Polimetla
 * @since May-03-2011
 * 
 */
public class TimeStampID {

	public static void main(String[] args) {

		Format formatter = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss:SSS a");
		System.out.println(formatter.format(new Date()));

		System.out.println("Use as random meaningful ID==>" + getTimeStampID());

		System.out.println("Get Unique ID==>" + getUniqueSystemInfo() + ":"
				+ getTimeStampID());

	}

	public static String getTimeStampID() {
		Format formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return formatter.format(new Date());
	}

	public static String getUniqueSystemInfo() {
		try {
			InetAddress thisIPConfig = InetAddress.getLocalHost();

			// System.out.println("Host Name==>"+thisIPConfig.getHostName());
			// System.out.println("IP Address==>"+thisIPConfig.getHostAddress());

			return thisIPConfig.getHostAddress();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "";
	}

}

In multithreaded environment, add thread id to make it more unique.
-o-
Output:

2011-05-03,13:46:36:673 PM
Use as random meaningful ID==>20110503134636673
Get Unique ID==>112.243.32.43:20110503134636689

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s