MixedRealityToolkit-Unity icon indicating copy to clipboard operation
MixedRealityToolkit-Unity copied to clipboard

[vNext] Proposed Fixes for Singleton

Open jbienzms opened this issue 9 years ago • 15 comments

I know this may be an unpopular topic, but personally I feel it's time we discuss the implementation of Singleton in the toolkit.

For those who aren't aware, many classes in the toolkit inherit from Singleton. In programming, Singleton is a pattern used to “ensure that only one instance of the singleton class ever exists” (that’s from Wikipedia). But the Singleton class in HoloToolkit doesn't guarantee only a single instance exists. In fact, it doesn't guarantee that any instance exists at all. What Singleton in the toolkit does is return the last instance to become Awake in the Unity scene hierarchy.

Here are some problems that commonly occur with the current implementation:

  1. If no instance of the behavior is placed anywhere in the scene, Singleton.Instance will return null. No exception is thrown and no error will be presented in the log window.

  2. If more than one instance of the behavior is placed in the scene, there is no guarantee which instance will actually be returned by Singleton.Instance. This is because the internal instance is set on Awake and the order in which Awake is called is random. With the current design of Singleton.Instance, the last one Awake wins.

  3. Many behaviors currently use the object returned by Singleton.Instance without checking first to see if it's null. If the user has forgotten to place the behavior in the scene, this results in a non-descriptive NullReferenceException at runtime and the calling GameObject is disabled. This is challenging to debug and very confusing for new Unity developers.

There are currently 271 uses of .Instance in the HoloToolkit. Of those 271, only a tiny fraction (maybe 10 or so) actually check to see if the instance is valid before using it. This opens up a very large possibility of error, and when one does occur it's difficult to solve.

I propose the following changes:

  1. Singleton should be renamed SceneInstance
  2. The .Instance property should be renamed .First
  3. The .First property will log a descriptive error and throw a descriptive exception if no instance is available. Something like "An instance of " + typeof(T).Name + " could not be found in the scene."
  4. A new .FirstOrDefault property will be added which does not throw an exception. This is for cases where it's OK that a behavior may not exist in the scene.
  5. A log message will be generated and exception thrown if more than one instance of the same behavior is added to the scene.

The .First and .FirstOrDefault names as well as their proposed implementation both follow the conventions used in System.Linq for IEnumerable.

These proposed changes correct the misuse of 'Singleton', follow a known pattern, and properly notify the user if they accidentally leave a required behavior out of a scene.

I'm open to thoughts and feedback. I'm also willing to implement these changes if others agree they would be beneficial.

jbienzms avatar Jan 31 '17 03:01 jbienzms

I was just thinking more about the way System.Linq handles enumerable. Maybe there shouldn't be an exception if more than one instance is added to the scene. We could support Linq like queries. .First, .FirstOrDefuault, .All, etc.

jbienzms avatar Jan 31 '17 03:01 jbienzms

Thanks for bringing this up Jared. One of the things I've been mulling over myself but haven't had the time to address. I think you've made a wonderful proposal and would like to see other peoples input as well.

This is probably my biggest concern with the current implementation:

  1. If more than one instance of the behavior is placed in the scene, there is no guarantee which instance will actually be returned by Singleton.Instance. This is because the internal instance is set on Awake and the order in which Awake is called is random. With the current design of Singleton.Instance, the last one Awake wins.

StephenHodgson avatar Jan 31 '17 14:01 StephenHodgson

Proposal seems reasonable to me. @mrbobbybobberson do you have any additional thoughts?

NeerajW avatar Jan 31 '17 17:01 NeerajW

I like the direction of this. It especially startled me when I found no error messaging in .Instance if you forget to create an instance or if you add more than one instance. The only thing I shy away from is making a "First" and "FirstOrDefault". I'd prefer to maintain the idea that this concept is for one-in-a-scene objects, so I'd keep the name as "Instance" or perhaps adopt the name "Single" modeled after Linq. And perhaps if some code needs to check if there's one available, a "HasInstance" or some other bool could be added. Thoughts on that?

mrbobbybobberson avatar Feb 01 '17 03:02 mrbobbybobberson

