From b9bb52ffce51f30ad3265a8cea9dbbab66cf8fb9 Mon Sep 17 00:00:00 2001 From: Baptiste Mathus Date: Tue, 10 May 2016 06:56:26 +0200 Subject: [PATCH] Switch Jenkins.getInstance() to @Nonnull (#2297) As detailed by @stephenc: > So there is `getInstanceOrNull()` which is for use in Jenkins core or > in code that plugins add that may escape the Jenkins singleton > lifecycle. > > In regular plugins `getInstance()` will never return null as the > lifecycle does not instantiate them until after there is a Jenkins > singleton and the plugins will be stopped before there is no > singleton. > > The `getActiveInstance()` is therefore equivalent to `getInstance()` > and should never have been born. > > The only way a plugin can get a `null` from `Jenkins.getInstance()` is > if you install an `atExit()` handler, use a `PhantomReference` type > thing, or directly manipulate the servlet container in some way or > other. A correctly written plugin should unwind any of those things > when it is stopped or a method bound to the termination lifecycle. If > there are some cases (for which I cannot anticipate a good coder being > able to write a correct termination lifecycle method to fix) where the > code cannot be unhooked... then in those cases the plugin should use > `getInstanceOrNull()` and know how to respond to the `null` that could > not be avoided. --- core/src/main/java/jenkins/model/Jenkins.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/jenkins/model/Jenkins.java b/core/src/main/java/jenkins/model/Jenkins.java index 1517f82bfc..c503b58891 100644 --- a/core/src/main/java/jenkins/model/Jenkins.java +++ b/core/src/main/java/jenkins/model/Jenkins.java @@ -754,10 +754,17 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve * @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down */ @CLIResolver - @Nullable // TODO replace with non-null once Jenkins 2.0+ + @Nonnull public static Jenkins getInstance() { - // TODO throw an IllegalStateException in Jenkins 2.0+ - return HOLDER.getInstance(); + Jenkins instance = HOLDER.getInstance(); + if (instance == null) { + if(!Boolean.getBoolean(Jenkins.class.getName()+".disableExceptionOnNullInstance")) { + // TODO: remove that second block around 2.20 (that is: ~20 versions to battle test it) + // See https://github.com/jenkinsci/jenkins/pull/2297#issuecomment-216710150 + throw new IllegalStateException("Jenkins has not been started, or was already shut down"); + } + } + return instance; } /** -- GitLab