Difference between javax.inject.Singleton and javax.ejb.Singleton

Hakan Kiyar picture Hakan Kiyar · Apr 12, 2016 · Viewed 16.4k times · Source

im little confused. What is the exact difference between javax.inject.Singleton and javax.ejb.Singleton?

Answer

Jens Piegsa picture Jens Piegsa · May 16, 2017

I found a plausible explanation here:

By default, javax.ejb.Singleton session beans are transactional (section 13.3.7 of the EJB 3.1 specification) and require acquisition of an exclusive lock for every business method invocation (sections 4.8.5.4 and 4.8.5.5).

In contrast, a javax.inject.Singleton is not transactional and does not support container-managed concurrency (the major consequence being that no locking scheme is implemented by the container). [...]

If you don't need EJB features, stick with @ApplicationScoped (javax.inject.Singleton is not defined by CDI, and its semantics are therefore not governed by that specification).

To reduce future confusion, I use this small unit test (first level package name needs to be replaced):

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;

import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;

import org.junit.Test;

public class SingletonTest {

    /** requires com.tngtech.archunit:archunit-junit:0.4.0 */
    @Test
    public void detectWrongSingletonAnnotation() {

        final ClassFileImporter importer = new ClassFileImporter();
        final JavaClasses classes = importer.importPackages("first_level_package");

        noClasses().should().beAnnotatedWith("javax.inject.Singleton")
                .as("Please use javax.ejb.Singleton instead of javax.inject.Singleton.")
                .check(classes);
    }
}