I am generating a OrderId which should consist of yyMMddhhmmssMs and this orderId represents primarykey field for the Orders table .
The way i was generating 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 load tested my Application using JMeter with 100 users with a ramp up of 2 seconds most of them were throwing Duplicate as shown 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 is it possible to generating UniqueId based on current time so that it never fails no matter how many concurrent users are present .