All lessons Leer en español

Security in depth · Unit 21 · Lesson 2 of 6

Objects have lifetimes

Use a job timeline to distinguish a saved reference from a live object.

4 minreadyShort lesson

Helpful before thisMemory safety: boundaries and lifetimes

See all lessons in this topic

After this lesson you can

  • Identify the missing ownership guarantee in a supplied asynchronous job timeline.

One idea. One situation. One reasoned decision.

How it works

A reference is useful only while the object it describes remains valid for that operation. Ownership, borrowing, and lifecycle rules help prevent accidental access after disposal or reuse. Concurrency makes these rules harder because another worker may change the lifetime unexpectedly. Prefer language and library facilities that express the intended ownership rather than relying on an informal agreement between distant pieces of code.

Object created → Valid lifetime → Object releasedObject createdValid lifetimeObject released
Follow the relationship: Object created → Valid lifetime → Object released.

A queued job can outlive its input

A fictional image preview service hands work to a queue. For this example, the queue stores a reference without extending the source object’s lifetime.

Event Recorded action
L1 Request creates image object P
L2 Preview job queues a reference to P
L3 Request ends and releases P
L4 Preview job starts

Worked decision: the job cannot rely on P being valid at L4. L2 records a location, but this queue’s contract gives it no ownership. Even if the same location still contains familiar-looking bytes, that observation does not restore the released object’s lifetime.

Two designs could meet the requirement: give the job an owned copy before L3, or use a documented ownership mechanism that keeps P alive until the job finishes. Merely making the queue faster does not guarantee either.

State a second requirement separately: if several workers can modify the retained object, its lifetime guarantee does not by itself prevent conflicting updates. The design must also define synchronization or immutability. Review both obligations against the actual language and library contract rather than assuming every reference behaves the same way.

The key distinction: Location and lifetime are different properties.

Check yourself

No timer. No penalties. Read the explanation and try again whenever you like.

  1. What change directly addresses the lifetime gap in L1-L4?

    Show the answer

    Correct answer: Give the job an owned copy or a lifetime-extending owner before the request ends. Either design can keep valid data available to the job under its documented contract. Concurrent modification still needs a separate rule.

Try it

  • WriteWrite a corrected order for events L1-L4 using either an owned copy or a documented shared owner. State when the final owner may release the object.
References