Thanks for weighing in @mrbobbybobberson. I think we really need to decide how much we want to enforce there being one and only one in the scene. If we really want to enforce exactly one, then I agree that First doesn't make sense. In that case we need to get much more explicit with the log messages and exceptions when one isn't found or when more than one attempts to register itself.

If, instead, the purpose is a lightweight dependency resolution strategy then we might consider relaxing the focus on there being exactly one and shift the focus to finding instance(s) within a scene. In this scenario I feel First does make sense because we would allow more than one.

I had never actually looked at or understood Single in Linq until tonight. That's very interesting and it opens up a third option here: Allow the base class to support multiple instances but let the caller assert when there should be only one:

  • First returns the first one or throws an exception if zero are found.
  • FirstOrDefault returns the first one or null if zero are found (no exception).
  • Single returns the ONLY one and throws an exception <1 or >1 are found.
  • SingleOrDefault returns the ONLY one if there is one but returns null if there are zero (no exception).
  • AsEnumerable returns all registered (awake) instances.

This allows the best of all to be supported by the same base class and still allows us framework developers to easily assert when there should be an exact number in the scene.

For something like SpatialMappingManager, we'd probably want to use Single to assert that there should be one and only one. For something like GestureManager SingleOrDefault may be OK (use it if available). For TextToSpeechManager, you might want to do an AsEnumerable to enumerate across all TTS in the scene and stop them mid sentence.

Thoughts?

jbienzms avatar Feb 01 '17 04:02 jbienzms

Oh, I forgot we didn't make TextToSpeechManager inherit from Singleton specifically because we wanted to support there being more than one instance. So my final example above doesn't entirely make sense right now, but it theoretically could. Then again, if there can be more than one instance I could see people starting to get confused about when to and not to inherit from this class.

I was hanging out with some folks in the Holo Academy today and we were talking about this. I was under the impression that this was created as a way of doing lightweight dependency resolution and allowing dependencies to come from the scene tree. Someone suggested that it started to create and keep instances awake across scenes (instead of using DontDestroyOnLoad).

If this is about resolving dependencies, most DI containers don't allow more than one instance and attempting to register more than one results in an exception. That would help clarify when to use this base class.

Honestly I go back on forth on whether the base class should enforce a single instance or whether or not the the caller (or calling convention) should enforce it. The latter is more flexible, but I can see how it would cause confusion about the cases when it should be used.

jbienzms avatar Feb 01 '17 05:02 jbienzms

Personally, I've not found a use case for me when I really wanted say multiple GazeManagers in my scene. So I would say keeping it to one instance would work well for majority of the cases. With the verbiage change, we can avoid some confusion around legacy singleton stuff as well. But basically, it's almost like the Singleton design pattern. For scenarios that don't want to be a solo 'Scene.Instance' would not inherit from it as you mentioned earlier.

NeerajW avatar Feb 01 '17 18:02 NeerajW

Another idea, why not convert these to an actual Singleton instance. This has been done many times in Unity before, and commonly using the DontDestroyOnLoad for keeping it around, and having any new instances destroy themselves if they are created - so we keep in line with the idea of a Singleton. If an Instance isn't set yet, its getter would Debug.LogError (then we get UnityPlayer.Log info for production builds) or the UnityEngine.Assertions to ensure something is caught in dev builds when expected game objects aren't present. The above should give devs enough info to know when they've forgotten a dependency.

adamtuliper avatar Feb 02 '17 17:02 adamtuliper

Are there any news regarding this issue? Yesterday I ran too into the "Singleton.Instance will return null" problem. Thanks to your posts I realized thats it's a HoloToolkit issue and not a problem within my code. Need to find a solution though..

CarpeTempus avatar Jun 02 '17 09:06 CarpeTempus

Another option to renaming singleton to sceneinstance would be to make a SceneInstance class. Then we can iterate on it without breaking existing folks.

In the RS2 branch we have added a 'SingleInstance' class that behaves like singleton, without needing to remember to call base.Awake() to set the instance. This allows for .Instance to work in Awake() from other scripts. Its getter logs if the class can't be found in the scene or if the class is found more than once in the scene. I could add a 'HasInstance' bool that would (return Instance != null);

CarpeTempus, which pattern caused your Singleton.Instance to be null? It probably is something that you need to correct on your end, either by adding the script with the singleton to the scene or not trying to access a .Instance in an Awake() function. Most of the discussion above I believe is regarding helping developers identify what they need to correct.

