简体   繁体   English

生成单调递增的整数

[英]Generate monotonically increasing integers

I need to generate monotonically increasing integers. 我需要生成单调递增的整数。

Could I use the timestamp to somehow generate such type of integer sequence? 我可以使用时间戳以某种方式生成这种整数序列吗?

I would request an integer at a time, and I won't be requesting more than an integer in the same second's interval - if I do, I won't mind if it passes me the same integer within that second's interval. 我会一次请求一个整数,而在相同的时间间隔内,我所请求的整数不会多-如果我这样做,我不会介意在该秒的间隔内是否传递相同的整数。

You can use an AtomicInteger object to maintain a thread safe counter. 您可以使用AtomicInteger对象维护线程安全计数器。 Then use getAndIncrement() when you need the next integer. 然后在需要下一个整数时使用getAndIncrement()

Since monotonically increasing integers do not need to be contiguous (ie there can be gaps, as long as the number keeps increasing), and it sounds like you want all calls made in the same second to return the same integer, a method that returns how many seconds the JVM has been up would do nicely. 由于单调递增的整数不需要是连续的(即,只要数字不断增加,就可以有间隔),而且听起来您希望在同一秒内进行的所有调用都返回相同的整数,因此该方法返回JVM运行好几秒钟会很好。

Here's a simple implementation that does that: 这是执行此操作的简单实现:

private static long startTime = System.currentTimeMillis();

public static int secondsSinceStart() {
    return (int) TimeUnit.SECONDS.convert(
        System.currentTimeMillis() - startTime, TimeUnit.MILLISECONDS);
}

FYI, this would last 68 years before rolling over. 仅供参考,这将持续68年,然后再滚动。

This is my self made generator... 这是我自制的发电机...

  public final class IdGenerator {

  private static final int MAGNITUDE = 10000;
  private static long previousTimestamp;

  private static int counter = 0;

  private IdGenerator() {
  }

  public synchronized static long generateId() {
    final long timeMillis = System.currentTimeMillis();
    if (previousTimestamp != timeMillis) {
      counter = 0;
    }
    previousTimestamp = timeMillis;

    final int counterValue = counter++;
    if (counterValue >= MAGNITUDE) {
      //just to be sure
      throw new IllegalStateException("too many id generated for a single timestamp!");
    }

    return timeMillis * MAGNITUDE + counterValue;
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM