如何实现唯一的ID编号

 我们经常在程序需要碰到一个唯一的名称问题。比如有很多人都在上传文件,那么我将文件暂时缓存在文件系统时,就需要保证不能同名。

当然我们一般可能会采用time来命名,但是time有些时候也不能完全保证同名,假设统一时间有两个人在传同一文件,就会出现问题。当然这种情况的可能性很小,但是我们还是要保证生成一个自己的ID号,并且长度也要稍短一些。

以下类实现了唯一ID编号的实现:

public class TempID
    implements Serializable
{

    /**
     * Constructs a new UUID.
     */
    public TempID()
    {
        synchronized(uuidObject)
        {
            if(shortValue == maxFirst )
            {
                for(boolean flag = false; !flag;)
                {
                    long currentTime = System.currentTimeMillis();
                    if(currentTime < oldCurrentTime + timeInterval)
                    {
                        try
                        {
                            Thread.currentThread();
                            Thread.sleep(timeInterval);
                        }
                        catch(InterruptedException _ex) { }
                    } else
                    {
                        oldCurrentTime = currentTime;
                        shortValue = 0;
                        flag = true;
                    }
                }

            }
            setUUIDFirst(shortValue++, 0);
            setUUIDSecond(oldCurrentTime, 2);
        }
    }
    /**
     * Constructs a new UUID.
     */
    public TempID(boolean isShort)
    {
        synchronized(uuidObject)
        {
            if(shortValue == maxFirst )
            {
                for(boolean flag = false; !flag;)
                {
                    long currentTime = System.currentTimeMillis();
                    if(currentTime < oldCurrentTime + timeInterval)
                    {
                        try
                        {
                            Thread.currentThread();
                            Thread.sleep(timeInterval);
                        }
                        catch(InterruptedException _ex) { }
                    } else
                    {
                        oldCurrentTime = currentTime;
                        shortValue = 0;
                        flag = true;
                    }
                }

            }
            setUUIDFirst(shortValue++, 0);
            setUUIDSecond(oldCurrentTime-1199030400000L, 2);
        }
    }
    /**
     * judge whether the object is equals to this FUUID.
     * @param obj
     * @return
     */
    public boolean equals(Object obj)
    {
        if(obj != null && (obj instanceof TempID))
        {
         TempID FUUID = (TempID)obj;
            return first == FUUID.first && second == FUUID.second ;
        } else
        {
            return false;
        }
    }

    /**
     * set the second 8 bytes of the uuidBytes according to the currentTime value .
     * @param value - the value to set
     * @param startPos - the start position of the uuidBytes
     */
    private void setUUIDSecond(long value, int startPos)
    {
     second = value ;
//        for(int j = 0; j < 48; j += 8)
//            uuidBytes[startPos++] = (byte)((int)(value >>> j) & 0xff);

    }
    /**
     * set the first two byte of the uuidBytes according to the shorValue.
     * @param value - the value to set
     * @param startPos - the start position of the uuidBytes
    */
    private void setUUIDFirst(short value, int startPos)
    {
     first = value ;
//        for(int j = 0; j < 16; j += 8)
//            uuidBytes[startPos++] = (byte)(value >>> j & 0xff);

    }

    /**
     * return the string value of the FUUID.
     * @return
     */
    public String toString()
    {
        StringBuffer uuidStringBuffer = new StringBuffer(10);
//        uuidStringBuffer.append(uuidStrPref);
        setUUIDString(uuidStringBuffer);
        return uuidStringBuffer.toString();
    }

    public static String newTempID() {
     return new TempID().toString() ;
    }
    public static String newShortTempID() {
     return new TempID(true).toString() ;
    }
    /**
     * set uuidString of the FUUID according the uuidBytes.
     * @param uuidBuffer
     */
    private void setUUIDString(StringBuffer uuidBuffer)
    {
     uuidBuffer.append(Long.toString(second,Character.MAX_RADIX)) ;
     uuidBuffer.append(Integer.toString(first,Character.MAX_RADIX)) ;
    }

//    private static final String uuidStrPref = "TEMP" ;
    private static final long timeInterval = 1L;
    private static final Object uuidObject = new Object();
    private static long oldCurrentTime = System.currentTimeMillis();
    private static short shortValue = 0 ;
    private static int maxFirst = Character.MAX_RADIX*Character.MAX_RADIX ;
    private short first ;
    private long second ;

    public static void main(String args[]) {
     System.out.println(new Date(108,0,0).getTime()) ;
     System.out.println(TempID.newTempID().length()) ;
     long l = System.currentTimeMillis() ;
     for ( int i = 0 ;i < 200000 ; i++ ) {
      TempID.newTempID() ;
     }
     System.out.println(System.currentTimeMillis()-l);
     System.out.println(TempID.newShortTempID()) ;
     System.out.println(Integer.toString(maxFirst-1,Character.MAX_RADIX));
       try {
          System.out.println(Long.toString(oldCurrentTime,Character.MAX_RADIX));
   System.out.println(Long.toHexString(java.text.SimpleDateFormat.getDateInstance().parse("2000-01-01").getTime()));
  } catch (Exception e) {
   // TODO: handle exception
  }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值