OSGI service vs. Singleton? - osgi

I am a beginner to OSGI and I am wondering if someone can enlighten me about the difference between creating OSGI service vs singleton pattern. For example, suppose I have a bundle core which provides IService, and multiple bundles that needs to access this. I can:
register a service in the core-bundle, in which the plugins can access
provide a singleton class, which provides the service
Using OSGI service seems to be quite cumbersome; and since the plugins have to depend on Core anyways (to get the interface), what's the advantage of using OSGI service?

Services are the connections between independent modules. Having modules depend on services (with their specification packages) can significantly reduce coupling between modules and thus provide much of the benefits of modularity.
I think the singleton pattern is used in two different ways: you just want a single object be shared between a set of users (e.g. a Log Service) or you can really only have one instance (e.g. there is only one piece of hardware). In general, I see that most people in the enterprise software world talk about the former. However, experience shows that when projects grow, singletons become less singleton but more a shared object, or at least an appearing to be shared object.
The nice thing in OSGi is that you can model both and the clients of the "singleton" are oblivious of it, nor does it require some central configuration. The reason is that OSGi relies on modules in charge, registering a service is a local decision as is listening to a service.
The power of services are not in its dynamics (they are cool though, especially during development), the essence of service is that they provide full local control inside the module without central configuration. Once you understand how powerful this is, there is no way back :-)
Last, OSGi services are not cumbersome, not since we have DS with annotations. Registering a service is now much simpler than creating a Spring bean, no xml, no central configuration:
// A component registered as a ISingleton service
#Component
public class MyImpl implements ISingleton {
void doSingle() { ... }
}
// A component that uses the ISingleton component
#Component
public class MyConsumer {
#Reference
void setISingleton(ISingleton is) { ... }
}
... And the dynamics come largely for free ...

Short answer: if you don't -- and won't -- need the benefit of an OSGi service (e.g., dynamically-managed service implementations and service searches), then you don't need an OSGi service.
But there is more to consider here than whether or not the service would be cumbersome. Heck, OSGi itself can be considered cumbersome. Will another bundle need to provide an implementation of that class? Maybe not. Will the Core bundle ever shut down or otherwise be unable to provide an implementation on demand? Maybe.
To determine if a service is right for the class in question, read the run-down of the specific benefits of a service on the OSGi Alliance's What Is OSGi page. They have a very good explanation of how your singleton class may become more cumbersome than a service.
Good luck.

My OSGi Threading Model 's poc is resulted into believing me that, every service is a singleton for a service consumer. As the only one service object get registered into the osgi service registry. (but you can override this behavior also). So as far as programming is considered, the behavior of a singleton class and an OSGi service is the same. Your class level variables are shared among the various service consumer calls.
I will say OSGI Service is Singleton++
But there are also differences.
OSGi gives you a separate class-loader for each service which is not possible in a singleton. All {singleton} classes are loaded by a single classloader. We can't have two classes with the same name (fully qualified name) in a singleton but this is possible in OSGi.
In certain situations we must be confirmed that a class should be loaded only once (making hibernate session factory, hdfc service initialization, POJO creations which are heavy initializations required only once). Now if you are living in a Java EE scenario some times your singleton class gets loaded twice by two different classloaders. So this results into two times the execution of a static block; an unnecessary job.
Such classloader problems are easily handled by OSGi (as you are a beginner I feel classloading itself is a problem for you in the next few days).
Another great feature provided by OSGi is updating a bundle.
Consider you changed the code in your singleton class. Now you need to deploy this updated class in your running application. You essentially need to restart the system, so that every singleton class loader updates the new instance of the singleton. This is not required in OSGi, just update the bundle.
I will say if you're going to design for larger applications (enterprise scale), or if you need to design code for a limited hardware capacity (low memory constraints, low computing power) then go for OSGi, it is best for the extreme ends. For all others your normal java coding will work perfectly.

You can manage the life cycle (deploy new version of the service, concurrently run multiple versions etc) of a service but you can't manage the life cycle of singleton without restarting the JVM (even with restart you can just have 1 version available at any point of time).

Related

Create A Service And Allow Only One Bundle To Hold That Service At any Time

