Java generate and track small reusable unique numbers for business use cases

Viewed 52

For inventory management we use a key/id called item number

  • It is a consecutive number starting from 1
  • It must be unique
  • The datatype is int
  • It is not a database key
  • It should get reused after deletion
  • We want to keep it small, so customers may enter the number by hand (e.g. the barcode scanner fails or the item label is damaged)

Current situation

  • Currently we keep track of that number in the database.
  • On each system (re-)start the highest currently used number is determined and used as a new starting point for every new number we need to generate
  • if the next number is not free, we just skip it and continue until we find a free one (this check is rather expensive since a query to the db is made; however most of the time the numbers are not in use)
  • the method responsible for the number generation is serialized for concurrent use

Problem 1: We are not able to reuse any item numbers after they have been deleted

Problem 2: Importing data from other sources

  • items from foreign systems have their own item number which we need to keep (except if the item number is used in the current system, then a new item number is generated instead)
  • these item numbers can have a much higher value as those in the current system => this leads to big gaps; after the next system start all new item numbers start from the highest number (!)

Required change

  • As part of system start-up we need to obtain the list of item numbers currently in use; I guess SELECTing just that one column and storing it in a Set should be ok; the required size for that data structure would be approximately 400 KB (a set of 100.000 ids of type int)
  • This set must then be consulted to find the next minimal number which is not contained in that set; that access needs to be serialized or handled in a concurrent matter (i.e. no two threads are allowed to receive the same number)
  • I've found a trivial approach on how to obtain the next free number here: Find First missing number in Set
  • the set and the database must be kept in sync about which numbers are used and which numbers are free; i.e. I could first test the set until I find a free number, and then test in the database; if not free why-so-ever insert in set and repeat ...

Questions

  • Does this approach sound reasonable?
  • Are you familiar with (standard) libraries which support implementing that kind of number generation?
0 Answers
Related