UObject AddToRoot garbage collection race condition?

If I have a UObject that isn’t stored in a UProperty or TArray, etc., all the documentation I have found has said it can be garbage collected unless AddToRoot() is called on it.

If I create a UObject in a thread outside of the game thread, can it be garbage collected out from under me before I get a chance to call AddToRoot()?

I haven’t been able to find any documentation that explains when garbage collection runs, and what guarantees are made.

Same issue with multithreaded checks of IsPendingKill. If I check IsPendingKill and it returns false, can garbage collection still end up running and setting pending kill in a different thread? What are the timeline guarantees?

Does it require at least two game ticks for an object to get deleted (one to mark pending kill, and one to sweep and destroy), or could it happen at any time?

Is there any documentation on these kind of guarantees and race conditions and what standard code should do? I can’t find anything that spells out the guarantees, tells when garbage collection happens, etc.


did u find answer of those question?
i am also facing same kind of issue which is causing my app to crash

If you pass in another UObject as the Outer in your NewObject call, it should prevent it from being garbage collected as the Outer object would cause your new object to at least have 1 reference to it.

That’s effectively what AddToRoot is doing anyway. Any UObject with 0 References is subject for GC at any time.

From what I was told UObjects really shouldn’t be used much in other threads and it is mainly only the async loader that can create uobjects on another thread. I don’t know what the async loader does to handle this issue.

hmm. if i save my uobject inside of a game instance will it be destroyed by Gc or during a new level loading ?

If you are placing it in the Level structure, that’s highly likely. You could always have the player hold a reference to the object, or some Manager object that exists outside the Level (or create one).

Game Instance persists through level loads. You should be fine with persisting UObjects that way. But AActors depend on a World will not persist to another one without using seamless travel and adding them to the GetSeamlessTravelActorList.