Interview Prep/Jenkins/Scripted pipeline, Groovy & CPS

Why does `java.io.NotSerializableException` happen in pipelines?

AdvancedConceptScripted pipeline, Groovy & CPS
Answer

At each step boundary, CPS serializes the program state. If a local variable holds an object that does not implement Serializable (such as java.util.regex.Matcher, groovy.json.internal.LazyMap, an Iterator, an HTTP connection), serialization fails. Fixes:

  • Do not keep such objects across a step: compute, extract plain values, and null the variable.
  • Move the logic into a @NonCPS method that returns plain String/List/Map.
  • Use serializable alternatives: readJSON instead of JsonSlurper, findAll instead of matcher loops.
All Jenkins questions Roadmap: Jenkins

More on Scripted pipeline, Groovy & CPS