[Zope] Which method to generate IDs for objects?
Tim Hicks
tim@sitefusion.co.uk
Fri, 18 Jan 2002 00:14:03 -0000
> 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
I follow this, and understand the points you both raise. Dieter, your
(partial) solution won't work from a PythonScript though because of the _ in
_setObject, right?
> 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.
Noted for future reference.
> 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.
I don't understand why storing the 'intid' in an object attribute cuts down
on the unsuccessful trials. Do you mean storing it persistently in the
parent object?
tim