3

Should I be sure that if any of my application component is started (onCreate for Activity/Service, onReceived for BroadcastReceiver, etc) then my application instance of Application class already exists?

I have static field "instance" in my Application class

  public class MyApplication extends Application {
private static MyApplication instance;

@Override
public void onCreate() {
    instance = this;
    super.onCreate();
}

    public MyApplication getInstance(){
         return instance;
    }

Of course this class is registered in manifest. I wonder if usage of static instance field is safe and will always return me proper value. I didn't use content providers before, but will it work for content providers too?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Solvek
  • 5,158
  • 5
  • 41
  • 64

1 Answers1

-3

If onCreate can only be accessed from a single thread, and is only created once, you should be fine. See this post for an example of how to implement the Singleton in a thread-safe way (albeit in C#). The static reference is indeed thread-safe providing you also have a static initializer.

http://www.codeinthemorning.com/design-patterns/singleton-pattern/

Anish Patel
  • 705
  • 3
  • 8
  • 19