Question

So the best way I thought of explaining it would be with examples.

When publishing service X, it is needed to register one instance of it. That same instance answers for as many clients call it.

I was wondering if there is a way to instantiate many instances of it on demand. Like client c1 asks for service X under instance x1, client c2 communicates with instance x2, and after processing each instance is destroyed.

As it works with web servers. Each client method call would be a request, and after it responses that request is destroyed.

I saw some answers about multiple references but I wasn't quite sure if they were all the same question I have.

Thankyou

Was it helpful?

Solution 2

OSGi currently supports ServiceFactory which allows the provider to create a unique service instance for each consumer bundle. This may be sufficient for your needs

But it does not allow the provider to provide a unique service instance for each request for a service within a bundle. I am working on a proposal for R6 to allow the creation of unique service instances for each request. Hopefully it will be accepted into the R6 spec.

OTHER TIPS

A few years ago I tried to answer this question in a generic way in the RFC Genuine Service Factories. After a lot of hard thought I came to the conclusion that the solution was very simple. Just register a factory service. So if you want to be able to create Foo's, just register a FooFactory service ... This allows you to have all the goodies of parameters, type safety, etc. If want a generic solution, just create a Factory type:

public interface Factory<T> { T create(); }

@Component
public class FooFactoryImpl implements Factory<Foo> {
  public Foo create() { ... }
}

However, I found that the nicest way is just to create a FooFactory since this gives you type safety all the way since the generic types tend to require casting. It also gives you extensibility, parameters, and most of all proper documentation of the semantics.

All the other solutions I know tend to suffer from heavy casting and bypassing the type system. The factory components in Declarative Services are a point in case. I think the responsibility of the OSGi service registry is to give you a handle. As with all technologies it is very tempting to add additional semantics since it is often close. I think this is a case that is much better left to Java than to OSGi. keep it simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top