How to create UniqueId based on current date

I am creating an OrderId which should consist of yyMMddhhmmssMs and this orderId represents the primarykey field for the Orders table.

The way to generate the order ID is below:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTime {

    public static String getCurrentDateTimeMS() {
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyMMddhhmmssMs");
        String datetime = ft.format(dNow);
        return datetime;
    }

    public static void main(String args[]) throws InterruptedException {
        for (int i = 0; i < 50; i++) {
            String orderid = DateTime.getCurrentDateTimeMS();
            System.out.println(orderid);
        }
    }
}

      

But when I loaded my app with JMeter with 100 users at 2 seconds zoom, most of them were throwing Duplicate like below.

java.sql.BatchUpdateException: Duplicate entry '1410160239241024' for key 'PRIMARY'
        at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1269)
        at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:955)
        at com.services.OrdersInsertService.getData(OrdersInsertService.java:86)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)

      

How can a UniqueId be generated based on the current time so that it never breaks no matter how many concurrent users are present.

+3


source to share


5 answers


This is due to the speed of the loop for

, which is faster than your time :). Because the loop repeats itself in less than milliseconds and generates values. You can only call it when you want to insert a single value into the database and don't repeat the values.

Alternatively, you can use UUID

for this purpose (for an alphanumeric value).

for (int i = 0; i < 50; i++) {
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyMMddhhmmssMs");
        String datetime = ft.format(dNow);
        System.out.println(datetime);
}

      



OUTPUT

141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
141016030003103
//.....and more

      

+4


source


This code will help you generate any number of unique IDs using the current timestamp. The generated identifier is of type long - 64 bits. The least significant 17 bits are used when a request to create a new unique identifier is received in the same millisecond of time as the previous request. It is identified as a sequence in the code below. This allows the code to generate 65536 unique IDs in a millisecond.



/**
 * Unique id is composed of:
 * current time stamp - 47 bits (millisecond precision w/a custom epoch gives as 69 years)
 * sequence number - 17 bits - rolls over every 65536 with protection to avoid rollover in the same ms
 **/

public class UniqueIdGenerator {
    private static final long twepoch = 1288834974657L;
    private static final long sequenceBits = 17;
    private static final long sequenceMax = 65536;
    private static volatile long lastTimestamp = -1L;
    private static volatile long sequence = 0L;

    public static void main(String[] args) {
        Set<Long> uniqueIds = new HashSet<Long>();
        long now = System.currentTimeMillis();
        for(int i=0; i < 100000; i++)
        {
            uniqueIds.add(generateLongId());
        }
        System.out.println("Number of Unique IDs generated: " + uniqueIds.size() + " in " + (System.currentTimeMillis() - now) + " milliseconds");
    }

    private static synchronized Long generateLongId() {
        long timestamp = System.currentTimeMillis();
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) % sequenceMax;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }
        lastTimestamp = timestamp;
        Long id = ((timestamp - twepoch) << sequenceBits) | sequence;
        return id;
    }

    private static long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}

      

+1


source


Use this:

int unique_id= (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE); 

      

+1


source


Add a unique string to each order ID, such as the user's email address (if unique in your database) or the user ID from your database. This makes the order ID truly unique.

String unique = timestamp + unique_user_field

0


source


Public class Test {

public static void main(String[] args) {

    Date d=new Date();
    //it will return unique value based on time
    System.out.println(d.getTime());


}

}

      

you can use getTime method of date class. it returns the number of milliseconds since Jan 1, 1970 00:00:00 GMT represented by that date.

0


source







All Articles