darax avatar Jun 02 '17 16:06 darax

Yeah there's a lot of work to be done to get both branches into compliance...

StephenHodgson avatar Jun 02 '17 17:06 StephenHodgson

Reading through the above discussion, I see some interesting points raised which allude to use cases I may not be familiar with. That said, it seems apparent that we're actually covering two related but distinct concepts which ultimately should be split into two separate discussions:

1) Singleton pattern objects: Objects which should have no more than one instance instantiated at any one time across all currently loaded Scenes, and which should be accessible from any Scene. These may or may not be made persistent instances, depending upon the particular use case they are intended to fulfil.

2) Scene-Singleton pattern objects: Objects which should have no more than one instance instantiated within any one Scene, but which may have additional instances which each exist in other Scenes, and which may or may not be accessible from other Scenes.

Personally I have not encountered a use case for a SceneSingleton pattern in Unity, primarily because the Singleton pattern performs almost the same function when used in conjunction with Unity's SceneManagement feature set, for every use case I have personally encountered in production environments. While I can envision a few use cases for this pattern, I also find myself wondering whether there is need for this feature within the MRTK, and invite further discussion from other participants on this point.

The main concern I see with the current implementation of SingleInstance is that it presents itself as being of a Singleton pattern, but is in actuality an implementation of the SceneSingleton pattern exhibiting modified behaviour that is inconsistent with the standard Singleton pattern, and which is also inconsistent with Unity's recommended MonoBehaviour logic flow, for the following reasons:


a) SingleInstance uses lazy instance referencing relying upon Object.FindObjectsOfType<T>() to acquire its first instance from the currently active Scene. This is a flawed approach as it i) does not support finding instances within additively loaded Scenes unless the hosting Scene has previously been marked as active within Unity's SceneManager (See link below for reference), ii) does not warn the user if other instances exist within Scenes which are currently loaded but are not the currently active Scene, and iii) even with these restrictions has a performance described as 'very slow' by Unity Technologies as internally it requires a GameObject.GetComponent<T>() search on every GameObject within a full Scene hierarchy traversal.

It is possible to address this issue by having the component iterate through all currently loaded Scenes to find all instances, however this is an even less performant solution than the current implementation, and I am aware of no more performant approach that does not require an unnecessarily complicated solution.

Unity Documentation, Script reference: Object.FindObjectsOfType<T> https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html

Proposed fix: Singleton instance references should be checked and set explicitly by the valid instance, using its this property.


b) SingleInstance does not follow Unity's recommended logic flow. The recommended logic flow of MonoBehaviour-derived objects is to initialise themselves within their Awake() method (See link below for reference), within which they do not attempt to access any instances of other Components which cannot be guaranteed to exist at that time. This is when the reference to the Singleton instance should be set. If a MonoBehaviour does need to access other Components which are saved to (and thus, initialised within the same frame as other Components in) the currently loading Scene, they should do so no earlier than within their OnEnable(), or ideally within their Start() methods.

Unity Documentation, MonoBehaviour Event Execution Order: https://docs.unity3d.com/Manual/ExecutionOrder.html

Proposed fix: Singleton reference should be set in the Component's Awake() method, and derived components should not access other Components until OnEnable() or Start() methods are executed.


c) SingleInstance attempts to address issues in other MRTK components. Implementing the two fixes proposed above exposes several cases of other components exhibiting the behaviour described in point b) above, in which they attempt to naively access one or more SingleInstance components which are either uninitialised or non-existent at time of execution. These issues may or may not be encountered in any individual project, depending upon feature inclusion, hierarchy layout, and loading order of Scenes containing derived components.

Referring to the class summary of the current implementation of SingleInstance, it seems clear that it was intended to address these issues, however it does so inadequately, and also introduces some serious and untenable issues of its own.

Proposed fix: Other components should be refactored as necessary to make their behaviour consistent with the recommended flow of MonoBehaviour components.


d) No support currently exists for raising an event once the Singleton instance has been initialised. In past and current projects, I have found it useful to be able to have external Components subscribe to an event which will be fired once a particular Singleton has successfully initialised.