I'm trying to create a service such that once it is created it only allows itself to be held by a single consumer/bundle at any one time. (If this is against the philosophy/specification of OSGi then that obviously provides a quick answer but reference to the OSGi specs. stating this would be appreciated.)
To implement such a requirement I implemented the ServiceFactory interface thinking that whenever there was a requirement for the service the getService(Bundle bundle, ServiceRegistration<S> registration) method would be called and it would be where I could determine if the Bundle was a new consumer or not and act accordingly.
It appears that this is not the case in the scenario I have tested this in.
Using a Apache Karaf and instantiating a consumer of the Service via Blueprint it would seem that the getService method is never called. Instead the consumer's binding method for the service is called directly but injecting a proxy service object.
While I understand that Blueprint uses proxies surely there is still the obligation of the ServiceFactory contract to fulfil even if it's a proxy object consuming the service?
Why do I want to do this?
I am attempting to wrap JavaFX and the Stage class and because JavaFX isn't OSGi friendly I am attempting to co-ordinate access to the Stage object. I'm aware that there are frameworks such as Drombler but a brief look at them made me think that it doesn't suit my use case. They appear too restrictive for my needs e.g. I don't necessarily wish to layout an application in the manner Drombler uses.
It depends what you mean by a consumer. ServiceFactory does give you the chance to create a separate instance of a service per bundle that calls getService on your service. It's not clear from your question but I suspect you weren't seeing the getService invoked multiple times because you were fetching the service from the same consumer bundle. In this case, ServiceFactory simply returns the same object repeatedly.
As for your general question about restricting access to a single consumer, no that really goes against the OSGi philosophy. I'm sorry I don't have a spec reference for you but the clue is in the name: it's a service that is available to all.
I'm aware that there are frameworks such as Drombler but a brief look at them made me think that it doesn't suit my use case. They appear too restrictive for my needs e.g. I don't necessarily wish to layout an application in the manner Drombler uses.
Please note that the layout of Drombler FX applications is pluggable so you can provide your own implementation tailored to your needs. This allows you to get the most out of Drombler FX and JavaFX.
While this feature is available for some time, there is now a new tutorial trail explaining it in more detail.

OSGi: when to use component framework and when to create objects yourself

I've been an AEM developer for almost a year now. I know AEM uses 'Declarative Services component framework' to manage life cycle of OSGi components.
Consider a scenario when i would export a package from a bundle and import that package from another bundle, i could create objects of classes in first bundle inside second bundle as well. it's a import-export contract in this case.
my question is when i should be using component framework to manage the lifecycle of my objects and when to handle it myself by creating them when required.
In an ideal design, you would NOT in fact be able to create objects from the exported package; because that package would contain only interfaces. This makes it a "pure" contract (API) export. If there are classes in there that you can directly instantiate, then they are implementation classes.
In general it is far better to export only pure APIs and to keep implementation classes hidden. There are two main reasons:
Implementation classes tend to have downstream dependencies. If you depend directly from implementation class to implementation class then you get a very large and fragile dependency graph... and eventually that graph will contain a cycle. In fact it's almost inevitable that it will. At that point, your application is not modular because you cannot deploy or change any part of it independently.
Pure interfaces can be analysed for compatibility between versions. As a consumer or a provider of an API, you know exactly which versions of the API you can support because the API does not contain executable code. However if you have a dependency onto an implementation class, then you never really know when they break compatibility because the breakage could happen deep down in executable code that you can't easily analyse.
If your objects are services then there's no question, they have to be OSGi components.
For other things, my first choice is OSGi components, unless they're trivial objects like data holders or something similar.
If an object requires configuration or refers to OSGi services then it's also clearly an OSGi component.
In general, it's best IMO to think in services and define your package exports as the minimum that allows other bundles to use a bundle's services. Unless a bundle is clearly a reusable library like commons-io (to take a simple example).

Migrating J2EE style Project to OSGi Style using the OSGi declarative services

I am new to OSGi and am using Equinox "Virgo Tomcat Server" (VTS) along with eclipse blueprint, and got big assignment to do in limited time
There is application already developed in J2EE Style
By using JSP->Struts2->Spring->MySQL and SOAP Web Services.
-There are various layer in the existing architecture
Simple Request flow is as mention below
From UI layer->it goes to strus2 configration-> it goes to Spring Configuration->From Spring configuration xml (that is module wise application context xml) Struts Action class is called -From Struts Action class layer -> it goes to Task layer->handler layer->Service Layer -> Adapter or DAO layer ->DB in some cases from service layer call also goes to WebService layer and communicate with Back-end legacy system
My Queries are as Follows
Q1] From UI/JSP to up-to strtus2 action layer code for every module should be club together in to a single .war file say "onlinebank.war" and from struts2 action onwords module wise code in every layer should go in to Module wise OSGi bundles
For e.g. if there are 10 modules there should be 10 osgi bundles
And each module wise bundle should contain module specific code from every layer after action layer and there should be communication between one war "onlinebank.war" and 10 osgi bundles
Q2]To take Q1 to next level
If there are 10 modules then instead of crunching module specific code in one OSGi bundle,
I have to create 3 bundles for each module(XXXAPI,XXXMain,XXXConfig)
for e.g. TestModule
I] TestModuleAPI (will contain only interfaces and abstract classes)
II] TestModuleMain (will contain implementation of interfaces and abstract classes and will provide some default functionality)
III]TestModuleConfig (will be accessing the default functionality of Main Bundle Via API Bundle and also provide some customize/new functionality)
So if there are 10 Module and 3 OSGi Bundles for each module (API,Main,Config) then for 10 bundles there should be 3*10=30 bundles and there should be proper communication between -single war "onlinebank.war" and the 30 bundles
Also there should be proper communication among 30 bundles it self to resolve the dependencies and works together properly/synchronously
Any help will be greatly appreciated
Regards,
Gokul
This is a big task you are tackling. I did such a migration and am quite familiar with OSGi. Still it took about 2 months. So you should first not underestimate the problems you will be facing.
The next thing is that a typical spring application is not well modularized. As there are no private/public packages in JSE developers tend to ignore module boundaries. The modules often also do not have a clean and small API at all so people known what they should access and what not.
So I think your first task is to refactor the application so each bundle offers a minimal API and other modules only access the API. For this task it might make sense to use an architecture tool that allows to define and control these accesses. While still in spring you create beans from a service interface from the API. Later in OSGi the API will allow to define clean OSGi services. If you skip this step then OSGi will not have big advantages. OSGi only works well if the application is strictly modularized.
Then for the actual OSGi migration I can only urge you to hire some specialist to help you. It will be a waste of time and resources if you do this alone.

