Select Page

What mean @NonCPS annotation in Jenkins pipeline

CPS – Continuation-passing style. Style of programming in which code execution in the form of a continuation, waterfall style. Usually, execution pipeline code with a hard and complex logic occur some error, like NotSerializableException. Pipeline restricts all variables to Serializable types. Basically in CPS style functions will never return any value. This is a groovy CPS library .  So what is Serializable type mean?

Serialization – it’s a process of translating data structure or objects to a different format. Also that can be more effective, better or simpler for storage in memory buffer or transmitted and reconstructed later. Best practices for Pipeline code says keeping Pipeline logic simple, that helps avoid a NotSerializableException.

This is list of Serializable Types in Jenkins Pipelines:

  1. Primitive common types like byte, int, double, short, char etc.
  2. Strings
  3. enums
  4. Arrays of serializable types
  5. ArrayLists and normal Groovy Lists
  6. Sets: HashSet
  7. Maps: normal Groovy Map, HashMap, TreeMap
  8. Exceptions
  9. URLs
  10. DatesRegex Patterns (compiled patterns

This is list of Non-Serializable Types and only allows with @NonCPS:

  1. Iterators: this is a common problem. You need to use C-style loop, i.e. for(int i=0; i<max; i++){
  2. Regex Matchers (you can use the built-in functions in String, etc, just not the Matcher itself)
  3. Important: JsonObjectJsonSlurper, etc in Groovy 2+ (used in some 2.x+ versions of Jenkins).

Use @NonCPS annotated functions for slightly more complex work. Basically need to use @NonCPS annotation when you got a not serializable types like some Xml objects. But the way using this method CPU cost may be more than usual. Also @NonCPS annotation allows to use more Groovy methods and features.

But you should understand that @NonCPS annotation not guaranteed that stage not generate error again. Maybe you’ll see new, more imported exception.