One notable example from the MRTK is the WorldAnchorManager's asynchronous loading of the stored WorldAnchor collection, the completion of which is in effect a prerequisite to the WorldAnchorManager being completely initialised. The reason for this process being asynchronous is apparent, however the constraint does require that other Components are able to safely track when that initialisation has taken place, and the cleanest way to do this is to allow those Components to subscribe to an OnInitialisationComplete event defined within the WorldAnchorManager. For similar reasons other Singletons may benefit from this functionality, even if is used only to allow them to announce that they now exist and may be accessed, and it seems worthwhile to implement this in the base class.

Proposed fix: Add a method with the signature public static void RaiseOnInitialisedOrNow(Action callback), which raises the injected callback immediately if the instance has been initialised at time of execution, or stores it for later execution within the Singleton's Awake() method once initialisation has completed successfully.


e) With the above changes, the class should be renamed appropriately. This is more of a code clarity concern, and is predicated upon the assumption that the intent of any entity should be apparent and clear from its name alone. Currently this intent is not served by the name of the SingleInstance class.

Proposed fix: The class is a generic extension of MonoBehaviour which implements Singleton functionality, so I propose the name MonoBehaviourSingleton<T> as an alternative.


f) The above changes do not provide support for SceneSingleton functionality. If deemed necessary, to cover the use case of having multiple instances of a component which implements singleton-like functionality, but with the specific constraint of having no more than one instance in any single Scene, and which may allow cross-Scene instance access, another component should be created to provide this functionality.

Proposed fix: Another thread should be created with this topic as its subject matter.


Contraindications:

While the proposed code changes to this class are relatively trivial, from making similar changes to our local (older) copy of the MRTK it has become clear that the effect upon dependant classes is not. In particular, it will expose a number of issues related to the behaviour described above in point c) throughout the MRTK, each of which will likely need to be addressed as separate issues. With that in mind, it is best that this proposal be considered for a later version which includes further modifications to other MRTK components.

shilohjames avatar May 04 '18 08:05 shilohjames

@shilohjames thanks for the extensive write-up!

We've already agreed to move away from singletons and develop a Dependency Injection approach with vNEXT.

@SimonDarksideJ will be able to give you a bit more information about how that will work.

StephenHodgson avatar May 05 '18 00:05 StephenHodgson

Seconded, a fantastic writeup @shilohjames :D

As @StephenHodgson points out, we are leaving Singleton out of the picture as much as possible, to the extent that there will only be ONE singleton in the MRTK (core).

Instead, we are using a managed container approach approach where all "entities" in the MRTK will subscribe and be managed by the Mixed Reality manager. This will also be extensible enough to support both MRTK components and runtime client components. This also reduces our dependancy on MonoBehaviour to the same extent.

This addresses a lot of what you have described:

    1. Singleton pattern objects: MRTK Managers are single instance in the running project, with Little to no MonoBehaviour impact (which makes them over 30% faster)
    1. Scene-Singleton pattern objects The MRTK manager has a separate container for "run-time" components, utilising the same logic. And more importantly, utilising the same API
  • a) SingleInstance uses lazy instance referencing Completely gone, the Container approach means you have a single place for finding a manager using a discovery pattern which is very fast. No searching of scene as we effectively don't use it.
  • b) SingleInstance does not follow Unity's recommended logic flow. Again, decoupled from MonoBehaviour, so we control the logic flow.

But from your feedback, you have covered somethings which I have not yet accounted for, namely:

  • d) No support currently exists for raising an event once the Singleton instance has been initialised. We do have events throughout the new system, in fact it is mostly event driven. However, the Manager itself doesn't currently raise events for new / existing components.
    Will add this
  • f) The above changes do not provide support for SceneSingleton functionality. Although runtime components in the manager are managed separately and can be flushed, this was designed around run-time, not necessarily scene switching. Will review and look at Scene Flushing / reuse

Keep an eye on the vNext branch (and the MixedRealityManager) to see more of what's coming. As soon as It's demo'able, no doubt Stephen and I will take to the stage 🗡

SimonDarksideJ avatar May 08 '18 16:05 SimonDarksideJ

See my blog post on medium explaining how we solved this problem in vNEXT.

https://medium.com/@stephen_hodgson/the-mixed-reality-framework-6fdb5c11feb2

StephenHodgson avatar Oct 29 '18 03:10 StephenHodgson