Uploaded image for project: 'Jenkins'
  1. Jenkins
  2. JENKINS-57564

Documentation Update - Jenkins Shared Library Pipeline - Singleton vs On-Demand Singleton

XMLWordPrintable

      In the Jenkins documentation, it mentions that all var definitions are on-demand singletons, but does not explain what that means. Documentation reference: https://jenkins.io/doc/book/pipeline/shared-libraries/#defining-global-variables

       

      Does this mean that the singleton is determined at the moment the job is called, so its a unique instance for that particular job? And how does this compare to an explicit @Singleton call when placed on a class?

       

      I tried setting up my shared pipeline so I could review both sides of it.  When I run the code below, I can see in the output that both classes print out the information I expect. They both start as empty strings and then are set equal to the env.BUILD_TAG.

       

      My concern is that if I have multiple jobs running concurrently, do they share the same Singleton or is it unique to each build? So far I have not been able to prove this, so I was hoping someone has an answer to this.

       

      Structure

      src
       - org
       - utilities
       - GlobalStateClass.groovy
      vars
       - globalStateVar.groovy
       - main.groovy

      GlobalStateClass.groovy

      #!groovy
      package org.utilities
      @Singleton
      class GlobalStateClass implements Serialization{
       public String version = ""
      }
      

       

      globalStateVar.groovy

      #!groovy
      class globalStateVar implements Serialization{
       public String version = ""
      }

      main.groovy

      #!groovy
      import org.utilities.GlobalStateClass
      def call () {
       println "Old Values: ${ GlobalStateClass.instance.version } ${ state.version }"
       String v = env.BUILD_TAG
       GlobalState.instance.version = v
       state.version = v
       println "New Values: ${ GlobalStateClass.instance.version } ${ state.version }"
      }
      

       

      Jenkinsfile

      pipeline {
       agent any
       stages {
         stage('test 0'){
           main()
         }
         stage('test 1'){
           main()
         }
         stage('test 2'){
           main()
         }
         stage('test 3'){
           main()
         }
       }
      }

            Unassigned Unassigned
            lemonygoodness Brandon Snuggs
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: