Search code examples
javadesign-patternssingletonsingle-instance

Specific instance/Non Singleton


How to instantiate java class with parameters and use the same instance through out the application?

What i want to do is when a tibco esb requests a web service call to my application,i will capture user information(user name) in one pojo class so that I can use this pojo class and user information at other places in application also for this particular tibco request.

This question might sounds crazy but I would like to implement something like this in my application.Waiting for your thoughts guys.


Solution

  • You can use a ThreadLocal solution:

    public class MyClassInstanceHolder {
        private static ThreadLocal<MyClass> instance = new ThreadLocal<>();
    
        public static setInstance(MyClass instance) {
            instance.set(instance);
        }
        public static MyClass getInstance() {
            instance.get();
        }
    }
    ...
    MyClass myInstance = MyClassInstanceHolder.getInstance();
    

    So in that thread you'll have access to the object stored in that ThreadLocal.