Create a GUID in Java

半城伤御伤魂 提交于 2019-11-26 12:05:28
Mark Byers

Have a look at the UUID class bundled with Java 5 and later.

For example:

java.util.UUID.randomUUID();

It depends what kind of UUID you want.

  • The standard Java UUID class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID instances from long, byte[] or String representations, and provide some appropriate accessors.)

  • The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.

For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.

Just to extend Mark Byers's answer with an example:

import java.util.UUID;

public class RandomStringUUID {
    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        System.out.println("UUID=" + uuid.toString() );
    }
}
Basil Bourque

The other Answers are correct, especially this one by Stephen C.

Reaching Outside Java

Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.

If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:

  • Command-line utility
    Bundled with nearly every operating system.
    For example, uuidgen found in Mac OS X, BSD, and Linux.
  • Database server
    Use JDBC to retrieve a UUID generated on the database server.
    For example, the uuid-ossp extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations:
    • uuid_generate_v1mc() – generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer.
    • uuid_generate_v5(namespace uuid, name text) – generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method.
  • Web Service
    For example, UUID Generator creates Versions 1 & 3 as well as nil values and GUID.

You can use this code to generate GUID.

 import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

public class StrictMicroSecondTimeBasedGuid
{
    private final static Logger logger = Logger
            .getLogger(StrictMicroSecondTimeBasedGuid.class);

    private static final long MICRO_IN_MILL = 1000;
    private static final long NANO_IN_MICRO = 1000;

    private static long baseNanoTime;
    private static long baseTimeInMicro;
    private static long lastGuid;

    static
    {
        /*
         * Nanosecond time's reference is not known, therfore following logic is
         * needed to calculate time in micro without knowing refrence point of
         * nano time*
         */
        baseNanoTime = System.nanoTime();
        baseTimeInMicro = System.currentTimeMillis() * MICRO_IN_MILL;
        lastGuid = baseTimeInMicro;
    }

    public static synchronized Long newGuid()
    {
        long newGuid;

        while ((newGuid = calNewTimeInMicro()) <= lastGuid)
        {
            /** we have to check for this log, we don't want to see log. */

            logger.debug("wait of 10-microsecond is introduced to get new guid");

            try
            {
                TimeUnit.MICROSECONDS.sleep(10);
            } catch (InterruptedException e)
            {
                logger.error("Error", e);
            }
        }

        lastGuid = newGuid;
        return newGuid;
    }

    private static long calNewTimeInMicro()
    {
        return baseTimeInMicro
                + ((System.nanoTime() - baseNanoTime) / NANO_IN_MICRO);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!