How do Groovy (Jenkins pipeline) singletons work?
12:44 05 Dec 2025

Say I have the following classes.

@Singleton
class EnvMgr {
    private String environment = null

    String getEnvironment() {
        return environment
    }
    def setEnvironment(final String env) {
        environment = env
    }
}

class SomeClass1 {
    private EnvMgr envMgr = null
    
    SomeClass1 {
        envMgr = EnvMgr.instance
        envMgr.setEnvironment("sandbox")
    }

    def printEnv() {
        return envMgr.getEnvironment()
    }
}
      
class SomeClass2 {
    private EnvMgr envMgr = null
    
    SomeClass2 {
        envMgr = EnvMgr.instance
    }

    def printEnv() {
        return envMgr.getEnvironment()
    }
} 

Note that SomeClass1 calls EnvMgr::setEnvironment() in its constructor, but SomeClass2 does not.

Now I have the following code to print the classes' environment attribute

c1 = new SomeClass1()
c2 = new SomeClass2()

c1.printEnv() // will print "sandbox"
c2.printEnv() // ???
  1. If I have a Jenkins pipeline that instantiates both classes in the same job, what will c2.printEnv() print?

  2. If I have 2 separate Jenkins pipelines that instantiate each class, say Job1 instantiates SomeClass1, then triggers Job2 which instantiates SomeClass2, what will c2.printEnv() print?

groovy jenkins-pipeline