Why use #Component annotation with each service in CQ

I am bit confused about following things. I understand #Service and #Component annotations are main annotations when we define a component or a service in OSGi. I am referring to http://felix.apache.org/documentation/subprojects/apache-felix-maven-scr-plugin/scr-annotations.html and What is the difference between OSGi Components and Services
Questions:
A service can not be created without #Component annotation, why is that?
I understand once we define a service its life-cycle is managed by OSGi differently but what are the advantages of doing so?
How do we use class defined as #Component as service can be accessed via sling.getService(ServiceName.class)
A service can be published without a #Component annotation, but you have to do it programmatically. If you use the annotation then you benefit from the automatic metadata generation in the build tool, and also from the Declarative Services runtime framework. This simplifies a lot of things. If you want to do it with low-level code you have to write an implementation of BundleActivator, declare that with the Bundle-Activator manifest header, call context.registerService etc. Bottom line: just use the #Component annotation!
Simple: laziness. When a component is a service then it can be instantiated lazily "on-demand", i.e. only when consumer first tries to use the service. Non-service components, on the other hand, usually do other kinds of things inside themselves, e.g. running a web server or a GUI or a polling thread, whatever. These need to be running all the time, rather than on-demand.
3. I didn't understand this question.
A component that is not published as a service cannot be accessed from outside the bundle. If you want it to be accessible then it has to be a service. In case you think this is useless, consider a component that creates an HTTP server. It opens port 80 and responds to network requests from the outside world. So it does something useful even though it's not a service and not accessible from other bundles. This kind of component is like a bridge between your application and the outside world; whereas services are a bridge between one part of your application and another part.
OSGi is the one where bundles are installed and manages. Everything that needs to be there in OSGi has to be a component be it simple component, a service or servlet. That is why we need to use #Component with service also.
Services are singleton. Everything that needs to be managed for Singleton class and using reference of service is done by OSGi. Nothing has to be done from our side. So everything is automatically managed.
You dont access components like that. Components are independently used. Quoting example from different post:
Suppose you want to a write Server component that sits on socket and responds to requests over TCP/IP. When the component starts, it opens the socket and creates the thread(s) required to serve clients. When it stops, it closes the thread(s) and socket

Obtaining list of installed OSGI bundles at runtime

My application obtains class names from a properties file. Classes represented by these class names could reside in certain OSGI bundles unknown at advance so in order to instantiate them I firstly have to find which bundle these classes belong to. I'm thinking about getting all installed bundles from BundleContext#getBundles, this means I have to obtain reference to BundleContext in AbstractUIPlugin#start. But I'm not sure if holding reference to BundleContext is the right thing to do since it's should be used only in the start method. So I need advice from OSGI experts here about the alternatives to get list of bundles.
Any help would be greatly appreciated.
Regards,
Setya
This is not really how OSGi is intended. If a bundle has something to add to the 'global' context, you should register a service. So each bundle that has something to share can do that in its own start method.
Some other component (DS, ServiceTracker, Blueprint, something like that) can then listen to these events, and act accordingly.
This is really important, if you start manually searching through all bundles you completely lose the advantages of OSGi.
Like written before you should try to use services to achieve what you want. I guess you have an Interface with one or more implementations that should be installable at runtime. So if you control the bundles that implement the interface then simply let them install their implementation as a service by using an Activator or a blueprint context. You can use service properties to describe your implementation.
The bundles that need the implementation can then lookup the services using a service tracker or a service reference in blueprint.
If that is not possible then you can use the bundle context to obtain the running bundles and instantiate the classes but this is not how OSGi should work. You will run into classloading problems as the bundle that tries to instantiate the classes will not have direct access to them.
Your bundle gets control at start up through the bundle activator, or better, through DS. At that time it can register services with the services registry so others can find/use them.
The route your planning to go (properties that name classes) is evil since you undoubtedly will run in class loading hell. Modularity is about hiding your implementation details, the name of your implementation classes are such details.
Exposing implementation classes in properties files is really bad practice and it looses the advantage of modularity. It does not matter if another class refers to your implementation class or a property file, the problem is that the impl. class is exposed.
Unfortunately this model has become so prevalent in our industry that many developers think it is normal :-(
OSGi allows you share instances typed by interfaces in a way that allows the implementation class to only be known inside the module.

Resources