bill_dom
bill_dom

Reputation: 71

Java best way to share an object across other objects without using static

I have class A which instantiate class B which in turn do same for class C and so on, forming a large tree. I now need to instantiate an object that should be available all across the tree and I don't want to individually inject this object manually in all classes. I don't want to use a static because there could be different instances of class A running concurrently in different thread and this shared object must be unique per thread. I don't have much experience with thread safe operations.

Upvotes: 1

Views: 1645

Answers (3)

Andrei Nikolaenko
Andrei Nikolaenko

Reputation: 1074

You can have kind of a "Parallel Singleton" so to say, i.e. instead of having only one instance it will keep as many instances as there are threads, in a hashmap with a thread-related object being the key.

Upvotes: 0

christopher
christopher

Reputation: 27336

Use Spring to manage the instance. That way you can inject your instance into any class that needs it and, provided the creation of the parent class is spring managed, the injected bean will be populated.

In some more detail, what you can do is define a class.

public class MyBean {
    // Add your class details.
}

And ensure that Spring is either scanning its package or you have defined the bean in your applicationContext.xml file like this. The next stage is to inject this bean where you need to, using the @Autowired annotation..

@Autowired
private MyBean myBean;

And on the creation of that class, myBean will be populated with the same instance of MyBean that was initially created.

Advantages

  • Doing it this way means that your solution scales well. You can inject it anywhere without constantly changing constructors (and when you're creating more and more sub classes and relationships between classes, this is a prime candidate for Shotgun Surgery.

  • It's always good to learn about technologies that are used in industry.

  • Managing a single instance of a class using other methods (like the Singleton pattern) is usually a bad idea.

Disadvantages

  • Spring does a lot more than just inject objects, and you're pulling down a lot of classes to do just this, which will increase the size of your solution, although not significantly.

Extra Reading

  • Have a look at a basic Spring tutorial to get you going.

  • Have a look at the different scopes that you can create beans with, in case some of them suit your needs better.

Upvotes: 1

bhspencer
bhspencer

Reputation: 13560

You either need a local reference in the context that you want to use the object or you need a static reference. Since you don't want to use static you need to get a local reference. You can do this by passing the object in in the constructor or by adding a setter method. Then higher up the tree where ever you construct the child node you pass in the needed object.

Upvotes: 0

Related Questions