Why @NonCPS is not necessary here?

49 views
Skip to first unread message

Jo

unread,
Mar 16, 2024, 4:03:17 PMMar 16
to Jenkins Users
I've read following documents regarding on serializing local variables: https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md#serializing-local-variables

After reading, I try to test my understanding with an hands-on example like this:

pipeline {
  agent {
    node { label 'linux' }
  }
  stages {
    stage('1') {
      steps {
        script {
          def matcher = '123' =~ /^\d+$/
          if (matcher.matches()) {
            sh "echo \"it is a number!:  ${matcher[0]}\""
          }
        }
      }
    }
  }
}

If I understood correctly, one way to fix the issue here is to introduce a method annotated with @NonCPS:

pipeline {
  agent {
    node { label 'linux' }
  }
  stages {
    stage('1') {
      steps {
        script {
          def number = tryGetNumber('123')
          if (number) {
            sh "echo \"it is a number!:  ${number}\""
          }
        }
      }
    }
  }
}
 
@NonCPS // commenting this line also works!?
def tryGetNumber(text) {
  def matcher = text =~ /^\d+$/
  if (matcher.matches()) {
    return matcher[0]
  }
  return null
}

This last example code works without @NonCPS annotation
I've tried similar other non-serializable-local-variable cases, but all worked without @NonCPS annotation. Only introducing a method is suffice to fix the issue.

I'm not sure if I misread the documents. When should @NonCPS be used? Is it only for performance improvement? (so that non-necessary local variables not written to disk)
Reply all
Reply to author
Forward
0 new messages