JAVA UUID Generation

Source: Internet
Author: User

Tags: style blog http io ar os using SP for

The GUID is a 128-bit long number, typically represented by a 16 binary. The core idea of the algorithm is to combine the machine's NIC, local time, and a random number to generate the GUID. Theoretically, if a machine produces 10 million GUIDs per second, it can be guaranteed (in a probabilistic sense) that it will not repeat for 3,240 years.

The UUID is a new class in 1.5 that, under Java.util, can produce a globally unique ID.

Package com.mytest;

Import Java.util.UUID;

public class Utest {
public static void Main (string[] args) {
UUID uuid = Uuid.randomuuid ();
SYSTEM.OUT.PRINTLN (UUID);
}
}


The UUID (universally unique Identifier) Globally unique identifier, which is a number generated on a machine that guarantees that all machines in the same time and space are unique. Based on the standard calculations developed by the Open Software Foundation (OSF), Ethernet card addresses, nanosecond time, chip ID codes, and many possible numbers are used. A combination of the following: the current date and time (the first part of the UUID is related to the time, if you generate a UUID after a few seconds, the first part is different, the rest is the same), the clock sequence, the globally unique IEEE Machine identification number (if there is a network card, from the network card, No network cards are available in other ways, the only drawback to the UUID is that the resulting string will be longer.
InJavaThere are several ways to generate a UUID in the main:

JDK1.5
If the JDK1.5 is used, then the spawning UUID becomes a simple matter, assuming that the JDK implements the UUID:
Java. util. UUID, can be called directly.
UUID uuid = Uuid.randomuuid ();
String s = Uuid.randomuuid (). toString ();//The primary key ID used to generate the database is very good.

The UUID is made up of a 16-bit number that shows up in the form of such
550e8400-e29b-11d4-a716-446655440000

Here is the code that implements obtaining a unique primary key ID for the database
public class Uuidgenerator {
Public Uuidgenerator () {
}
/**
* Get a UUID
* @return String UUID
*/
public static String Getuuid () {
String s = Uuid.randomuuid (). toString ();
Remove the "-" symbol
Return s.substring (0,8) +s.substring (9,13) +s.substring (14,18) +s.substring (19,23) +s.substring (24);
}
/**
* Get a specified number of UUID
* The number of UUID to be obtained @param numbers int
* @return string[] UUID Array
*/
public static string[] Getuuid (int number) {
if (number < 1) {
return null;
}
string[] ss = new String[number];
for (int i=0;i<number;i++) {
Ss[i] = Getuuid ();
}
return SS;
}
public static void Main (string[] args) {
string[] ss = Getuuid (10);
for (int i=0;i<ss.length;i++) {
System.out.println (Ss[i]);
}
}
}


Two ways of generating GUIDs and UUID

Need to Comm Log Library

/**
* @author Administrator
*
* TODO to change the template for this generated type comment go to
* Window-preferences-java-code Style-code Templates
*/
Import java.net.InetAddress;
Import java.net.UnknownHostException;
Import Java.security.MessageDigest;
Import java.security.NoSuchAlgorithmException;
Import Java.security.SecureRandom;
Import Java.util.Random;

public class Randomguid extends Object {
Protected final Org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory
. GetLog (GetClass ());

Public String valueBeforeMD5 = "";
Public String valueAfterMD5 = "";
private static Random Myrand;
private static SecureRandom Mysecurerand;

private static String s_id;
private static final int pad_below = 0x10;
private static final int two_bytes = 0xFF;

/*
* Static block to take care of one time securerandom seed.
* It takes a few seconds to initialize SecureRandom. You might
* Want to consider removing this static block or replacing
* It with a "time since first loaded" seed to reduce this time.
* This block would run only once per JVM instance.
*/

static {
Mysecurerand = new SecureRandom ();
Long Secureinitializer = Mysecurerand.nextlong ();
Myrand = new Random (Secureinitializer);
try {
s_id = Inetaddress.getlocalhost (). toString ();
} catch (Unknownhostexception e) {
E.printstacktrace ();
}

}


/*
* Default constructor. With no specification of security option,
* This constructor defaults-lower security, high performance.
*/
Public Randomguid () {
Getrandomguid (FALSE);
}

/*
* Constructor with security option. Setting Secure True
* Enables each random number generated to be cryptographically
* Strong. Secure false defaults to the standard Random function seeded
* With a single cryptographically strong random number.
*/
Public Randomguid (Boolean secure) {
Getrandomguid (secure);
}

/*
* Method to generate the random GUID
*/
private void Getrandomguid (Boolean secure) {
MessageDigest MD5 = NULL;
StringBuffer sbValueBeforeMD5 = new StringBuffer (128);

try {
MD5 = messagedigest.getinstance ("MD5");
} catch (NoSuchAlgorithmException e) {
Logger.error ("error:" + E);
}

try {
Long time = System.currenttimemillis ();
Long rand = 0;

         if (secure) {
             rand = Mysecurerand.nextlong ();
        } else {
             rand = Myrand.nextlong ();
        }
         sbvaluebeforemd5.append (s_id);
         sbvaluebeforemd5.append (":");
         Sbvaluebeforemd5.append (long.tostring (time));
         sbvaluebeforemd5.append (":");
         Sbvaluebeforemd5.append (long.tostring (Rand));

ValueBeforeMD5 = Sbvaluebeforemd5.tostring ();
Md5.update (Valuebeforemd5.getbytes ());

byte[] array = md5.digest ();
StringBuffer sb = new StringBuffer (32);
for (int j = 0; j < Array.Length; ++j) {
int b = array[j] & two_bytes;
if (b < pad_below)
Sb.append (' 0 ');
Sb.append (integer.tohexstring (b));
}

ValueAfterMD5 = Sb.tostring ();

} catch (Exception e) {
Logger.error ("error:" + E);
}
}

  /*
    * Convert to the standard format for GUID
    * (Useful for SQL Server uniqueidentifiers, etc.)
    * EXAMPLE:C2FEEEAC-CFCD-11D1-8B05-00600806D9B6
    */
   public string toString () {
      String raw = Valueaftermd5.touppercase ();
      stringbuffer sb = new StringBuffer (64);
      sb.append (raw.substring (0, 8));
      sb.append ("-");
      Sb.append (raw.substring (8, 12));
      sb.append ("-");
      Sb.append (raw.substring (12, 16));
      sb.append ("-");
      Sb.append (raw.substring (16, 20));
      sb.append ("-");
      sb.append (raw.substring);

return sb.tostring ();
}


Demonstraton and self Test of class
public static void Main (String args[]) {
for (int i=0; i<; i++) {
Randomguid myguid = new Randomguid ();
System.out.println ("Seeding string=" + myguid.valuebeforemd5);
System.out.println ("rawguid=" + myguid.valueaftermd5);
System.out.println ("randomguid=" + myguid.tostring ());
}
}


}

Same

UUID uuid = Uuid.randomuuid ();
System.out.println ("{" +uuid.tostring () + "}");

A UUID is a number generated on a machine that guarantees that all machines in the same time and space are unique. Typically the platform provides the API to generate the UUID. The UUID is based on the standards established by the Open Software Foundation (OSF), using Ethernet card addresses, nanosecond-seconds, chip ID codes, and many possible numbers. A combination of the following: the current date and time (the first part of the UUID is related to the time, if you generate a UUID after a few seconds, the first part is different, the rest is the same), the clock sequence, the globally unique IEEE Machine identification number (if there is a network card, from the network card, No network cards are available in other ways, the only drawback to the UUID is that the resulting string will be longer. The most common use of UUID for this standard is the GUID of Microsoft (Globals Unique Identifiers).

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/xiajing12345/archive/2005/04/22/358976.aspx




The UUID meaning is a universal unique identifier (universally unique Identifier), which is a software construction standard and is also organized by the Open Software Foundation, OSF, in a distributed computing environment ( Distributed Computing Environment, DCE) part of the field. The purpose of the UUID is to allow all elements in a distributed system to have unique identification information without the need to specify the information through the central control terminal. In this way, everyone can create a UUID that does not clash with others. In such a case, there is no need to consider the name duplication problem when the database is established. Currently the most widely used UUID is Microsoft's globally Unique Identifiers (GUIDs), while other important applications are the Linux ext2/ext3 file system, LUKS encryption partition, GNOME, KDE, Mac OS X, and so on.

The following is an example of a specific build UUID:

View Plaincopy to Clipboardprint?
Package test;

Import Java.util.UUID;

public class Uuidgenerator {
Public Uuidgenerator () {
}

public static String Getuuid () {
UUID uuid = Uuid.randomuuid ();
String str = uuid.tostring ();
Remove the "-" symbol
String temp = str.substring (0, 8) + str.substring (9, +) + str.substring (+) + str.substring (+ +) + str.substring (2 4);
Return str+ "," +TEMP;
}
Get a specified number of UUID
public static string[] Getuuid (int number) {
if (number < 1) {
return null;
}
string[] ss = new String[number];
for (int i = 0; i < number; i++) {
Ss[i] = Getuuid ();
}
return SS;
}

public static void Main (string[] args) {
string[] ss = Getuuid (10);
for (int i = 0; i < ss.length; i++) {
System.out.println ("ss[" +i+ "]=====" +ss[i]);
}
}
}
Package test;

Import Java.util.UUID;

public class Uuidgenerator {
Public Uuidgenerator () {
}

public static String Getuuid () {
UUID uuid = Uuid.randomuuid ();
String str = uuid.tostring ();
Remove the "-" symbol
String temp = str.substring (0, 8) + str.substring (9, +) + str.substring (+) + str.substring (+ +) + str.substring (2 4);
Return str+ "," +TEMP;
}
Get a specified number of UUID
public static string[] Getuuid (int number) {
if (number < 1) {
return null;
}
string[] ss = new String[number];
for (int i = 0; i < number; i++) {
Ss[i] = Getuuid ();
}
return SS;
}

public static void Main (string[] args) {
string[] ss = Getuuid (10);
for (int i = 0; i < ss.length; i++) {
System.out.println ("ss[" +i+ "]=====" +ss[i]);
}
}
}

Results:

View Plaincopy to Clipboardprint?
Ss[0]=====4cdbc040-657a-4847-b266-7e31d9e2c3d9,4cdbc040657a4847b2667e31d9e2c3d9
ss[1]=====72297c88-4260-4c05-9b05-d28bfb11d10b,72297c8842604c059b05d28bfb11d10b
Ss[2]=====6d513b6a-69bd-4f79-b94c-d65fc841ea95,6d513b6a69bd4f79b94cd65fc841ea95
ss[3]=====d897a7d3-87a3-4e38-9e0b-71013a6dbe4c,d897a7d387a34e389e0b71013a6dbe4c
ss[4]=====5709f0ba-31e3-42bd-a28d-03485b257c94,5709f0ba31e342bda28d03485b257c94
Ss[5]=====530fbb8c-eec9-48d1-ae1b-5f792daf09f3,530fbb8ceec948d1ae1b5f792daf09f3
ss[6]=====4bf07297-65b2-45ca-b905-6fc6f2f39158,4bf0729765b245cab9056fc6f2f39158
Ss[7]=====6e5a0e85-b4a0-485f-be54-a758115317e1,6e5a0e85b4a0485fbe54a758115317e1
Ss[8]=====245accec-3c12-4642-967f-e476cef558c4,245accec3c124642967fe476cef558c4
ss[9]=====ddd4b5a9-fecd-446c-bd78-63b70bb500a1,ddd4b5a9fecd446cbd7863b70bb500a1
Ss[0]=====4cdbc040-657a-4847-b266-7e31d9e2c3d9,4cdbc040657a4847b2667e31d9e2c3d9
ss[1]=====72297c88-4260-4c05-9b05-d28bfb11d10b,72297c8842604c059b05d28bfb11d10b
Ss[2]=====6d513b6a-69bd-4f79-b94c-d65fc841ea95,6d513b6a69bd4f79b94cd65fc841ea95
ss[3]=====d897a7d3-87a3-4e38-9e0b-71013a6dbe4c,d897a7d387a34e389e0b71013a6dbe4c
ss[4]=====5709f0ba-31e3-42bd-a28d-03485b257c94,5709f0ba31e342bda28d03485b257c94
Ss[5]=====530fbb8c-eec9-48d1-ae1b-5f792daf09f3,530fbb8ceec948d1ae1b5f792daf09f3
ss[6]=====4bf07297-65b2-45ca-b905-6fc6f2f39158,4bf0729765b245cab9056fc6f2f39158
Ss[7]=====6e5a0e85-b4a0-485f-be54-a758115317e1,6e5a0e85b4a0485fbe54a758115317e1
Ss[8]=====245accec-3c12-4642-967f-e476cef558c4,245accec3c124642967fe476cef558c4
ss[9]=====ddd4b5a9-fecd-446c-bd78-63b70bb500a1,ddd4b5a9fecd446cbd7863b70bb500a1

As can be seen, the UUID refers to the number generated on a machine, which guarantees that all machines in the same time and space are unique. Typically, the platform provides the generated APIs. Based on standard calculations developed by the Open Software Foundation (OSF), Ethernet card addresses, nanosecond-seconds, chip ID codes, and many possible numbers are used

The UUID is composed of the following parts:

(1) The current date and time, the first part of the UUID is related to the time, if you generate a UUID after a few seconds to generate a UUID, then the first part is different, the rest is the same.

(2) Clock sequence

(3) Globally unique IEEE machine identification number, if there is a network card, from the network card MAC address obtained, no network card is obtained in other ways.

The only drawback to the UUID is that the resulting string will be longer. The most common use of UUID for this standard is the GUID of Microsoft (Globals Unique Identifiers). In ColdFusion, the UUID can be easily generated using the Createuuid () function in the form of: Xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx (8-4-4-16), where each x is 0-9 or a-f A hexadecimal number within the range. The standard UUID format is: xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12), which can be converted from cflib download CreateGUID () UDF.

The benefits of using UUID are reflected in distributed software systems (e.g. DCE/RPC, Com+,corba), which ensures that the identities generated by each node are not duplicated, and that the benefits of the UUID will be more pronounced with the development of integrated technologies such as Web services. Depending on the specific mechanism used, the UUID must not only be guaranteed to be different from each other, or at least be very different from any other generic unique identifiers that were generated before the 3400 AD.

The universal unique identifier can also be used to point to most possible objects. Microsoft and some other software companies tend to use the globally unique identifier (GUID), which is a type of universal unique identifier that can be used to point to the Building object module object and other software components. The first universal unique identifier is a component created in the Snare computer system (NCS) and subsequently become a distributed computing environment (DCE) of the Open Software Foundation (OSF).

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/carefree31441/archive/2009/03/17/3998553.aspx

JAVA UUID Generation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: