程序只在一个虚拟机上用,可以在这个产生唯一代码的方法前面加上synchronized
跨虚拟的机的可以通过数据库实现代码的生成。或者采用ejb来生key

解决方案 »

  1.   

    在数据库中有Sequence(序号)它由数据库自动增加,这是解决多用户操作时可能同时取同一个值一种好的解决方法。
    在程序中可用Select语句读取。
      

  2.   

    可以在数据库中加个表,里面只有2个字段,表名和值!
    可以用到单例和工厂模式写一个生成主键的类,对这个表进行synchronized操作,每次要insert时利用这个类生成键!
      

  3.   

    不一定要用synchronized。用数据库事务也可以,做成一个函数或一个存贮过程
    begin transaction;
      index = select key from keyTable;
      index = index+1;
      update KeyTable set key = index; 
      index = select key from keyTable;
    end transaction;
    return index; 为提高效率可以写成如下(应尽量用这个函数生成key,否则浪费编码空间):
    int getIndex(){
    static bIsFirst = false;
    int currentIndex , maxIndex;
    if(IsFirst || (currentIndex == maxIndex)){
    begin transaction;
      currentIndex = select key from keyTable;
      maxIndex = currentIndex+100;//或其它缓冲值
      update KeyTable set key = maxIndex; 
      maxIndex = select key from keyTable;
    end transaction;
    }//end if 
    return ++currentIndex;
    }//end 
      

  4.   

    注相应SQL语句请用JDBC调用(这里简写了)
      

  5.   

    可以在数据库中加个表,里面只有2个字段,表名和值!
    可以用到单例和工厂模式写一个生成主键的类,对这个表进行synchronized操作,每次要insert时利用这个类生成键!
    --
    同意