Search code examples
osgiaemaem-6

Are services in AEM really singleton?


I have an interface which I have implemented. I have annoted the impl with @Component and @Service of the package org.apache.felix.scr.annotations.

I wrote a simple constructor for my impl

public MyImpl(){
LOG.info("New instance created!!");
}

I also added loggers in @activate and @deactivate method.

I expected to see "New instance created!!" only once BUT I can see activate and deactivate method being called per request I make on a page(This service is invoked by A Sling Model which is used in that page)

What I saw was "New instance created!!" logged several times.

This means the OSGi container create multiple instances of my Service and called the activate and deactivate method every time.

This shows that this is not a Singleton.

The Object should be discarded only when I uninstall my bundle.

Please help me understand what is going on here.

I WANT TO IMPLEMENT A TRUE SINGLETON IN AEM

I have implemented this in AEM 6.5 instance which uses Apache Felix.

Edit:

Adding Service properties:

aemRootUrl  http://localhost:8080
api.http.connections_manager.timeout    60000
api.http.cookie_max.age 18000
api.http.max_connections    200
api.http.max_connections_per_host   20
api.http.timeout.connection 300000
api.http.timeout.socket 300000
api.server.ssl.trust_all_certs  true
api.server.url  https://10asdasdsad
api.server.username admin
component.id    3925
component.name  com.example.foundation.core.connection.impl.HybrisConnectionImpl
non_akamai.api.server.url   hadasdadasd
service.bundleid    585
Service PID com.example.foundation.core.connection.impl.HybrisConnectionImpl
service.scope   bundle
Using Bundles   com.example.dumb-foundation.core (585)

Values altered to hide client specific information

EDIT:: I've removed the SCR annotations and replaced them with OSGI annotations here I've explictly specified

@Component(service =HybrisConnection.class, immediate=true,scope = ServiceScope.SINGLETON)

But still is shows as scope=bundle.

Should I enforce Singleton and OSGi annotations on it's dependencies as well for this to be a proper Singleton?


Solution

  • In declarative services (which is what you use behind the scenes) there are some cases when a component (and its service) is unpublished.

    By default a simple component with immediate=true will come up when the bundle starts and go down when it stops.

    If your component has any mandatory service dependencies (@Reference) then it will only be active while all dependencies are present. So if at least one dependent service goes away the component will be deactivated.

    In addition the component might get restarted when config is not present at start but added later. If you want to avoid this make the config required.