close
# Using the algorithm from Hibernate to generate UUID

require 'socket'
require 'thread'

class UUID
  @@instance = nil
  @@mutex = Mutex.new

  def initialize
    @IP = 0
    ipStr = IPSocket.getaddress(Socket.gethostname)
    ipStr.split('.').collect {|a| a.to_i}.pack('C*').each_byte {|a| @IP = (@IP << 8) - 128 + a}
    @counter = -1
    @JVM = (currentTimeMillis >> 8) & 0xffffffff
  end

  def currentTimeMillis
    (Time.new.to_f * 1000).to_i
  end

  def getJVM
    @JVM
  end

  def getCount
    @@mutex.synchronize do
      @counter = (@counter + 1) % 32768
    end
  end

  def getIP
    @IP
  end

  def getHiTime
    currentTimeMillis >> 32
  end

  def getLoTime
    currentTimeMillis & 0xffffffff
  end

  def generate
    sprintf(’%08x-%08x-%04x-%08x-%04x’, getIP, getJVM, getHiTime, getLoTime, getCount)
  end

  def UUID.getInstance
    @@mutex.synchronize do
      @@instance = new unless @@instance
    end
    @@instance
  end

  def UUID.getUUID
    getInstance.generate
  end
end
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Forth 的頭像
    Forth

    不就是個blog

    Forth 發表在 痞客邦 留言(0) 人氣()