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
@NonCPSmethod that returns plainString/List/Map. - Use serializable alternatives:
readJSONinstead ofJsonSlurper,findAllinstead ofmatcherloops.
More on Scripted pipeline, Groovy & CPS
What does a scripted pipeline look like and when would you still write one?IntermediateWhat is CPS and why does Jenkins transform pipeline Groovy?AdvancedWhat does `@NonCPS` do and what are its rules?AdvancedWhy do some Groovy closures behave unexpectedly in pipelines, for example `list.each { }` or `sort`?AdvancedWhat is the `script` block in declarative, and what are its limits?BeginnerHow do you share a variable between stages in declarative?Intermediate