[Zope] Which method to generate IDs for objects?
Dieter Maurer
dieter@handshake.de
Thu, 17 Jan 2002 23:30:46 +0100
Thomas Guettler writes:
> On Wed, Jan 16, 2002 at 12:21:45PM -0000, Tim Hicks wrote:
> > I don't know if this is very efficient/elegant/etc*, but I use it to get a
> > unique id within a folder...
> >
> > -------------
> > intid = 1
> > while 1:
> > if hasattr(photo_folder, str(intid)):
> > intid = intid + 1
> > else:
>
>
> How thread-safe is this? I Java I would write a syncronise block
> around i=i+1, because of the following example:
It is not thread safe and therefore the later "_setObject"
may raise a BadRequest exception due to duplicate ids.
It is therefore better, to use the "_setObject" directly:
while 1:
try: self._setObject(str(intid),o); break;
except BadRequest: intid= intid+1
This, still, is not thread safe. But conflicting threads
write the same object. The standard ZODB conflict resolution
will normally abort one of the conflicting transactions
and restart the corresponding request.
I store the "intid" counter in an object attribute, in order
not to make so many unsuccessful trials. True, usually,
ZODB objects should not be used for counting. But I write
the object anyway (for the new object), thus there is no
additional penalty to write the counter.
Dieter