February 17, 2010

Don’t use Entity.ID as a unique key

The function Entity.ID returns a integer number for an instance of an entity. For my entity representing an order in my simulation model, I called the entity "MyOrder", and used MyOrder.ID in an expression to return an integer number that is different for each instance. Or is it?

When digging a little bit deeper one finds that it is a misbelief to think that the ID is uniquely used. I stumbled over this when I was trying to implement a storage with reserved items for production orders. To reserve an item for a production order, I wanted to assign the ID, because at this time I thought it would be unique. When writing some debug information to a log file, I saw some strange behavior: although only executed once, the process step that stores the reserved items for an order does this multiple times for the same order.

After wondering about this for a bit I found the reason for this: the ID is unique, but only for entities that are currently in the model. So what does this mean? It means that when an entity is created it may be assigned the ID 25, but after it is destroyed by the sink, and therefore leaves the model, the number 25 becomes available again, and is eventually assigned to the next created entity. This explains why in my storage I found multiple entries for the same ID, at different times.

I worked around this problem by adding my own OrderNr state to the entity and assigning it a unique value when it is created. For this, I use a simple discrete state variable that is incremented every time an entity is created.

To sum up: The Entity.ID is unique for the lifetime of an entity in the system; once it has been destroyed, this ID can be reused. So the ID is not unique for a whole simulation run.