This is an automated email from the ASF dual-hosted git repository.

remm pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 3a72dd77d52c70f6bfa8c0002bf93e6e74ff7d14
Author: remm <r...@apache.org>
AuthorDate: Sun Mar 16 22:31:21 2025 +0100

    Cleanups
---
 java/org/apache/catalina/Context.java              |  26 +++--
 java/org/apache/catalina/Host.java                 |   2 +-
 java/org/apache/catalina/Pipeline.java             |   4 +-
 java/org/apache/catalina/Realm.java                |   2 +-
 java/org/apache/catalina/Server.java               |   2 +-
 java/org/apache/catalina/Service.java              |   2 +-
 java/org/apache/catalina/WebResourceRoot.java      |   8 +-
 java/org/apache/catalina/Wrapper.java              |   2 +-
 .../catalina/authenticator/AuthenticatorBase.java  |   8 +-
 .../catalina/authenticator/BasicAuthenticator.java |   2 +-
 .../authenticator/DigestAuthenticator.java         |  14 +--
 .../catalina/authenticator/FormAuthenticator.java  |  10 +-
 .../catalina/authenticator/SSLAuthenticator.java   |   4 +-
 .../catalina/authenticator/SingleSignOn.java       |  12 +-
 .../authenticator/SingleSignOnSessionKey.java      |   9 +-
 .../authenticator/SpnegoAuthenticator.java         |   6 +-
 .../jaspic/AuthConfigFactoryImpl.java              |  12 +-
 .../authenticator/jaspic/CallbackHandlerImpl.java  |   2 +-
 .../jaspic/SimpleServerAuthConfig.java             |   8 +-
 java/org/apache/catalina/connector/Request.java    |  16 +--
 java/org/apache/catalina/core/ContainerBase.java   |   2 +-
 java/org/apache/catalina/core/StandardContext.java |  26 ++---
 .../apache/catalina/manager/ManagerServlet.java    |   2 +-
 .../webresources/AbstractArchiveResource.java      |   2 +-
 .../webresources/AbstractArchiveResourceSet.java   |  12 +-
 .../webresources/AbstractFileResourceSet.java      |   9 +-
 .../catalina/webresources/AbstractResourceSet.java |   2 +-
 java/org/apache/catalina/webresources/Cache.java   |  16 ++-
 .../catalina/webresources/CachedResource.java      |   2 +-
 .../catalina/webresources/DirResourceSet.java      |  21 ++--
 .../catalina/webresources/ExtractingRoot.java      |   3 +-
 .../catalina/webresources/FileResourceSet.java     |   4 +-
 .../apache/catalina/webresources/StandardRoot.java |  42 +++----
 java/org/apache/coyote/AbstractProcessorLight.java |   2 +-
 java/org/apache/coyote/AbstractProtocol.java       |  12 +-
 java/org/apache/coyote/CompressionConfig.java      |  66 +++++------
 java/org/apache/coyote/Request.java                |  18 +--
 java/org/apache/coyote/Response.java               |  15 +--
 .../org/apache/coyote/ajp/AbstractAjpProtocol.java |   5 +-
 java/org/apache/coyote/ajp/AjpMessage.java         |   4 +-
 java/org/apache/coyote/ajp/AjpProcessor.java       | 125 ++++++++-------------
 .../coyote/http11/AbstractHttp11Protocol.java      |  11 +-
 .../apache/coyote/http11/Http11InputBuffer.java    |  31 ++---
 java/org/apache/coyote/http11/Http11Processor.java |  28 ++---
 .../coyote/http11/filters/BufferedInputFilter.java |   2 +-
 .../coyote/http11/filters/ChunkedInputFilter.java  |  10 +-
 .../coyote/http11/filters/IdentityInputFilter.java |   4 +-
 .../http11/filters/IdentityOutputFilter.java       |   2 +-
 .../http11/filters/SavedRequestInputFilter.java    |   2 +-
 .../coyote/http11/upgrade/UpgradeGroupInfo.java    |   8 +-
 .../http11/upgrade/UpgradeServletOutputStream.java |   8 +-
 .../coyote/http2/ConnectionSettingsBase.java       |  35 ++----
 java/org/apache/coyote/http2/FrameType.java        |  40 +++----
 java/org/apache/coyote/http2/HPackHuffman.java     |  18 ++-
 java/org/apache/coyote/http2/HpackDecoder.java     |   2 +-
 java/org/apache/coyote/http2/HpackEncoder.java     |  11 +-
 java/org/apache/coyote/http2/Http2AsyncParser.java |  13 +--
 .../coyote/http2/Http2AsyncUpgradeHandler.java     |   6 +-
 java/org/apache/coyote/http2/Http2Protocol.java    |  16 +--
 .../apache/coyote/http2/Http2UpgradeHandler.java   |  13 +--
 java/org/apache/coyote/http2/Setting.java          |  44 ++------
 java/org/apache/coyote/http2/Stream.java           |  23 ++--
 62 files changed, 345 insertions(+), 523 deletions(-)

diff --git a/java/org/apache/catalina/Context.java 
b/java/org/apache/catalina/Context.java
index 9cc19c5369..e542ccc7c4 100644
--- a/java/org/apache/catalina/Context.java
+++ b/java/org/apache/catalina/Context.java
@@ -131,7 +131,7 @@ public interface Context extends Container, ContextBind {
      *
      * @param listeners The set of instantiated listener objects.
      */
-    void setApplicationEventListeners(Object listeners[]);
+    void setApplicationEventListeners(Object[] listeners);
 
 
     /**
@@ -149,7 +149,7 @@ public interface Context extends Container, ContextBind {
      *
      * @param listeners The set of instantiated listener objects.
      */
-    void setApplicationLifecycleListeners(Object listeners[]);
+    void setApplicationLifecycleListeners(Object[] listeners);
 
 
     /**
@@ -952,19 +952,19 @@ public interface Context extends Container, ContextBind {
 
 
     /**
-     * @return the set of application listener class names configured for this 
application.
+     * @return the array of application listener class names configured for 
this application.
      */
     String[] findApplicationListeners();
 
 
     /**
-     * @return the set of application parameters for this application.
+     * @return the array of application parameters for this application.
      */
     ApplicationParameter[] findApplicationParameters();
 
 
     /**
-     * @return the set of security constraints for this web application. If 
there are none, a zero-length array is
+     * @return the array of security constraints for this web application. If 
there are none, a zero-length array is
      *             returned.
      */
     SecurityConstraint[] findConstraints();
@@ -991,7 +991,7 @@ public interface Context extends Container, ContextBind {
 
 
     /**
-     * @return the set of defined error pages for all specified error codes 
and exception types.
+     * @return the array of defined error pages for all specified error codes 
and exception types.
      */
     ErrorPage[] findErrorPages();
 
@@ -1005,13 +1005,13 @@ public interface Context extends Container, ContextBind 
{
 
 
     /**
-     * @return the set of defined filters for this Context.
+     * @return the array of defined filters for this Context.
      */
     FilterDef[] findFilterDefs();
 
 
     /**
-     * @return the set of filter mappings for this Context.
+     * @return the array of filter mappings for this Context.
      */
     FilterMap[] findFilterMaps();
 
@@ -1104,7 +1104,8 @@ public interface Context extends Container, ContextBind {
 
 
     /**
-     * @return the set of watched resources for this Context. If none are 
defined, a zero length array will be returned.
+     * @return the array of watched resources for this Context. If none are 
defined, a zero length array will be
+     * returned.
      */
     String[] findWatchedResources();
 
@@ -1119,19 +1120,20 @@ public interface Context extends Container, ContextBind 
{
 
 
     /**
-     * @return the set of welcome files defined for this Context. If none are 
defined, a zero-length array is returned.
+     * @return the array of welcome files defined for this Context. If none 
are defined, a zero-length array is
+     * returned.
      */
     String[] findWelcomeFiles();
 
 
     /**
-     * @return the set of LifecycleListener classes that will be added to 
newly created Wrappers automatically.
+     * @return the array of LifecycleListener classes that will be added to 
newly created Wrappers automatically.
      */
     String[] findWrapperLifecycles();
 
 
     /**
-     * @return the set of ContainerListener classes that will be added to 
newly created Wrappers automatically.
+     * @return the array of ContainerListener classes that will be added to 
newly created Wrappers automatically.
      */
     String[] findWrapperListeners();
 
diff --git a/java/org/apache/catalina/Host.java 
b/java/org/apache/catalina/Host.java
index d8ed79369e..321875a8cf 100644
--- a/java/org/apache/catalina/Host.java
+++ b/java/org/apache/catalina/Host.java
@@ -243,7 +243,7 @@ public interface Host extends Container {
 
 
     /**
-     * @return the set of alias names for this Host. If none are defined, a 
zero length array is returned.
+     * @return the array of alias names for this Host. If none are defined, a 
zero length array is returned.
      */
     String[] findAliases();
 
diff --git a/java/org/apache/catalina/Pipeline.java 
b/java/org/apache/catalina/Pipeline.java
index 57afd26ac8..9036fca7a9 100644
--- a/java/org/apache/catalina/Pipeline.java
+++ b/java/org/apache/catalina/Pipeline.java
@@ -80,8 +80,8 @@ public interface Pipeline extends Contained {
 
 
     /**
-     * @return the set of Valves in the pipeline associated with this 
Container, including the basic Valve (if any). If
-     *             there are no such Valves, a zero-length array is returned.
+     * @return the array of Valves in the pipeline associated with this 
Container, including the basic Valve (if any).
+     *   If there are no such Valves, a zero-length array is returned.
      */
     Valve[] getValves();
 
diff --git a/java/org/apache/catalina/Realm.java 
b/java/org/apache/catalina/Realm.java
index af7a108be2..2528442db4 100644
--- a/java/org/apache/catalina/Realm.java
+++ b/java/org/apache/catalina/Realm.java
@@ -131,7 +131,7 @@ public interface Realm extends Contained {
      *
      * @return the associated principal, or {@code null} if there is none
      */
-    Principal authenticate(X509Certificate certs[]);
+    Principal authenticate(X509Certificate[] certs);
 
 
     /**
diff --git a/java/org/apache/catalina/Server.java 
b/java/org/apache/catalina/Server.java
index 3c3a248ec6..dd64b019bf 100644
--- a/java/org/apache/catalina/Server.java
+++ b/java/org/apache/catalina/Server.java
@@ -231,7 +231,7 @@ public interface Server extends Lifecycle {
 
 
     /**
-     * @return the set of Services defined within this Server.
+     * @return the array of Services defined within this Server.
      */
     Service[] findServices();
 
diff --git a/java/org/apache/catalina/Service.java 
b/java/org/apache/catalina/Service.java
index 04a2e594fa..8eb1888581 100644
--- a/java/org/apache/catalina/Service.java
+++ b/java/org/apache/catalina/Service.java
@@ -101,7 +101,7 @@ public interface Service extends Lifecycle {
     /**
      * Find and return the set of Connectors associated with this Service.
      *
-     * @return the set of associated Connectors
+     * @return the array of associated Connectors
      */
     Connector[] findConnectors();
 
diff --git a/java/org/apache/catalina/WebResourceRoot.java 
b/java/org/apache/catalina/WebResourceRoot.java
index b99874ee3f..d2a9a34423 100644
--- a/java/org/apache/catalina/WebResourceRoot.java
+++ b/java/org/apache/catalina/WebResourceRoot.java
@@ -205,7 +205,7 @@ public interface WebResourceRoot extends Lifecycle {
     void addPreResources(WebResourceSet webResourceSet);
 
     /**
-     * @return the list of WebResourceSet configured to this web application 
as a 'Pre' resource.
+     * @return the array of WebResourceSet configured to this web application 
as a 'Pre' resource.
      */
     WebResourceSet[] getPreResources();
 
@@ -217,7 +217,7 @@ public interface WebResourceRoot extends Lifecycle {
     void addJarResources(WebResourceSet webResourceSet);
 
     /**
-     * @return the list of WebResourceSet configured to this web application 
as a 'Jar' resource.
+     * @return the array of WebResourceSet configured to this web application 
as a 'Jar' resource.
      */
     WebResourceSet[] getJarResources();
 
@@ -229,7 +229,7 @@ public interface WebResourceRoot extends Lifecycle {
     void addPostResources(WebResourceSet webResourceSet);
 
     /**
-     * @return the list of WebResourceSet configured to this web application 
as a 'Post' resource.
+     * @return the array of WebResourceSet configured to this web application 
as a 'Post' resource.
      */
     WebResourceSet[] getPostResources();
 
@@ -380,7 +380,7 @@ public interface WebResourceRoot extends Lifecycle {
     void deregisterTrackedResource(TrackedWebResource trackedResource);
 
     /**
-     * @return the set of {@link WebResourceSet#getBaseUrl()} for all {@link 
WebResourceSet}s used by this root.
+     * @return the list of {@link WebResourceSet#getBaseUrl()} for all {@link 
WebResourceSet}s used by this root.
      */
     List<URL> getBaseUrls();
 
diff --git a/java/org/apache/catalina/Wrapper.java 
b/java/org/apache/catalina/Wrapper.java
index 63e4dcf7a0..275649de8a 100644
--- a/java/org/apache/catalina/Wrapper.java
+++ b/java/org/apache/catalina/Wrapper.java
@@ -226,7 +226,7 @@ public interface Wrapper extends Container {
 
 
     /**
-     * @return the set of security role reference names associated with this 
servlet, if any; otherwise return a
+     * @return the array of security role reference names associated with this 
servlet, if any; otherwise return a
      *             zero-length array.
      */
     String[] findSecurityReferences();
diff --git a/java/org/apache/catalina/authenticator/AuthenticatorBase.java 
b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
index db467ba4e9..9cc82f3c56 100644
--- a/java/org/apache/catalina/authenticator/AuthenticatorBase.java
+++ b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
@@ -721,7 +721,7 @@ public abstract class AuthenticatorBase extends ValveBase 
implements Authenticat
 
 
     private CallbackHandler createCallbackHandler() {
-        CallbackHandler callbackHandler = null;
+        CallbackHandler callbackHandler;
 
         Class<?> clazz = null;
         try {
@@ -822,7 +822,7 @@ public abstract class AuthenticatorBase extends ValveBase 
implements Authenticat
                 if (requirePrincipal) {
                     return false;
                 }
-            } else if (cachedAuth == false || 
!principal.getUserPrincipal().equals(request.getUserPrincipal())) {
+            } else if (!cachedAuth || 
!principal.getUserPrincipal().equals(request.getUserPrincipal())) {
                 // Skip registration if authentication credentials were
                 // cached and the Principal did not change.
 
@@ -936,7 +936,7 @@ public abstract class AuthenticatorBase extends ValveBase 
implements Authenticat
                     authorized = new GenericPrincipal(username);
                 }
                 String authType = request.getAuthType();
-                if (authType == null || authType.length() == 0) {
+                if (authType == null || authType.isEmpty()) {
                     authType = getAuthMethod();
                 }
                 register(request, response, authorized, authType, username, 
null);
@@ -1208,7 +1208,7 @@ public abstract class AuthenticatorBase extends ValveBase 
implements Authenticat
         // path, if there is one
         Container parent = context.getParent();
         while ((sso == null) && (parent != null)) {
-            Valve valves[] = parent.getPipeline().getValves();
+            Valve[] valves = parent.getPipeline().getValves();
             for (Valve valve : valves) {
                 if (valve instanceof SingleSignOn) {
                     sso = (SingleSignOn) valve;
diff --git a/java/org/apache/catalina/authenticator/BasicAuthenticator.java 
b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
index 9d8151850e..2f62ca7965 100644
--- a/java/org/apache/catalina/authenticator/BasicAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
@@ -76,7 +76,7 @@ public class BasicAuthenticator extends AuthenticatorBase {
         if (authorization != null) {
             authorization.toBytes();
             ByteChunk authorizationBC = authorization.getByteChunk();
-            BasicCredentials credentials = null;
+            BasicCredentials credentials;
             try {
                 credentials = new BasicCredentials(authorizationBC, charset);
                 String username = credentials.getUsername();
diff --git a/java/org/apache/catalina/authenticator/DigestAuthenticator.java 
b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
index 0ce23324e9..5e1c529ebf 100644
--- a/java/org/apache/catalina/authenticator/DigestAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
@@ -208,7 +208,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
 
     public String getAlgorithms() {
         StringBuilder result = new StringBuilder();
-        StringUtils.join(algorithms, ',', (x) -> x.getRfcName(), result);
+        StringUtils.join(algorithms, ',', AuthDigest::getRfcName, result);
         return result.toString();
     }
 
@@ -462,7 +462,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
         private final long nonceValidity;
         private final String key;
         private final Map<String,NonceInfo> nonces;
-        private boolean validateUri = true;
+        private final boolean validateUri;
 
         private String userName = null;
         private String method = null;
@@ -555,7 +555,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
                         absolute.append("://");
                         absolute.append(host);
                         absolute.append(uriQuery);
-                        if (!uri.equals(absolute.toString())) {
+                        if (!uri.contentEquals(absolute)) {
                             return false;
                         }
                     } else {
@@ -645,11 +645,7 @@ public class DigestAuthenticator extends AuthenticatorBase 
{
             }
 
             // Validate algorithm is one of the algorithms configured for the 
authenticator
-            if (!algorithms.contains(algorithm)) {
-                return false;
-            }
-
-            return true;
+            return algorithms.contains(algorithm);
         }
 
         public boolean isNonceStale() {
@@ -671,7 +667,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
 
     public static class NonceInfo {
         private final long timestamp;
-        private final boolean seen[];
+        private final boolean[] seen;
         private final int offset;
         private int count = 0;
 
diff --git a/java/org/apache/catalina/authenticator/FormAuthenticator.java 
b/java/org/apache/catalina/authenticator/FormAuthenticator.java
index 62421d24b2..8af1393872 100644
--- a/java/org/apache/catalina/authenticator/FormAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/FormAuthenticator.java
@@ -159,7 +159,7 @@ public class FormAuthenticator extends AuthenticatorBase {
 
         // References to objects we will need later
         Session session = null;
-        Principal principal = null;
+        Principal principal;
 
         // Have we authenticated this user before but have caching disabled?
         if (!cache) {
@@ -227,7 +227,7 @@ public class FormAuthenticator extends AuthenticatorBase {
             // If this request was to the root of the context without a 
trailing
             // '/', need to redirect to add it else the submit of the login 
form
             // may not go to the correct web application
-            if (request.getServletPath().length() == 0 && 
request.getPathInfo() == null) {
+            if (request.getServletPath().isEmpty() && request.getPathInfo() == 
null) {
                 StringBuilder location = new StringBuilder(requestURI);
                 location.append('/');
                 if (request.getQueryString() != null) {
@@ -424,7 +424,7 @@ public class FormAuthenticator extends AuthenticatorBase {
         }
 
         String loginPage = config.getLoginPage();
-        if (loginPage == null || loginPage.length() == 0) {
+        if (loginPage == null || loginPage.isEmpty()) {
             String msg = sm.getString("formAuthenticator.noLoginPage", 
context.getName());
             log.warn(msg);
             response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 
msg);
@@ -480,7 +480,7 @@ public class FormAuthenticator extends AuthenticatorBase {
             throws IOException {
 
         String errorPage = config.getErrorPage();
-        if (errorPage == null || errorPage.length() == 0) {
+        if (errorPage == null || errorPage.isEmpty()) {
             String msg = sm.getString("formAuthenticator.noErrorPage", 
context.getName());
             log.warn(msg);
             response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 
msg);
@@ -663,7 +663,7 @@ public class FormAuthenticator extends AuthenticatorBase {
 
         // Create and populate a SavedRequest object for this request
         SavedRequest saved = new SavedRequest();
-        Cookie cookies[] = request.getCookies();
+        Cookie[] cookies = request.getCookies();
         if (cookies != null) {
             for (Cookie cookie : cookies) {
                 saved.addCookie(cookie);
diff --git a/java/org/apache/catalina/authenticator/SSLAuthenticator.java 
b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
index b3df81c9ed..61564a3094 100644
--- a/java/org/apache/catalina/authenticator/SSLAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
@@ -77,7 +77,7 @@ public class SSLAuthenticator extends AuthenticatorBase {
             containerLog.trace(" Looking up certificates");
         }
 
-        X509Certificate certs[] = getRequestCertificates(request);
+        X509Certificate[] certs = getRequestCertificates(request);
 
         if ((certs == null) || (certs.length < 1)) {
             if (containerLog.isDebugEnabled()) {
@@ -128,7 +128,7 @@ public class SSLAuthenticator extends AuthenticatorBase {
      */
     protected X509Certificate[] getRequestCertificates(final Request request) 
throws IllegalStateException {
 
-        X509Certificate certs[] = (X509Certificate[]) 
request.getAttribute(Globals.CERTIFICATES_ATTR);
+        X509Certificate[] certs = (X509Certificate[]) 
request.getAttribute(Globals.CERTIFICATES_ATTR);
 
         if ((certs == null) || (certs.length < 1)) {
             try {
diff --git a/java/org/apache/catalina/authenticator/SingleSignOn.java 
b/java/org/apache/catalina/authenticator/SingleSignOn.java
index 813b37eea9..11f079d467 100644
--- a/java/org/apache/catalina/authenticator/SingleSignOn.java
+++ b/java/org/apache/catalina/authenticator/SingleSignOn.java
@@ -112,7 +112,7 @@ public class SingleSignOn extends ValveBase {
      * @param cookieDomain cookie domain name
      */
     public void setCookieDomain(String cookieDomain) {
-        if (cookieDomain != null && cookieDomain.trim().length() == 0) {
+        if (cookieDomain != null && cookieDomain.trim().isEmpty()) {
             this.cookieDomain = null;
         } else {
             this.cookieDomain = cookieDomain;
@@ -225,7 +225,7 @@ public class SingleSignOn extends ValveBase {
             containerLog.trace(sm.getString("singleSignOn.debug.cookieCheck"));
         }
         Cookie cookie = null;
-        Cookie cookies[] = request.getCookies();
+        Cookie[] cookies = request.getCookies();
         if (cookies != null) {
             for (Cookie value : cookies) {
                 if (cookieName.equals(value.getName())) {
@@ -313,7 +313,7 @@ public class SingleSignOn extends ValveBase {
         // session was logged out, we'll log out of all session associated with
         // the SSO.
         if (((session.getMaxInactiveInterval() > 0) &&
-                (session.getIdleTimeInternal() >= 
session.getMaxInactiveInterval() * 1000)) ||
+                (session.getIdleTimeInternal() >= 
session.getMaxInactiveInterval() * 1000L)) ||
                 (!session.getManager().getContext().getState().isAvailable())) 
{
             if (containerLog.isDebugEnabled()) {
                 
containerLog.debug(sm.getString("singleSignOn.debug.sessionTimeout", ssoId, 
session));
@@ -384,7 +384,7 @@ public class SingleSignOn extends ValveBase {
 
         // Expire any associated sessions
         Set<SingleSignOnSessionKey> ssoKeys = sso.findSessions();
-        if (ssoKeys.size() == 0) {
+        if (ssoKeys.isEmpty()) {
             if (containerLog.isDebugEnabled()) {
                 
containerLog.debug(sm.getString("singleSignOn.debug.deregisterNone", ssoId));
             }
@@ -423,7 +423,7 @@ public class SingleSignOn extends ValveBase {
             
containerLog.warn(sm.getString("singleSignOn.sessionExpire.managerNotFound", 
key));
             return;
         }
-        Session session = null;
+        Session session;
         try {
             session = manager.findSession(key.getSessionId());
         } catch (IOException e) {
@@ -558,7 +558,7 @@ public class SingleSignOn extends ValveBase {
 
         // If there are not sessions left in the SingleSignOnEntry,
         // deregister the entry.
-        if (entry.findSessions().size() == 0) {
+        if (entry.findSessions().isEmpty()) {
             deregister(ssoId);
         }
     }
diff --git a/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java 
b/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
index 521f404781..b740594a71 100644
--- a/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
+++ b/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
@@ -90,13 +90,10 @@ public class SingleSignOnSessionKey implements Serializable 
{
             return false;
         }
         if (hostName == null) {
-            if (other.hostName != null) {
-                return false;
-            }
-        } else if (!hostName.equals(other.hostName)) {
-            return false;
+            return other.hostName == null;
+        } else {
+            return hostName.equals(other.hostName);
         }
-        return true;
     }
 
     @Override
diff --git a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java 
b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
index 9227238198..95840af6a7 100644
--- a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
@@ -86,7 +86,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
     }
 
     public void setNoKeepAliveUserAgents(String noKeepAliveUserAgents) {
-        if (noKeepAliveUserAgents == null || noKeepAliveUserAgents.length() == 
0) {
+        if (noKeepAliveUserAgents == null || noKeepAliveUserAgents.isEmpty()) {
             this.noKeepAliveUserAgents = null;
         } else {
             this.noKeepAliveUserAgents = 
Pattern.compile(noKeepAliveUserAgents);
@@ -184,8 +184,8 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
 
         LoginContext lc = null;
         GSSContext gssContext = null;
-        byte[] outToken = null;
-        Principal principal = null;
+        byte[] outToken;
+        Principal principal;
         try {
             try {
                 lc = new LoginContext(getLoginConfigName());
diff --git 
a/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java 
b/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java
index 81acb0c4e2..597c51fa31 100644
--- a/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java
+++ b/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java
@@ -62,7 +62,7 @@ public class AuthConfigFactoryImpl extends AuthConfigFactory {
 
     private static final String SERVLET_LAYER_ID = "HttpServlet";
 
-    private static String DEFAULT_REGISTRATION_ID = getRegistrationID(null, 
null);
+    private static final String DEFAULT_REGISTRATION_ID = 
getRegistrationID(null, null);
 
     private final Map<String,RegistrationContextImpl> 
layerAppContextRegistrations = new ConcurrentHashMap<>();
     private final Map<String,RegistrationContextImpl> appContextRegistrations 
= new ConcurrentHashMap<>();
@@ -122,7 +122,7 @@ public class AuthConfigFactoryImpl extends 
AuthConfigFactory {
     private AuthConfigProvider createAuthConfigProvider(String className, 
Map<String,String> properties)
             throws SecurityException {
         Class<?> clazz = null;
-        AuthConfigProvider provider = null;
+        AuthConfigProvider provider;
         try {
             clazz = Class.forName(className, true, 
Thread.currentThread().getContextClassLoader());
         } catch (ClassNotFoundException e) {
@@ -158,14 +158,14 @@ public class AuthConfigFactoryImpl extends 
AuthConfigFactory {
 
     private void addRegistrationContextImpl(String layer, String appContext, 
String registrationID,
             RegistrationContextImpl registrationContextImpl) {
-        RegistrationContextImpl previous = null;
+        RegistrationContextImpl previous;
 
         // Add the registration, noting any registration it replaces
         if (layer != null && appContext != null) {
             previous = layerAppContextRegistrations.put(registrationID, 
registrationContextImpl);
         } else if (layer == null && appContext != null) {
             previous = appContextRegistrations.put(registrationID, 
registrationContextImpl);
-        } else if (layer != null && appContext == null) {
+        } else if (layer != null) {
             previous = layerRegistrations.put(registrationID, 
registrationContextImpl);
         } else {
             previous = defaultRegistration.put(registrationID, 
registrationContextImpl);
@@ -360,10 +360,10 @@ public class AuthConfigFactoryImpl extends 
AuthConfigFactory {
 
 
     private static String getRegistrationID(String layer, String appContext) {
-        if (layer != null && layer.length() == 0) {
+        if (layer != null && layer.isEmpty()) {
             throw new 
IllegalArgumentException(sm.getString("authConfigFactoryImpl.zeroLengthMessageLayer"));
         }
-        if (appContext != null && appContext.length() == 0) {
+        if (appContext != null && appContext.isEmpty()) {
             throw new 
IllegalArgumentException(sm.getString("authConfigFactoryImpl.zeroLengthAppContext"));
         }
         return (layer == null ? "" : layer) + ":" + (appContext == null ? "" : 
appContext);
diff --git 
a/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java 
b/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
index afb0626eaf..17660ebe08 100644
--- a/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
+++ b/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
@@ -126,7 +126,7 @@ public class CallbackHandlerImpl implements 
CallbackHandler, Contained {
                             mergedRoles.addAll(Arrays.asList(groups));
                         }
 
-                        if (mergedRoles.size() == 0) {
+                        if (mergedRoles.isEmpty()) {
                             mergedRoles = Collections.emptyList();
                         }
 
diff --git 
a/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java 
b/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java
index 2c6cd51748..23d76a0240 100644
--- a/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java
+++ b/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java
@@ -39,7 +39,7 @@ import org.apache.tomcat.util.res.StringManager;
  */
 public class SimpleServerAuthConfig implements ServerAuthConfig {
 
-    private static StringManager sm = 
StringManager.getManager(SimpleServerAuthConfig.class);
+    private static final StringManager sm = 
StringManager.getManager(SimpleServerAuthConfig.class);
 
     private static final String SERVER_AUTH_MODULE_KEY_PREFIX =
             "org.apache.catalina.authenticator.jaspic.ServerAuthModule.";
@@ -116,9 +116,7 @@ public class SimpleServerAuthConfig implements 
ServerAuthConfig {
                             module.initialize(null, null, handler, 
mergedProperties);
                             modules.add(module);
                         } catch (ReflectiveOperationException | 
IllegalArgumentException | SecurityException e) {
-                            AuthException ae = new AuthException();
-                            ae.initCause(e);
-                            throw ae;
+                            throw new AuthException(e);
                         }
 
                         // Look for the next module
@@ -127,7 +125,7 @@ public class SimpleServerAuthConfig implements 
ServerAuthConfig {
                         moduleClassName = mergedProperties.get(key);
                     }
 
-                    if (modules.size() == 0) {
+                    if (modules.isEmpty()) {
                         throw new 
AuthException(sm.getString("simpleServerAuthConfig.noModules"));
                     }
 
diff --git a/java/org/apache/catalina/connector/Request.java 
b/java/org/apache/catalina/connector/Request.java
index a53f7bc719..8692695993 100644
--- a/java/org/apache/catalina/connector/Request.java
+++ b/java/org/apache/catalina/connector/Request.java
@@ -1036,7 +1036,7 @@ public class Request implements HttpServletRequest {
         }
 
         if (!locales.isEmpty()) {
-            return locales.get(0);
+            return locales.getFirst();
         }
 
         return defaultLocale;
@@ -1827,7 +1827,7 @@ public class Request implements HttpServletRequest {
             // is the protocol that must have been selected
             List<Upgrade> upgradeProtocols = 
Upgrade.parse(getHeaders(HTTP_UPGRADE_HEADER_NAME));
             if (upgradeProtocols != null && upgradeProtocols.size() == 1) {
-                result = upgradeProtocols.get(0).toString();
+                result = upgradeProtocols.getFirst().toString();
             }
         }
 
@@ -2413,12 +2413,12 @@ public class Request implements HttpServletRequest {
         parseParts();
 
         if (partsParseException != null) {
-            if (partsParseException instanceof IOException) {
-                throw (IOException) partsParseException;
-            } else if (partsParseException instanceof IllegalStateException) {
-                throw (IllegalStateException) partsParseException;
-            } else if (partsParseException instanceof ServletException) {
-                throw (ServletException) partsParseException;
+            switch (partsParseException) {
+                case IOException ioException -> throw ioException;
+                case IllegalStateException illegalStateException -> throw 
illegalStateException;
+                case ServletException servletException -> throw 
servletException;
+                default -> {
+                }
             }
         }
 
diff --git a/java/org/apache/catalina/core/ContainerBase.java 
b/java/org/apache/catalina/core/ContainerBase.java
index 6711a60e01..9b337db5a8 100644
--- a/java/org/apache/catalina/core/ContainerBase.java
+++ b/java/org/apache/catalina/core/ContainerBase.java
@@ -1016,7 +1016,7 @@ public abstract class ContainerBase extends 
LifecycleMBeanBase implements Contai
             } else if (c == null) {
                 // May happen in unit testing and/or some embedding scenarios
                 keyProperties.append(",container");
-                keyProperties.append(containerCount++);
+                keyProperties.append(containerCount);
                 keyProperties.append("=null");
                 break;
             } else {
diff --git a/java/org/apache/catalina/core/StandardContext.java 
b/java/org/apache/catalina/core/StandardContext.java
index 74db0aa354..fc959a481f 100644
--- a/java/org/apache/catalina/core/StandardContext.java
+++ b/java/org/apache/catalina/core/StandardContext.java
@@ -3865,9 +3865,9 @@ public class StandardContext extends ContainerBase 
implements Context, Notificat
                     ApplicationFilterConfig filterConfig = new 
ApplicationFilterConfig(this, entry.getValue());
                     filterConfigs.put(name, filterConfig);
                 } catch (Throwable t) {
-                    t = ExceptionUtils.unwrapInvocationTargetException(t);
-                    ExceptionUtils.handleThrowable(t);
-                    
getLogger().error(sm.getString("standardContext.filterStart", name), t);
+                    Throwable throwable = 
ExceptionUtils.unwrapInvocationTargetException(t);
+                    ExceptionUtils.handleThrowable(throwable);
+                    
getLogger().error(sm.getString("standardContext.filterStart", name), throwable);
                     ok = false;
                 }
             }
@@ -3942,9 +3942,9 @@ public class StandardContext extends ContainerBase 
implements Context, Notificat
                 String listener = listeners[i];
                 results[i] = getInstanceManager().newInstance(listener);
             } catch (Throwable t) {
-                t = ExceptionUtils.unwrapInvocationTargetException(t);
-                ExceptionUtils.handleThrowable(t);
-                
getLogger().error(sm.getString("standardContext.applicationListener", 
listeners[i]), t);
+                Throwable throwable = 
ExceptionUtils.unwrapInvocationTargetException(t);
+                ExceptionUtils.handleThrowable(throwable);
+                
getLogger().error(sm.getString("standardContext.applicationListener", 
listeners[i]), throwable);
                 ok = false;
             }
         }
@@ -4075,10 +4075,10 @@ public class StandardContext extends ContainerBase 
implements Context, Notificat
                         getInstanceManager().destroyInstance(listeners[j]);
                     }
                 } catch (Throwable t) {
-                    t = ExceptionUtils.unwrapInvocationTargetException(t);
-                    ExceptionUtils.handleThrowable(t);
+                    Throwable throwable = 
ExceptionUtils.unwrapInvocationTargetException(t);
+                    ExceptionUtils.handleThrowable(throwable);
                     
getLogger().error(sm.getString("standardContext.listenerStop", 
listeners[j].getClass().getName()),
-                            t);
+                        throwable);
                     ok = false;
                 }
             }
@@ -4097,10 +4097,10 @@ public class StandardContext extends ContainerBase 
implements Context, Notificat
                         getInstanceManager().destroyInstance(listeners[j]);
                     }
                 } catch (Throwable t) {
-                    t = ExceptionUtils.unwrapInvocationTargetException(t);
-                    ExceptionUtils.handleThrowable(t);
+                    Throwable throwable = 
ExceptionUtils.unwrapInvocationTargetException(t);
+                    ExceptionUtils.handleThrowable(throwable);
                     
getLogger().error(sm.getString("standardContext.listenerStop", 
listeners[j].getClass().getName()),
-                            t);
+                        throwable);
                     ok = false;
                 }
             }
@@ -5308,7 +5308,7 @@ public class StandardContext extends ContainerBase 
implements Context, Notificat
         // Create this directory if necessary
         File dir = new File(workDir);
         if (!dir.isAbsolute()) {
-            String catalinaHomePath = null;
+            String catalinaHomePath;
             try {
                 catalinaHomePath = getCatalinaBase().getCanonicalPath();
                 dir = new File(catalinaHomePath, workDir);
diff --git a/java/org/apache/catalina/manager/ManagerServlet.java 
b/java/org/apache/catalina/manager/ManagerServlet.java
index ac06110600..625b53c82c 100644
--- a/java/org/apache/catalina/manager/ManagerServlet.java
+++ b/java/org/apache/catalina/manager/ManagerServlet.java
@@ -976,7 +976,7 @@ public class ManagerServlet extends HttpServlet implements 
ContainerServlet {
                 if (displayPath.isEmpty()) {
                     displayPath = "/";
                 }
-                List<String> parts = null;
+                List<String> parts;
                 if (context.getState().isAvailable()) {
                     parts = Arrays.asList(displayPath, "running", "" + 
context.getManager().findSessions().length,
                             context.getDocBase());
diff --git a/java/org/apache/catalina/webresources/AbstractArchiveResource.java 
b/java/org/apache/catalina/webresources/AbstractArchiveResource.java
index 657fd7522d..f7e2914dec 100644
--- a/java/org/apache/catalina/webresources/AbstractArchiveResource.java
+++ b/java/org/apache/catalina/webresources/AbstractArchiveResource.java
@@ -68,7 +68,7 @@ public abstract class AbstractArchiveResource extends 
AbstractResource {
             resourceName = resourceName.substring(0, resourceName.length() - 
1);
         }
         String internalPath = archiveResourceSet.getInternalPath();
-        if (internalPath.length() > 0 && 
resourceName.equals(internalPath.subSequence(1, internalPath.length()))) {
+        if (!internalPath.isEmpty() && 
resourceName.contentEquals(internalPath.subSequence(1, internalPath.length()))) 
{
             name = "";
         } else {
             int index = resourceName.lastIndexOf('/');
diff --git 
a/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java 
b/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java
index d5551522f5..0644a8c3d0 100644
--- a/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java
+++ b/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java
@@ -71,7 +71,7 @@ public abstract class AbstractArchiveResourceSet extends 
AbstractResourceSet {
         if (path.startsWith(webAppMount)) {
             String pathInJar = getInternalPath() + 
path.substring(webAppMount.length());
             // Always strip off the leading '/' to get the JAR path
-            if (pathInJar.length() > 0 && pathInJar.charAt(0) == '/') {
+            if (!pathInJar.isEmpty() && pathInJar.charAt(0) == '/') {
                 pathInJar = pathInJar.substring(1);
             }
             for (String name : getArchiveEntries(false).keySet()) {
@@ -81,13 +81,13 @@ public abstract class AbstractArchiveResourceSet extends 
AbstractResourceSet {
                     } else {
                         name = name.substring(pathInJar.length());
                     }
-                    if (name.length() == 0) {
+                    if (name.isEmpty()) {
                         continue;
                     }
                     if (name.charAt(0) == '/') {
                         name = name.substring(1);
                     }
-                    if (name.length() > 0 && name.lastIndexOf('/') == -1) {
+                    if (!name.isEmpty() && name.lastIndexOf('/') == -1) {
                         result.add(name);
                     }
                 }
@@ -118,7 +118,7 @@ public abstract class AbstractArchiveResourceSet extends 
AbstractResourceSet {
             String pathInJar = getInternalPath() + 
path.substring(webAppMount.length());
             // Always strip off the leading '/' to get the JAR path and make
             // sure it ends in '/'
-            if (pathInJar.length() > 0) {
+            if (!pathInJar.isEmpty()) {
                 if (pathInJar.charAt(pathInJar.length() - 1) != '/') {
                     pathInJar = pathInJar.substring(1) + '/';
                 }
@@ -228,10 +228,10 @@ public abstract class AbstractArchiveResourceSet extends 
AbstractResourceSet {
         if (path.startsWith(webAppMount)) {
             String pathInJar = getInternalPath() + 
path.substring(webAppMount.length());
             // Always strip off the leading '/' to get the JAR path
-            if (pathInJar.length() > 0 && pathInJar.charAt(0) == '/') {
+            if (!pathInJar.isEmpty() && pathInJar.charAt(0) == '/') {
                 pathInJar = pathInJar.substring(1);
             }
-            if (pathInJar.equals("")) {
+            if (pathInJar.isEmpty()) {
                 // Special case
                 // This is a directory resource so the path must end with /
                 if (!path.endsWith("/")) {
diff --git a/java/org/apache/catalina/webresources/AbstractFileResourceSet.java 
b/java/org/apache/catalina/webresources/AbstractFileResourceSet.java
index f416f929cb..6ddc2da927 100644
--- a/java/org/apache/catalina/webresources/AbstractFileResourceSet.java
+++ b/java/org/apache/catalina/webresources/AbstractFileResourceSet.java
@@ -117,7 +117,7 @@ public abstract class AbstractFileResourceSet extends 
AbstractResourceSet {
         canPath = canPath.substring(canonicalBase.length());
 
         // The remaining request path must start with '/' if it has non-zero 
length
-        if (canPath.length() > 0 && canPath.charAt(0) != File.separatorChar) {
+        if (!canPath.isEmpty() && canPath.charAt(0) != File.separatorChar) {
             return null;
         }
 
@@ -132,7 +132,7 @@ public abstract class AbstractFileResourceSet extends 
AbstractResourceSet {
         //
         // absPath is normalized so canPath needs to be normalized as well
         // Can't normalize canPath earlier as canonicalBase is not normalized
-        if (canPath.length() > 0) {
+        if (!canPath.isEmpty()) {
             canPath = normalize(canPath);
         }
         if (!canPath.equals(absPath)) {
@@ -182,10 +182,7 @@ public abstract class AbstractFileResourceSet extends 
AbstractResourceSet {
         // level APIs are used to create the files that bypass various checks.
         // File names that end in ' ' are known to cause problems when using
         // File#getCanonicalPath().
-        if (name.charAt(len - 1) == ' ') {
-            return true;
-        }
-        return false;
+        return name.charAt(len - 1) == ' ';
     }
 
 
diff --git a/java/org/apache/catalina/webresources/AbstractResourceSet.java 
b/java/org/apache/catalina/webresources/AbstractResourceSet.java
index f139339848..bd7d0c55e7 100644
--- a/java/org/apache/catalina/webresources/AbstractResourceSet.java
+++ b/java/org/apache/catalina/webresources/AbstractResourceSet.java
@@ -40,7 +40,7 @@ public abstract class AbstractResourceSet extends 
LifecycleBase implements WebRe
 
 
     protected final void checkPath(String path) {
-        if (path == null || path.length() == 0 || path.charAt(0) != '/') {
+        if (path == null || path.isEmpty() || path.charAt(0) != '/') {
             throw new 
IllegalArgumentException(sm.getString("abstractResourceSet.checkPath", path));
         }
     }
diff --git a/java/org/apache/catalina/webresources/Cache.java 
b/java/org/apache/catalina/webresources/Cache.java
index ad41aaa983..ae85288fe8 100644
--- a/java/org/apache/catalina/webresources/Cache.java
+++ b/java/org/apache/catalina/webresources/Cache.java
@@ -49,8 +49,8 @@ public class Cache {
     private int objectMaxSize = (int) maxSize / OBJECT_MAX_SIZE_FACTOR;
     private CacheStrategy cacheStrategy;
 
-    private LongAdder lookupCount = new LongAdder();
-    private LongAdder hitCount = new LongAdder();
+    private final LongAdder lookupCount = new LongAdder();
+    private final LongAdder hitCount = new LongAdder();
 
     private final ConcurrentMap<String,CachedResource> resourceCache = new 
ConcurrentHashMap<>();
 
@@ -233,11 +233,8 @@ public class Cache {
     private boolean noCache(String path) {
         // Don't cache classes. The class loader handles this.
         // Don't cache JARs. The ResourceSet handles this.
-        if ((path.endsWith(".class") && (path.startsWith("/WEB-INF/classes/") 
|| path.startsWith("/WEB-INF/lib/"))) ||
-                (path.startsWith("/WEB-INF/lib/") && path.endsWith(".jar"))) {
-            return true;
-        }
-        return false;
+        return (path.endsWith(".class") && 
(path.startsWith("/WEB-INF/classes/") || path.startsWith("/WEB-INF/lib/"))) ||
+            (path.startsWith("/WEB-INF/lib/") && path.endsWith(".jar"));
     }
 
     private long evict(long targetSize, Iterator<CachedResource> iter) {
@@ -315,9 +312,10 @@ public class Cache {
         if (objectMaxSize * 1024L > Integer.MAX_VALUE) {
             log.warn(sm.getString("cache.objectMaxSizeTooBigBytes", 
Integer.valueOf(objectMaxSize)));
             this.objectMaxSize = Integer.MAX_VALUE;
+        } else {
+            // Internally bytes, externally kilobytes
+            this.objectMaxSize = objectMaxSize * 1024;
         }
-        // Internally bytes, externally kilobytes
-        this.objectMaxSize = objectMaxSize * 1024;
     }
 
     public int getObjectMaxSize() {
diff --git a/java/org/apache/catalina/webresources/CachedResource.java 
b/java/org/apache/catalina/webresources/CachedResource.java
index 7a729048dd..68f6b4c5c6 100644
--- a/java/org/apache/catalina/webresources/CachedResource.java
+++ b/java/org/apache/catalina/webresources/CachedResource.java
@@ -422,7 +422,7 @@ public class CachedResource implements WebResource {
         // Longer paths use a noticeable amount of memory so account for this 
in
         // the cache size. The fixed component of a String instance's memory
         // usage is accounted for in the 500 bytes above.
-        result += getWebappPath().length() * 2;
+        result += getWebappPath().length() * 2L;
         if (getContentLength() <= objectMaxSizeBytes) {
             result += getContentLength();
         }
diff --git a/java/org/apache/catalina/webresources/DirResourceSet.java 
b/java/org/apache/catalina/webresources/DirResourceSet.java
index 3e9676bdd3..ae98c7ace6 100644
--- a/java/org/apache/catalina/webresources/DirResourceSet.java
+++ b/java/org/apache/catalina/webresources/DirResourceSet.java
@@ -25,6 +25,7 @@ import java.nio.file.StandardCopyOption;
 import java.util.HashMap;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import java.util.jar.Manifest;
 
@@ -46,8 +47,8 @@ public class DirResourceSet extends AbstractFileResourceSet 
implements WebResour
 
     private static final Log log = LogFactory.getLog(DirResourceSet.class);
 
-    private Map<String,ResourceLock> resourceLocksByPath = new HashMap<>();
-    private Object resourceLocksByPathLock = new Object();
+    private final Map<String,ResourceLock> resourceLocksByPath = new 
HashMap<>();
+    private final Object resourceLocksByPathLock = new Object();
 
 
     /**
@@ -142,11 +143,7 @@ public class DirResourceSet extends 
AbstractFileResourceSet implements WebResour
                 return EMPTY_STRING_ARRAY;
             }
             String[] result = f.list();
-            if (result == null) {
-                return EMPTY_STRING_ARRAY;
-            } else {
-                return result;
-            }
+            return Objects.requireNonNullElse(result, EMPTY_STRING_ARRAY);
         } else {
             if (!path.endsWith("/")) {
                 path = path + "/";
@@ -276,7 +273,7 @@ public class DirResourceSet extends AbstractFileResourceSet 
implements WebResour
             return false;
         }
 
-        File dest = null;
+        File dest;
         /*
          * Lock the path for writing until the write is complete. The lock 
prevents concurrent reads and writes (e.g.
          * HTTP GET and PUT / DELETE) for the same path causing corruption of 
the FileResource where some of the fields
@@ -311,7 +308,7 @@ public class DirResourceSet extends AbstractFileResourceSet 
implements WebResour
 
     @Override
     protected void checkType(File file) {
-        if (file.isDirectory() == false) {
+        if (!file.isDirectory()) {
             throw new IllegalArgumentException(
                     sm.getString("dirResourceSet.notDirectory", getBase(), 
File.separator, getInternalPath()));
         }
@@ -322,7 +319,7 @@ public class DirResourceSet extends AbstractFileResourceSet 
implements WebResour
     protected void initInternal() throws LifecycleException {
         super.initInternal();
         // Is this an exploded web application?
-        if (getWebAppMount().equals("")) {
+        if (getWebAppMount().isEmpty()) {
             // Look for a manifest
             File mf = file("META-INF/MANIFEST.MF", true);
             if (mf != null && mf.isFile()) {
@@ -376,7 +373,7 @@ public class DirResourceSet extends AbstractFileResourceSet 
implements WebResour
     @Override
     public ResourceLock lockForRead(String path) {
         String key = getLockKey(path);
-        ResourceLock resourceLock = null;
+        ResourceLock resourceLock;
         synchronized (resourceLocksByPathLock) {
             /*
              * Obtain the ResourceLock and increment the usage count inside 
the sync to ensure that that map always has
@@ -414,7 +411,7 @@ public class DirResourceSet extends AbstractFileResourceSet 
implements WebResour
     @Override
     public ResourceLock lockForWrite(String path) {
         String key = getLockKey(path);
-        ResourceLock resourceLock = null;
+        ResourceLock resourceLock;
         synchronized (resourceLocksByPathLock) {
             /*
              * Obtain the ResourceLock and increment the usage count inside 
the sync to ensure that that map always has
diff --git a/java/org/apache/catalina/webresources/ExtractingRoot.java 
b/java/org/apache/catalina/webresources/ExtractingRoot.java
index fe9718664d..6b0c3f75eb 100644
--- a/java/org/apache/catalina/webresources/ExtractingRoot.java
+++ b/java/org/apache/catalina/webresources/ExtractingRoot.java
@@ -79,8 +79,7 @@ public class ExtractingRoot extends StandardRoot {
 
     private File getExpansionTarget() {
         File tmpDir = (File) 
getContext().getServletContext().getAttribute(ServletContext.TEMPDIR);
-        File expansionTarget = new File(tmpDir, APPLICATION_JARS_DIR);
-        return expansionTarget;
+        return new File(tmpDir, APPLICATION_JARS_DIR);
     }
 
 
diff --git a/java/org/apache/catalina/webresources/FileResourceSet.java 
b/java/org/apache/catalina/webresources/FileResourceSet.java
index 035e2f7a4e..93f0aab504 100644
--- a/java/org/apache/catalina/webresources/FileResourceSet.java
+++ b/java/org/apache/catalina/webresources/FileResourceSet.java
@@ -86,7 +86,7 @@ public class FileResourceSet extends AbstractFileResourceSet {
         if (webAppMount.startsWith(path)) {
             String name = path.substring(0, path.length() - 1);
             name = name.substring(name.lastIndexOf('/') + 1);
-            if (name.length() > 0) {
+            if (!name.isEmpty()) {
                 return new VirtualResource(root, path, name);
             }
         }
@@ -160,7 +160,7 @@ public class FileResourceSet extends 
AbstractFileResourceSet {
 
     @Override
     protected void checkType(File file) {
-        if (file.isFile() == false) {
+        if (!file.isFile()) {
             throw new IllegalArgumentException(
                     sm.getString("fileResourceSet.notFile", getBase(), 
File.separator, getInternalPath()));
         }
diff --git a/java/org/apache/catalina/webresources/StandardRoot.java 
b/java/org/apache/catalina/webresources/StandardRoot.java
index 7c5c08dbea..a5ab071c5d 100644
--- a/java/org/apache/catalina/webresources/StandardRoot.java
+++ b/java/org/apache/catalina/webresources/StandardRoot.java
@@ -147,7 +147,7 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
                 }
             }
         }
-        if (result.size() == 0) {
+        if (result.isEmpty()) {
             return null;
         }
         return result;
@@ -241,7 +241,7 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
             throw new 
IllegalStateException(sm.getString("standardRoot.checkStateNotStarted"));
         }
 
-        if (path == null || path.length() == 0 || !path.startsWith("/")) {
+        if (path == null || !path.startsWith("/")) {
             throw new 
IllegalArgumentException(sm.getString("standardRoot.invalidPath", path));
         }
 
@@ -255,7 +255,7 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
             // convert it to '/'
             result = RequestUtil.normalize(path, false);
         }
-        if (result == null || result.length() == 0 || !result.startsWith("/")) 
{
+        if (result == null || !result.startsWith("/")) {
             throw new 
IllegalArgumentException(sm.getString("standardRoot.invalidPathNormal", path, 
result));
         }
 
@@ -263,7 +263,7 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
     }
 
     protected final WebResource getResourceInternal(String path, boolean 
useClassLoaderResources) {
-        WebResource result = null;
+        WebResource result;
         WebResource virtual = null;
         WebResource mainEmpty = null;
         for (List<WebResourceSet> list : allResources) {
@@ -322,7 +322,7 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
             }
         }
 
-        if (result.size() == 0) {
+        if (result.isEmpty()) {
             result.add(main.getResource(path));
         }
 
@@ -367,22 +367,13 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
         List<WebResourceSet> resourceList;
         WebResourceSet resourceSet;
 
-        switch (type) {
-            case PRE:
-                resourceList = preResources;
-                break;
-            case CLASSES_JAR:
-                resourceList = classResources;
-                break;
-            case RESOURCE_JAR:
-                resourceList = jarResources;
-                break;
-            case POST:
-                resourceList = postResources;
-                break;
-            default:
-                throw new 
IllegalArgumentException(sm.getString("standardRoot.createUnknownType", type));
-        }
+        resourceList = switch (type) {
+            case PRE -> preResources;
+            case CLASSES_JAR -> classResources;
+            case RESOURCE_JAR -> jarResources;
+            case POST -> postResources;
+            default -> throw new 
IllegalArgumentException(sm.getString("standardRoot.createUnknownType", type));
+        };
 
         // This implementation assumes that the base for all resources will be 
a
         // file.
@@ -676,10 +667,7 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
 
     @Override
     protected String getObjectNameKeyProperties() {
-        StringBuilder keyProperties = new 
StringBuilder("type=WebResourceRoot");
-        keyProperties.append(context.getMBeanKeyProperties());
-
-        return keyProperties.toString();
+        return "type=WebResourceRoot" + context.getMBeanKeyProperties();
     }
 
     // --------------------------------------------------------------- 
Lifecycle
@@ -823,11 +811,11 @@ public class StandardRoot extends LifecycleMBeanBase 
implements WebResourceRoot
         private final String archivePath;
 
         BaseLocation(URL url) {
-            File f = null;
+            File f;
 
             if ("jar".equals(url.getProtocol()) || 
"war".equals(url.getProtocol())) {
                 String jarUrl = url.toString();
-                int endOfFileUrl = -1;
+                int endOfFileUrl;
                 if ("jar".equals(url.getProtocol())) {
                     endOfFileUrl = jarUrl.indexOf("!/");
                 } else {
diff --git a/java/org/apache/coyote/AbstractProcessorLight.java 
b/java/org/apache/coyote/AbstractProcessorLight.java
index 85b6944245..927d290a7c 100644
--- a/java/org/apache/coyote/AbstractProcessorLight.java
+++ b/java/org/apache/coyote/AbstractProcessorLight.java
@@ -33,7 +33,7 @@ import org.apache.tomcat.util.net.SocketWrapperBase;
  */
 public abstract class AbstractProcessorLight implements Processor {
 
-    private Set<DispatchType> dispatches = new CopyOnWriteArraySet<>();
+    private final Set<DispatchType> dispatches = new CopyOnWriteArraySet<>();
 
 
     @Override
diff --git a/java/org/apache/coyote/AbstractProtocol.java 
b/java/org/apache/coyote/AbstractProtocol.java
index 865167f35f..2d95e12a43 100644
--- a/java/org/apache/coyote/AbstractProtocol.java
+++ b/java/org/apache/coyote/AbstractProtocol.java
@@ -642,9 +642,7 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
         }
 
         endpoint.start();
-        monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(() -> {
-            startAsyncTimeout();
-        }, 0, 60, TimeUnit.SECONDS);
+        monitorFuture = 
getUtilityExecutor().scheduleWithFixedDelay(this::startAsyncTimeout, 0, 60, 
TimeUnit.SECONDS);
     }
 
 
@@ -853,7 +851,7 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
                     String negotiatedProtocol = 
wrapper.getNegotiatedProtocol();
                     // OpenSSL typically returns null whereas JSSE typically
                     // returns "" when no protocol is negotiated
-                    if (negotiatedProtocol != null && 
negotiatedProtocol.length() > 0) {
+                    if (negotiatedProtocol != null && 
!negotiatedProtocol.isEmpty()) {
                         UpgradeProtocol upgradeProtocol = 
getProtocol().getNegotiatedProtocol(negotiatedProtocol);
                         if (upgradeProtocol != null) {
                             processor = upgradeProtocol.getProcessor(wrapper, 
getProtocol().getAdapter());
@@ -900,7 +898,7 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
 
                 processor.setSslSupport(wrapper.getSslSupport());
 
-                SocketState state = SocketState.CLOSED;
+                SocketState state;
                 do {
                     state = processor.process(wrapper, status);
 
@@ -1006,7 +1004,7 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
                     // Connection closed. OK to recycle the processor.
                     // Processors handling upgrades require additional clean-up
                     // before release.
-                    if (processor != null && processor.isUpgrade()) {
+                    if (processor.isUpgrade()) {
                         UpgradeToken upgradeToken = 
processor.getUpgradeToken();
                         HttpUpgradeHandler httpUpgradeHandler = 
upgradeToken.getHttpUpgradeHandler();
                         InstanceManager instanceManager = 
upgradeToken.getInstanceManager();
@@ -1200,7 +1198,7 @@ public abstract class AbstractProtocol<S> implements 
ProtocolHandler, MBeanRegis
         @Override
         public boolean push(Processor processor) {
             int cacheSize = handler.getProtocol().getProcessorCache();
-            boolean offer = cacheSize == -1 ? true : size.get() < cacheSize;
+            boolean offer = cacheSize == -1 || size.get() < cacheSize;
             // avoid over growing our cache or add after we have stopped
             boolean result = false;
             if (offer) {
diff --git a/java/org/apache/coyote/CompressionConfig.java 
b/java/org/apache/coyote/CompressionConfig.java
index b32c18ef1c..76ce932e64 100644
--- a/java/org/apache/coyote/CompressionConfig.java
+++ b/java/org/apache/coyote/CompressionConfig.java
@@ -56,20 +56,19 @@ public class CompressionConfig {
      *                        in bytes which implies <code>on</code>
      */
     public void setCompression(String compression) {
-        if (compression.equals("on")) {
-            this.compressionLevel = 1;
-        } else if (compression.equals("force")) {
-            this.compressionLevel = 2;
-        } else if (compression.equals("off")) {
-            this.compressionLevel = 0;
-        } else {
-            try {
-                // Try to parse compression as an int, which would give the
-                // minimum compression size
-                setCompressionMinSize(Integer.parseInt(compression));
-                this.compressionLevel = 1;
-            } catch (Exception e) {
-                this.compressionLevel = 0;
+        switch (compression) {
+            case "on" -> this.compressionLevel = 1;
+            case "force" -> this.compressionLevel = 2;
+            case "off" -> this.compressionLevel = 0;
+            default -> {
+                try {
+                    // Try to parse compression as an int, which would give the
+                    // minimum compression size
+                    setCompressionMinSize(Integer.parseInt(compression));
+                    this.compressionLevel = 1;
+                } catch (Exception e) {
+                    this.compressionLevel = 0;
+                }
             }
         }
     }
@@ -81,15 +80,11 @@ public class CompressionConfig {
      * @return The current compression level in string form (off/on/force)
      */
     public String getCompression() {
-        switch (compressionLevel) {
-            case 0:
-                return "off";
-            case 1:
-                return "on";
-            case 2:
-                return "force";
-        }
-        return "off";
+        return switch (compressionLevel) {
+            case 1 -> "on";
+            case 2 -> "force";
+            default -> "off";
+        };
     }
 
 
@@ -125,7 +120,7 @@ public class CompressionConfig {
      *                                    applied
      */
     public void setNoCompressionUserAgents(String noCompressionUserAgents) {
-        if (noCompressionUserAgents == null || 
noCompressionUserAgents.length() == 0) {
+        if (noCompressionUserAgents == null || 
noCompressionUserAgents.isEmpty()) {
             this.noCompressionUserAgents = null;
         } else {
             this.noCompressionUserAgents = 
Pattern.compile(noCompressionUserAgents);
@@ -153,7 +148,7 @@ public class CompressionConfig {
         StringTokenizer tokens = new StringTokenizer(compressibleMimeType, 
",");
         while (tokens.hasMoreTokens()) {
             String token = tokens.nextToken().trim();
-            if (token.length() > 0) {
+            if (!token.isEmpty()) {
                 values.add(token);
             }
         }
@@ -193,8 +188,8 @@ public class CompressionConfig {
             return false;
         }
 
-        boolean useTE = false;
-        boolean useCE = true;
+        boolean useTransferEncoding = false;
+        boolean useContentEncoding = true;
 
         MimeHeaders responseHeaders = response.getMimeHeaders();
 
@@ -214,7 +209,7 @@ public class CompressionConfig {
             }
             if (tokens.contains("identity")) {
                 // If identity, do not do content modifications
-                useCE = false;
+                useContentEncoding = false;
             } else if (tokens.contains("br") || tokens.contains("compress") || 
tokens.contains("dcb")
                     || tokens.contains("dcz") || tokens.contains("deflate") || 
tokens.contains("gzip")
                     || tokens.contains("pack200-gzip") || 
tokens.contains("zstd")) {
@@ -243,7 +238,7 @@ public class CompressionConfig {
         boolean foundGzip = false;
         // TE and accept-encoding seem to have equivalent syntax
         while (!foundGzip && headerValues.hasMoreElements()) {
-            List<TE> tes = null;
+            List<TE> tes;
             try {
                 tes = TE.parse(new StringReader(headerValues.nextElement()));
             } catch (IOException ioe) {
@@ -253,7 +248,7 @@ public class CompressionConfig {
 
             for (TE te : tes) {
                 if ("gzip".equalsIgnoreCase(te.getEncoding())) {
-                    useTE = true;
+                    useTransferEncoding = true;
                     foundGzip = true;
                     break;
                 }
@@ -262,13 +257,13 @@ public class CompressionConfig {
 
         // Check if the resource has a strong ETag
         String eTag = responseHeaders.getHeader("ETag");
-        if (!useTE && eTag != null && !eTag.trim().startsWith("W/")) {
+        if (!useTransferEncoding && eTag != null && 
!eTag.trim().startsWith("W/")) {
             // Has an ETag that doesn't start with "W/..." so it must be a
             // strong ETag
             return false;
         }
 
-        if (useCE && !useTE) {
+        if (useContentEncoding && !useTransferEncoding) {
             // If processing reaches this far, the response might be 
compressed.
             // Therefore, set the Vary header to keep proxies happy
             ResponseUtil.addVaryFieldName(responseHeaders, "accept-encoding");
@@ -277,9 +272,8 @@ public class CompressionConfig {
             // Only interested in whether gzip encoding is supported. Other
             // encodings and weights can be ignored.
             headerValues = request.getMimeHeaders().values("accept-encoding");
-            foundGzip = false;
             while (!foundGzip && headerValues.hasMoreElements()) {
-                List<AcceptEncoding> acceptEncodings = null;
+                List<AcceptEncoding> acceptEncodings;
                 try {
                     acceptEncodings = AcceptEncoding.parse(new 
StringReader(headerValues.nextElement()));
                 } catch (IOException ioe) {
@@ -319,7 +313,7 @@ public class CompressionConfig {
 
         // Compressed content length is unknown so mark it as such.
         response.setContentLength(-1);
-        if (useTE) {
+        if (useTransferEncoding) {
             // Configure the transfer encoding for compressed content
             responseHeaders.addValue("Transfer-Encoding").setString("gzip");
         } else {
@@ -337,7 +331,7 @@ public class CompressionConfig {
      * @param sArray the StringArray
      * @param value  string
      */
-    private static boolean startsWithStringArray(String sArray[], String 
value) {
+    private static boolean startsWithStringArray(String[] sArray, String 
value) {
         if (value == null) {
             return false;
         }
diff --git a/java/org/apache/coyote/Request.java 
b/java/org/apache/coyote/Request.java
index fc7fb52674..416df0297c 100644
--- a/java/org/apache/coyote/Request.java
+++ b/java/org/apache/coyote/Request.java
@@ -22,6 +22,7 @@ import java.io.UnsupportedEncodingException;
 import java.nio.charset.Charset;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Objects;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicLong;
@@ -120,7 +121,7 @@ public final class Request {
     /**
      * Notes.
      */
-    private final Object notes[] = new Object[Constants.MAX_NOTES];
+    private final Object[] notes = new Object[Constants.MAX_NOTES];
 
 
     /**
@@ -233,7 +234,7 @@ public final class Request {
 
     public boolean isReady() {
         // Assume read is not possible
-        boolean ready = false;
+        boolean ready;
         synchronized (nonBlockingStateLock) {
             if (registeredForRead) {
                 fireListener = true;
@@ -532,17 +533,13 @@ public final class Request {
         response.setRequest(this);
     }
 
-    protected void setHook(ActionHook hook) {
+    void setHook(ActionHook hook) {
         this.hook = hook;
     }
 
     public void action(ActionCode actionCode, Object param) {
         if (hook != null) {
-            if (param == null) {
-                hook.action(actionCode, this);
-            } else {
-                hook.action(actionCode, param);
-            }
+            hook.action(actionCode, Objects.requireNonNullElse(param, this));
         }
     }
 
@@ -624,10 +621,7 @@ public final class Request {
     }
 
     public boolean getSupportsRelativeRedirects() {
-        if (protocol().equals("") || protocol().equals("HTTP/1.0")) {
-            return false;
-        }
-        return true;
+        return !protocol().equals("") && !protocol().equals("HTTP/1.0");
     }
 
 
diff --git a/java/org/apache/coyote/Response.java 
b/java/org/apache/coyote/Response.java
index f6cc713029..70998333d5 100644
--- a/java/org/apache/coyote/Response.java
+++ b/java/org/apache/coyote/Response.java
@@ -23,6 +23,7 @@ import java.nio.ByteBuffer;
 import java.nio.charset.Charset;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Objects;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -93,7 +94,7 @@ public final class Response {
     /**
      * Notes.
      */
-    final Object notes[] = new Object[Constants.MAX_NOTES];
+    final Object[] notes = new Object[Constants.MAX_NOTES];
 
 
     /**
@@ -179,7 +180,7 @@ public final class Response {
     }
 
 
-    protected void setHook(ActionHook hook) {
+    void setHook(ActionHook hook) {
         this.hook = hook;
     }
 
@@ -200,11 +201,7 @@ public final class Response {
 
     public void action(ActionCode actionCode, Object param) {
         if (hook != null) {
-            if (param == null) {
-                hook.action(actionCode, this);
-            } else {
-                hook.action(actionCode, param);
-            }
+            hook.action(actionCode, Objects.requireNonNullElse(param, this));
         }
     }
 
@@ -585,7 +582,7 @@ public final class Response {
             // There is a charset so have to rebuild content-type without it
             this.contentType = m.toStringNoCharset();
             charsetValue = charsetValue.trim();
-            if (charsetValue.length() > 0) {
+            if (!charsetValue.isEmpty()) {
                 charsetHolder = CharsetHolder.getInstance(charsetValue);
                 try {
                     charsetHolder.validate();
@@ -775,7 +772,7 @@ public final class Response {
             return true;
         }
         // Assume write is not possible
-        boolean ready = false;
+        boolean ready;
         synchronized (nonBlockingStateLock) {
             if (registeredForWrite) {
                 fireListener = true;
diff --git a/java/org/apache/coyote/ajp/AbstractAjpProtocol.java 
b/java/org/apache/coyote/ajp/AbstractAjpProtocol.java
index f1231ad473..561d08ecf6 100644
--- a/java/org/apache/coyote/ajp/AbstractAjpProtocol.java
+++ b/java/org/apache/coyote/ajp/AbstractAjpProtocol.java
@@ -235,8 +235,7 @@ public abstract class AbstractAjpProtocol<S> extends 
AbstractProtocol<S> {
 
     @Override
     protected Processor createProcessor() {
-        AjpProcessor processor = new AjpProcessor(this, getAdapter());
-        return processor;
+        return new AjpProcessor(this, getAdapter());
     }
 
 
@@ -251,7 +250,7 @@ public abstract class AbstractAjpProtocol<S> extends 
AbstractProtocol<S> {
     public void start() throws Exception {
         if (getSecretRequired()) {
             String secret = getSecret();
-            if (secret == null || secret.length() == 0) {
+            if (secret == null || secret.isEmpty()) {
                 throw new 
IllegalArgumentException(sm.getString("ajpprotocol.noSecret"));
             }
         }
diff --git a/java/org/apache/coyote/ajp/AjpMessage.java 
b/java/org/apache/coyote/ajp/AjpMessage.java
index 04e99aab9f..86ecdd73db 100644
--- a/java/org/apache/coyote/ajp/AjpMessage.java
+++ b/java/org/apache/coyote/ajp/AjpMessage.java
@@ -61,7 +61,7 @@ public class AjpMessage {
     /**
      * Fixed size buffer.
      */
-    protected final byte buf[];
+    protected final byte[] buf;
 
 
     /**
@@ -373,7 +373,7 @@ public class AjpMessage {
     // ------------------------------------------------------ Protected Methods
 
 
-    protected static String hexLine(byte buf[], int start, int len) {
+    protected static String hexLine(byte[] buf, int start, int len) {
         StringBuilder sb = new StringBuilder();
         for (int i = start; i < start + 16; i++) {
             if (i < len + 4) {
diff --git a/java/org/apache/coyote/ajp/AjpProcessor.java 
b/java/org/apache/coyote/ajp/AjpProcessor.java
index 8df1960e10..fc5861765e 100644
--- a/java/org/apache/coyote/ajp/AjpProcessor.java
+++ b/java/org/apache/coyote/ajp/AjpProcessor.java
@@ -27,9 +27,6 @@ import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -131,29 +128,20 @@ public class AjpProcessor extends AbstractProcessor {
         System.arraycopy(pongMessage.getBuffer(), 0, pongMessageArray, 0, 
pongMessage.getLen());
 
         // Build Map of Java Servlet to Jakarta Servlet attribute names
-        Map<String,String> m = new HashMap<>();
-        m.put("jakarta.servlet.request.secure_protocol", 
"jakarta.servlet.request.secure_protocol");
-        m.put("jakarta.servlet.request.cipher_suite", 
"jakarta.servlet.request.cipher_suite");
-        m.put("jakarta.servlet.request.key_size", 
"jakarta.servlet.request.key_size");
-        m.put("jakarta.servlet.request.ssl_session", 
"jakarta.servlet.request.ssl_session");
-        m.put("jakarta.servlet.request.X509Certificate", 
"jakarta.servlet.request.X509Certificate");
-        m.put("javax.servlet.request.cipher_suite", 
"jakarta.servlet.request.cipher_suite");
-        m.put("javax.servlet.request.key_size", 
"jakarta.servlet.request.key_size");
-        m.put("javax.servlet.request.ssl_session", 
"jakarta.servlet.request.ssl_session");
-        m.put("javax.servlet.request.X509Certificate", 
"jakarta.servlet.request.X509Certificate");
-        jakartaAttributeMapping = Collections.unmodifiableMap(m);
-
-        Set<String> s = new HashSet<>();
-        s.add("CERT_ISSUER");
-        s.add("CERT_SUBJECT");
-        s.add("CERT_COOKIE");
-        s.add("HTTPS_SERVER_SUBJECT");
-        s.add("CERT_FLAGS");
-        s.add("HTTPS_SECRETKEYSIZE");
-        s.add("CERT_SERIALNUMBER");
-        s.add("HTTPS_SERVER_ISSUER");
-        s.add("HTTPS_KEYSIZE");
-        iisTlsAttributes = Collections.unmodifiableSet(s);
+        jakartaAttributeMapping = Map.of(
+            "jakarta.servlet.request.secure_protocol", 
"jakarta.servlet.request.secure_protocol",
+            "jakarta.servlet.request.cipher_suite", 
"jakarta.servlet.request.cipher_suite",
+            "jakarta.servlet.request.key_size", 
"jakarta.servlet.request.key_size",
+            "jakarta.servlet.request.ssl_session", 
"jakarta.servlet.request.ssl_session",
+            "jakarta.servlet.request.X509Certificate", 
"jakarta.servlet.request.X509Certificate",
+            "javax.servlet.request.cipher_suite", 
"jakarta.servlet.request.cipher_suite",
+            "javax.servlet.request.key_size", 
"jakarta.servlet.request.key_size",
+            "javax.servlet.request.ssl_session", 
"jakarta.servlet.request.ssl_session",
+            "javax.servlet.request.X509Certificate", 
"jakarta.servlet.request.X509Certificate");
+
+        iisTlsAttributes = Set.of(
+            "CERT_ISSUER", "CERT_SUBJECT", "CERT_COOKIE", 
"HTTPS_SERVER_SUBJECT", "CERT_FLAGS", "HTTPS_SECRETKEYSIZE",
+            "CERT_SERIALNUMBER", "HTTPS_SERVER_ISSUER", "HTTPS_KEYSIZE");
     }
 
 
@@ -680,7 +668,7 @@ public class AjpProcessor extends AbstractProcessor {
         boolean contentLengthSet = false;
         int hCount = requestHeaderMessage.getInt();
         for (int i = 0; i < hCount; i++) {
-            String hName = null;
+            String hName;
 
             // Header names are encoded as either an integer code starting
             // with 0xA0, or as a normal string (in which case the first
@@ -688,7 +676,7 @@ public class AjpProcessor extends AbstractProcessor {
             int isc = requestHeaderMessage.peekInt();
             int hId = isc & 0xFF;
 
-            MessageBytes vMB = null;
+            MessageBytes vMB;
             isc &= 0xFF00;
             if (0xA000 == isc) {
                 requestHeaderMessage.getInt(); // To advance the read position
@@ -733,8 +721,7 @@ public class AjpProcessor extends AbstractProcessor {
         while ((attributeCode = requestHeaderMessage.getByte()) != 
Constants.SC_A_ARE_DONE) {
 
             switch (attributeCode) {
-
-                case Constants.SC_A_REQ_ATTRIBUTE:
+                case Constants.SC_A_REQ_ATTRIBUTE -> {
                     requestHeaderMessage.getBytes(tmpMB);
                     String n = tmpMB.toString();
                     requestHeaderMessage.getBytes(tmpMB);
@@ -776,19 +763,14 @@ public class AjpProcessor extends AbstractProcessor {
                             setErrorState(ErrorState.CLOSE_CLEAN, null);
                         }
                     }
-                    break;
-
-                case Constants.SC_A_CONTEXT:
-                    requestHeaderMessage.getBytes(tmpMB);
-                    // nothing
-                    break;
+                }
+                case Constants.SC_A_CONTEXT -> 
requestHeaderMessage.getBytes(tmpMB);
 
-                case Constants.SC_A_SERVLET_PATH:
-                    requestHeaderMessage.getBytes(tmpMB);
-                    // nothing
-                    break;
+                // nothing
+                case Constants.SC_A_SERVLET_PATH -> 
requestHeaderMessage.getBytes(tmpMB);
 
-                case Constants.SC_A_REMOTE_USER:
+                // nothing
+                case Constants.SC_A_REMOTE_USER -> {
                     boolean tomcatAuthorization = 
protocol.getTomcatAuthorization();
                     if (tomcatAuthorization || 
!protocol.getTomcatAuthentication()) {
                         // Implies tomcatAuthentication == false
@@ -798,9 +780,8 @@ public class AjpProcessor extends AbstractProcessor {
                         // Ignore user information from reverse proxy
                         requestHeaderMessage.getBytes(tmpMB);
                     }
-                    break;
-
-                case Constants.SC_A_AUTH_TYPE:
+                }
+                case Constants.SC_A_AUTH_TYPE -> {
                     if (protocol.getTomcatAuthorization() || 
!protocol.getTomcatAuthentication()) {
                         // Implies tomcatAuthentication == false
                         requestHeaderMessage.getBytes(request.getAuthType());
@@ -808,61 +789,44 @@ public class AjpProcessor extends AbstractProcessor {
                         // Ignore user information from reverse proxy
                         requestHeaderMessage.getBytes(tmpMB);
                     }
-                    break;
-
-                case Constants.SC_A_QUERY_STRING:
-                    requestHeaderMessage.getBytes(request.queryString());
-                    break;
-
-                case Constants.SC_A_JVM_ROUTE:
-                    requestHeaderMessage.getBytes(tmpMB);
-                    // nothing
-                    break;
+                }
+                case Constants.SC_A_QUERY_STRING -> 
requestHeaderMessage.getBytes(request.queryString());
+                case Constants.SC_A_JVM_ROUTE -> 
requestHeaderMessage.getBytes(tmpMB);
 
-                case Constants.SC_A_SSL_CERT:
+                // nothing
+                case Constants.SC_A_SSL_CERT ->
                     // SSL certificate extraction is lazy, moved to 
JkCoyoteHandler
                     requestHeaderMessage.getBytes(certificates);
-                    break;
-
-                case Constants.SC_A_SSL_CIPHER:
+                case Constants.SC_A_SSL_CIPHER -> {
                     requestHeaderMessage.getBytes(tmpMB);
                     request.setAttribute(SSLSupport.CIPHER_SUITE_KEY, 
tmpMB.toString());
-                    break;
-
-                case Constants.SC_A_SSL_SESSION:
+                }
+                case Constants.SC_A_SSL_SESSION -> {
                     requestHeaderMessage.getBytes(tmpMB);
                     request.setAttribute(SSLSupport.SESSION_ID_KEY, 
tmpMB.toString());
-                    break;
-
-                case Constants.SC_A_SSL_KEY_SIZE:
+                }
+                case Constants.SC_A_SSL_KEY_SIZE ->
                     request.setAttribute(SSLSupport.KEY_SIZE_KEY, 
Integer.valueOf(requestHeaderMessage.getInt()));
-                    break;
-
-                case Constants.SC_A_STORED_METHOD:
-                    requestHeaderMessage.getBytes(request.method());
-                    break;
-
-                case Constants.SC_A_SECRET:
+                case Constants.SC_A_STORED_METHOD -> 
requestHeaderMessage.getBytes(request.method());
+                case Constants.SC_A_SECRET -> {
                     requestHeaderMessage.getBytes(tmpMB);
-                    if (secret != null && secret.length() > 0) {
+                    if (secret != null && !secret.isEmpty()) {
                         secretPresentInRequest = true;
                         if (!tmpMB.equals(secret)) {
                             response.setStatus(403);
                             setErrorState(ErrorState.CLOSE_CLEAN, null);
                         }
                     }
-                    break;
-
-                default:
-                    // Ignore unknown attribute for backward compatibility
-                    break;
-
+                }
+                default -> {
+                }
+                // Ignore unknown attribute for backward compatibility
             }
 
         }
 
         // Check if secret was submitted if required
-        if (secret != null && secret.length() > 0 && !secretPresentInRequest) {
+        if (secret != null && !secret.isEmpty() && !secretPresentInRequest) {
             response.setStatus(403);
             setErrorState(ErrorState.CLOSE_CLEAN, null);
         }
@@ -873,10 +837,9 @@ public class AjpProcessor extends AbstractProcessor {
 
             int pos = uriBC.indexOf("://", 0, 3, 4);
             int uriBCStart = uriBC.getStart();
-            int slashPos = -1;
             if (pos != -1) {
                 byte[] uriB = uriBC.getBytes();
-                slashPos = uriBC.indexOf('/', pos + 3);
+                int slashPos = uriBC.indexOf('/', pos + 3);
                 if (slashPos == -1) {
                     slashPos = uriBC.getLength();
                     // Set URI as "/"
diff --git a/java/org/apache/coyote/http11/AbstractHttp11Protocol.java 
b/java/org/apache/coyote/http11/AbstractHttp11Protocol.java
index f48dcd82d5..feb1689058 100644
--- a/java/org/apache/coyote/http11/AbstractHttp11Protocol.java
+++ b/java/org/apache/coyote/http11/AbstractHttp11Protocol.java
@@ -373,7 +373,7 @@ public abstract class AbstractHttp11Protocol<S> extends 
AbstractProtocol<S> {
      *                                 "gorilla|desesplorer|tigrus"
      */
     public void setRestrictedUserAgents(String restrictedUserAgents) {
-        if (restrictedUserAgents == null || restrictedUserAgents.length() == 
0) {
+        if (restrictedUserAgents == null || restrictedUserAgents.isEmpty()) {
             this.restrictedUserAgents = null;
         } else {
             this.restrictedUserAgents = Pattern.compile(restrictedUserAgents);
@@ -475,7 +475,7 @@ public abstract class AbstractHttp11Protocol<S> extends 
AbstractProtocol<S> {
      * The names of headers that are allowed to be sent via a trailer when 
using chunked encoding. They are stored in
      * lower case.
      */
-    private Set<String> allowedTrailerHeaders = ConcurrentHashMap.newKeySet();
+    private final Set<String> allowedTrailerHeaders = 
ConcurrentHashMap.newKeySet();
 
     public void setAllowedTrailerHeaders(String commaSeparatedHeaders) {
         // Jump through some hoops so we don't end up with an empty set while
@@ -552,7 +552,7 @@ public abstract class AbstractHttp11Protocol<S> extends 
AbstractProtocol<S> {
         // HTTP Upgrade
         String httpUpgradeName = 
upgradeProtocol.getHttpUpgradeName(getEndpoint().isSSLEnabled());
         boolean httpUpgradeConfigured = false;
-        if (httpUpgradeName != null && httpUpgradeName.length() > 0) {
+        if (httpUpgradeName != null && !httpUpgradeName.isEmpty()) {
             httpUpgradeProtocols.put(httpUpgradeName, upgradeProtocol);
             httpUpgradeConfigured = true;
             
getLog().info(sm.getString("abstractHttp11Protocol.httpUpgradeConfigured", 
getName(), httpUpgradeName));
@@ -561,7 +561,7 @@ public abstract class AbstractHttp11Protocol<S> extends 
AbstractProtocol<S> {
 
         // ALPN
         String alpnName = upgradeProtocol.getAlpnName();
-        if (alpnName != null && alpnName.length() > 0) {
+        if (alpnName != null && !alpnName.isEmpty()) {
             // ALPN is only available with TLS
             if (getEndpoint().isSSLEnabled()) {
                 negotiatedProtocols.put(alpnName, upgradeProtocol);
@@ -763,8 +763,7 @@ public abstract class AbstractHttp11Protocol<S> extends 
AbstractProtocol<S> {
 
     @Override
     protected Processor createProcessor() {
-        Http11Processor processor = new Http11Processor(this, adapter);
-        return processor;
+        return new Http11Processor(this, adapter);
     }
 
 
diff --git a/java/org/apache/coyote/http11/Http11InputBuffer.java 
b/java/org/apache/coyote/http11/Http11InputBuffer.java
index 13a174c480..6f2cfa5f7a 100644
--- a/java/org/apache/coyote/http11/Http11InputBuffer.java
+++ b/java/org/apache/coyote/http11/Http11InputBuffer.java
@@ -120,10 +120,10 @@ public class Http11InputBuffer implements InputBuffer, 
ApplicationBufferHandler,
     private byte prevChr = 0;
     private byte chr = 0;
     private volatile boolean parsingRequestLine;
-    private int parsingRequestLinePhase = 0;
-    private boolean parsingRequestLineEol = false;
-    private int parsingRequestLineStart = 0;
-    private int parsingRequestLineQPos = -1;
+    private int parsingRequestLinePhase;
+    private boolean parsingRequestLineEol;
+    private int parsingRequestLineStart;
+    private int parsingRequestLineQPos;
     private final HttpParser httpParser;
     private final HttpHeaderParser httpHeaderParser;
 
@@ -132,12 +132,6 @@ public class Http11InputBuffer implements InputBuffer, 
ApplicationBufferHandler,
      */
     private final int headerBufferSize;
 
-    /**
-     * Known size of the NioChannel read buffer.
-     */
-    private int socketReadBufferSize;
-
-
     // ----------------------------------------------------------- Constructors
 
     public Http11InputBuffer(Request request, int headerBufferSize, HttpParser 
httpParser) {
@@ -578,20 +572,12 @@ public class Http11InputBuffer implements InputBuffer, 
ApplicationBufferHandler,
             throw new 
IllegalStateException(sm.getString("iib.parseheaders.ise.error"));
         }
 
-        HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS;
+        HeaderParseStatus status;
 
         do {
             status = httpHeaderParser.parseHeader();
-            // Checking that
-            // (1) Headers plus request line size does not exceed its limit
-            // (2) There are enough bytes to avoid expanding the buffer when
-            // reading body
-            // Technically, (2) is technical limitation, (1) is logical
-            // limitation to enforce the meaning of headerBufferSize
-            // From the way how buf is allocated and how blank lines are being
-            // read, it should be enough to check (1) only.
-            if (byteBuffer.position() > headerBufferSize ||
-                    byteBuffer.capacity() - byteBuffer.position() < 
socketReadBufferSize) {
+            // Checking that headers plus request line size does not exceed 
its limit
+            if (byteBuffer.position() > headerBufferSize) {
                 throw new 
IllegalArgumentException(sm.getString("iib.requestheadertoolarge.error"));
             }
         } while (status == HeaderParseStatus.HAVE_MORE_HEADERS);
@@ -779,7 +765,7 @@ public class Http11InputBuffer implements InputBuffer, 
ApplicationBufferHandler,
             byteBuffer.limit(end).position(end);
         }
 
-        int nRead = -1;
+        int nRead;
         int mark = byteBuffer.position();
         try {
             if (byteBuffer.position() < byteBuffer.limit()) {
@@ -891,6 +877,5 @@ public class Http11InputBuffer implements InputBuffer, 
ApplicationBufferHandler,
         temp.put(byteBuffer);
         byteBuffer = temp;
         byteBuffer.mark();
-        temp = null;
     }
 }
diff --git a/java/org/apache/coyote/http11/Http11Processor.java 
b/java/org/apache/coyote/http11/Http11Processor.java
index afdef54424..10f45e4132 100644
--- a/java/org/apache/coyote/http11/Http11Processor.java
+++ b/java/org/apache/coyote/http11/Http11Processor.java
@@ -22,6 +22,7 @@ import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
 import java.util.regex.Pattern;
 
@@ -96,7 +97,7 @@ public class Http11Processor extends AbstractProcessor {
      * Tracks how many internal filters are in the filter library so they are 
skipped when looking for pluggable
      * filters.
      */
-    private int pluggableFilterIndex = Integer.MAX_VALUE;
+    private final int pluggableFilterIndex;
 
 
     /**
@@ -452,11 +453,7 @@ public class Http11Processor extends AbstractProcessor {
 
             if (!protocol.getDisableUploadTimeout()) {
                 int connectionTimeout = protocol.getConnectionTimeout();
-                if (connectionTimeout > 0) {
-                    socketWrapper.setReadTimeout(connectionTimeout);
-                } else {
-                    socketWrapper.setReadTimeout(0);
-                }
+                socketWrapper.setReadTimeout(Math.max(connectionTimeout, 0));
             }
 
             rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE);
@@ -871,7 +868,7 @@ public class Http11Processor extends AbstractProcessor {
 
         OutputFilter[] outputFilters = outputBuffer.getFilters();
 
-        if (http09 == true) {
+        if (http09) {
             // HTTP/0.9
             
outputBuffer.addActiveFilter(outputFilters[Constants.IDENTITY_FILTER]);
             outputBuffer.commit();
@@ -1411,17 +1408,14 @@ public class Http11Processor extends AbstractProcessor {
                 sendfileData.keepAliveState = SendfileKeepAliveState.NONE;
             }
             result = socketWrapper.processSendfile(sendfileData);
-            switch (result) {
-                case ERROR:
-                    // Write failed
-                    if (log.isDebugEnabled()) {
-                        
log.debug(sm.getString("http11processor.sendfile.error"));
-                    }
-                    setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null);
-                    //$FALL-THROUGH$
-                default:
-                    sendfileData = null;
+            if (Objects.requireNonNull(result) == SendfileState.ERROR) {
+                // Write failed
+                if (log.isDebugEnabled()) {
+                    log.debug(sm.getString("http11processor.sendfile.error"));
+                }
+                setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null);
             }
+            sendfileData = null;
         }
         return result;
     }
diff --git a/java/org/apache/coyote/http11/filters/BufferedInputFilter.java 
b/java/org/apache/coyote/http11/filters/BufferedInputFilter.java
index 455ffb882a..dfd54adb53 100644
--- a/java/org/apache/coyote/http11/filters/BufferedInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/BufferedInputFilter.java
@@ -88,7 +88,7 @@ public class BufferedInputFilter implements InputFilter, 
ApplicationBufferHandle
             if (buffered.getLimit() == 0) {
                 // Special case - ignore (swallow) body. Do so within a limit.
                 long swallowed = 0;
-                int read = 0;
+                int read;
                 while ((read = buffer.doRead(this)) >= 0) {
                     swallowed += read;
                     if (maxSwallowSize > -1 && swallowed > maxSwallowSize) {
diff --git a/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java 
b/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
index 429f1e2586..1be7215e76 100644
--- a/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
@@ -175,7 +175,7 @@ public class ChunkedInputFilter implements InputFilter, 
ApplicationBufferHandler
     @Override
     public long end() throws IOException {
         long swallowed = 0;
-        int read = 0;
+        int read;
         // Consume extra bytes : parse the stream until the end chunk is found
         while ((read = doRead(this)) >= 0) {
             swallowed += read;
@@ -325,8 +325,8 @@ public class ChunkedInputFilter implements InputFilter, 
ApplicationBufferHandler
             if (read < 0) {
                 // Unexpected end of stream
                 
throwBadRequestException(sm.getString("chunkedInputFilter.invalidHeader"));
-            } else if (read == 0) {
-                return false;
+            } else {
+                return read != 0;
             }
         }
         return true;
@@ -473,7 +473,7 @@ public class ChunkedInputFilter implements InputFilter, 
ApplicationBufferHandler
 
 
     private int parseChunkBody(ApplicationBufferHandler handler) throws 
IOException {
-        int result = 0;
+        int result;
 
         if (!fill()) {
             return 0;
@@ -584,7 +584,7 @@ public class ChunkedInputFilter implements InputFilter, 
ApplicationBufferHandler
      */
     private boolean parseTrailerFields() throws IOException {
         // Handle optional trailer headers
-        HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS;
+        HeaderParseStatus status;
         do {
             try {
                 status = httpHeaderParser.parseHeader();
diff --git a/java/org/apache/coyote/http11/filters/IdentityInputFilter.java 
b/java/org/apache/coyote/http11/filters/IdentityInputFilter.java
index e396360a81..2a4ff3d481 100644
--- a/java/org/apache/coyote/http11/filters/IdentityInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/IdentityInputFilter.java
@@ -89,7 +89,7 @@ public class IdentityInputFilter implements InputFilter, 
ApplicationBufferHandle
     @Override
     public int doRead(ApplicationBufferHandler handler) throws IOException {
 
-        int result = -1;
+        int result;
 
         if (contentLength >= 0) {
             if (remaining > 0) {
@@ -114,6 +114,8 @@ public class IdentityInputFilter implements InputFilter, 
ApplicationBufferHandle
                 }
                 result = -1;
             }
+        } else {
+            result = -1;
         }
 
         return result;
diff --git a/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java 
b/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
index 8c44d8552a..e83c37fd18 100644
--- a/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
+++ b/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
@@ -55,7 +55,7 @@ public class IdentityOutputFilter implements OutputFilter {
     @Override
     public int doWrite(ByteBuffer chunk) throws IOException {
 
-        int result = -1;
+        int result;
 
         if (contentLength >= 0) {
             if (remaining > 0) {
diff --git a/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java 
b/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
index 84b6ae8f7b..c6609be67a 100644
--- a/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
@@ -32,7 +32,7 @@ public class SavedRequestInputFilter implements InputFilter {
     /**
      * The original request body.
      */
-    protected ByteChunk input = null;
+    protected ByteChunk input;
 
     /**
      * Create a new SavedRequestInputFilter.
diff --git a/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java 
b/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java
index fe64cbfea5..f05d30051b 100644
--- a/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java
+++ b/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java
@@ -29,10 +29,10 @@ public class UpgradeGroupInfo extends BaseModelMBean {
 
     private final Set<UpgradeInfo> upgradeInfos = (new 
ConcurrentHashMap<UpgradeInfo,Boolean>()).keySet(Boolean.TRUE);
 
-    private LongAdder deadBytesReceived = new LongAdder();
-    private LongAdder deadBytesSent = new LongAdder();
-    private LongAdder deadMsgsReceived = new LongAdder();
-    private LongAdder deadMsgsSent = new LongAdder();
+    private final LongAdder deadBytesReceived = new LongAdder();
+    private final LongAdder deadBytesSent = new LongAdder();
+    private final LongAdder deadMsgsReceived = new LongAdder();
+    private final LongAdder deadMsgsSent = new LongAdder();
 
 
     public void addUpgradeInfo(UpgradeInfo ui) {
diff --git 
a/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java 
b/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java
index b2bea31f6e..b9e1f0f34d 100644
--- a/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java
+++ b/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java
@@ -202,12 +202,8 @@ public class UpgradeServletOutputStream extends 
ServletOutputStream {
      * Must hold writeLock to call this method.
      */
     private void writeInternal(byte[] b, int off, int len) throws IOException {
-        if (listener == null) {
-            // Simple case - blocking IO
-            socketWrapper.write(true, b, off, len);
-        } else {
-            socketWrapper.write(false, b, off, len);
-        }
+        // Blocking IO if no listener
+        socketWrapper.write(listener == null, b, off, len);
         upgradeInfo.addBytesSent(len);
     }
 
diff --git a/java/org/apache/coyote/http2/ConnectionSettingsBase.java 
b/java/org/apache/coyote/http2/ConnectionSettingsBase.java
index 0b702bf5b5..cdb95ab10b 100644
--- a/java/org/apache/coyote/http2/ConnectionSettingsBase.java
+++ b/java/org/apache/coyote/http2/ConnectionSettingsBase.java
@@ -71,34 +71,23 @@ abstract class ConnectionSettingsBase<T extends Throwable> {
         }
 
         switch (setting) {
-            case HEADER_TABLE_SIZE:
-                validateHeaderTableSize(value);
-                break;
-            case ENABLE_PUSH:
-                validateEnablePush(value);
-                break;
-            case MAX_CONCURRENT_STREAMS:
+            case HEADER_TABLE_SIZE -> validateHeaderTableSize(value);
+            case ENABLE_PUSH -> validateEnablePush(value);
+            case MAX_CONCURRENT_STREAMS, MAX_HEADER_LIST_SIZE -> {
                 // No further validation required
-                break;
-            case INITIAL_WINDOW_SIZE:
-                validateInitialWindowSize(value);
-                break;
-            case MAX_FRAME_SIZE:
-                validateMaxFrameSize(value);
-                break;
-            case MAX_HEADER_LIST_SIZE:
-                // No further validation required
-                break;
-            case NO_RFC7540_PRIORITIES:
-                validateNoRfc7540Priorities(value);
-                break;
-            case ENABLE_CONNECT_PROTOCOL:
-            case TLS_RENEG_PERMITTED:
+            }
+            case INITIAL_WINDOW_SIZE -> validateInitialWindowSize(value);
+            case MAX_FRAME_SIZE -> validateMaxFrameSize(value);
+            case NO_RFC7540_PRIORITIES -> validateNoRfc7540Priorities(value);
+            case ENABLE_CONNECT_PROTOCOL, TLS_RENEG_PERMITTED -> {
                 // Not supported. Ignore it.
                 return;
-            case UNKNOWN:
+                // Not supported. Ignore it.
+            }
+            case UNKNOWN -> {
                 // Unrecognised. Ignore it.
                 return;
+            }
         }
 
         set(setting, Long.valueOf(value));
diff --git a/java/org/apache/coyote/http2/FrameType.java 
b/java/org/apache/coyote/http2/FrameType.java
index da0614c453..070c4ae0b7 100644
--- a/java/org/apache/coyote/http2/FrameType.java
+++ b/java/org/apache/coyote/http2/FrameType.java
@@ -87,31 +87,19 @@ enum FrameType {
 
 
     static FrameType valueOf(int i) {
-        switch (i) {
-            case 0:
-                return DATA;
-            case 1:
-                return HEADERS;
-            case 2:
-                return PRIORITY;
-            case 3:
-                return RST;
-            case 4:
-                return SETTINGS;
-            case 5:
-                return PUSH_PROMISE;
-            case 6:
-                return PING;
-            case 7:
-                return GOAWAY;
-            case 8:
-                return WINDOW_UPDATE;
-            case 9:
-                return CONTINUATION;
-            case 16:
-                return PRIORITY_UPDATE;
-            default:
-                return UNKNOWN;
-        }
+        return switch (i) {
+            case 0 -> DATA;
+            case 1 -> HEADERS;
+            case 2 -> PRIORITY;
+            case 3 -> RST;
+            case 4 -> SETTINGS;
+            case 5 -> PUSH_PROMISE;
+            case 6 -> PING;
+            case 7 -> GOAWAY;
+            case 8 -> WINDOW_UPDATE;
+            case 9 -> CONTINUATION;
+            case 16 -> PRIORITY_UPDATE;
+            default -> UNKNOWN;
+        };
     }
 }
diff --git a/java/org/apache/coyote/http2/HPackHuffman.java 
b/java/org/apache/coyote/http2/HPackHuffman.java
index e5ce4826ba..6ca431c3ae 100644
--- a/java/org/apache/coyote/http2/HPackHuffman.java
+++ b/java/org/apache/coyote/http2/HPackHuffman.java
@@ -324,11 +324,11 @@ public class HPackHuffman {
             int newLength = length + 1;
             HuffmanCode high = new HuffmanCode(code << 1 | 1, newLength);
             HuffmanCode low = new HuffmanCode(code << 1, newLength);
-            int newVal = 0;
+            int newVal;
             boolean highTerminal = allCodes.remove(high);
             if (highTerminal) {
                 // bah, linear search
-                int i = 0;
+                int i;
                 for (i = 0; i < codes.length; ++i) {
                     if (codes[i].equals(high)) {
                         break;
@@ -344,7 +344,7 @@ public class HPackHuffman {
             boolean lowTerminal = allCodes.remove(low);
             if (lowTerminal) {
                 // bah, linear search
-                int i = 0;
+                int i;
                 for (i = 0; i < codes.length; ++i) {
                     if (codes[i].equals(low)) {
                         break;
@@ -470,7 +470,7 @@ public class HPackHuffman {
             HuffmanCode code = HUFFMAN_CODES[c];
             if (code.length + bytePos <= 8) {
                 // it fits in the current byte
-                currentBufferByte |= ((code.value & 0xFF) << 8 - (code.length 
+ bytePos));
+                currentBufferByte |= (byte) ((code.value & 0xFF) << 8 - 
(code.length + bytePos));
                 bytePos += code.length;
             } else {
                 // it does not fit, it may need up to 4 bytes
@@ -483,9 +483,9 @@ public class HPackHuffman {
                     }
                     int remainingInByte = 8 - bytePos;
                     if (rem > remainingInByte) {
-                        currentBufferByte |= (val >> (rem - remainingInByte));
+                        currentBufferByte |= (byte) (val >> (rem - 
remainingInByte));
                     } else {
-                        currentBufferByte |= (val << (remainingInByte - rem));
+                        currentBufferByte |= (byte) (val << (remainingInByte - 
rem));
                     }
                     if (rem > remainingInByte) {
                         buffer.put(currentBufferByte);
@@ -563,11 +563,7 @@ public class HPackHuffman {
             if (length != that.length) {
                 return false;
             }
-            if (value != that.value) {
-                return false;
-            }
-
-            return true;
+            return value == that.value;
         }
 
         @Override
diff --git a/java/org/apache/coyote/http2/HpackDecoder.java 
b/java/org/apache/coyote/http2/HpackDecoder.java
index 5257802285..6804f9efb1 100644
--- a/java/org/apache/coyote/http2/HpackDecoder.java
+++ b/java/org/apache/coyote/http2/HpackDecoder.java
@@ -61,7 +61,7 @@ public class HpackDecoder {
     /**
      * The maximum allowed memory size set by the container.
      */
-    private int maxMemorySizeHard;
+    private final int maxMemorySizeHard;
     /**
      * The maximum memory size currently in use. May be less than the hard 
limit.
      */
diff --git a/java/org/apache/coyote/http2/HpackEncoder.java 
b/java/org/apache/coyote/http2/HpackEncoder.java
index 391423ea8b..6b413d8861 100644
--- a/java/org/apache/coyote/http2/HpackEncoder.java
+++ b/java/org/apache/coyote/http2/HpackEncoder.java
@@ -44,13 +44,10 @@ class HpackEncoder {
         public boolean shouldUseIndexing(String headerName, String value) {
             // content length and date change all the time
             // no need to index them, or they will churn the table
-            switch (headerName) {
-                case "content-length":
-                case "date":
-                    return false;
-                default:
-                    return true;
-            }
+            return switch (headerName) {
+                case "content-length", "date" -> false;
+                default -> true;
+            };
         }
 
         @Override
diff --git a/java/org/apache/coyote/http2/Http2AsyncParser.java 
b/java/org/apache/coyote/http2/Http2AsyncParser.java
index e1c8170765..5274374d0d 100644
--- a/java/org/apache/coyote/http2/Http2AsyncParser.java
+++ b/java/org/apache/coyote/http2/Http2AsyncParser.java
@@ -152,14 +152,11 @@ class Http2AsyncParser extends Http2Parser {
         if (error != null) {
             Throwable error = this.error;
             this.error = null;
-            if (error instanceof Http2Exception) {
-                throw (Http2Exception) error;
-            } else if (error instanceof IOException) {
-                throw (IOException) error;
-            } else if (error instanceof RuntimeException) {
-                throw (RuntimeException) error;
-            } else {
-                throw new RuntimeException(error);
+            switch (error) {
+                case Http2Exception http2Exception -> throw http2Exception;
+                case IOException ioException -> throw ioException;
+                case RuntimeException runtimeException -> throw 
runtimeException;
+                case null, default -> throw new RuntimeException(error);
             }
         }
     }
diff --git a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java 
b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
index 13f730b78d..a3abe26535 100644
--- a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
@@ -401,8 +401,8 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
                     }
                     return;
                 }
-                sendfile.streamReservation -= bytesWritten;
-                sendfile.connectionReservation -= bytesWritten;
+                sendfile.streamReservation -= (int) bytesWritten;
+                sendfile.connectionReservation -= (int) bytesWritten;
                 sendfile.pos += bytesWritten;
                 try {
                     if (sendfile.connectionReservation == 0) {
@@ -496,7 +496,7 @@ public class Http2AsyncUpgradeHandler extends 
Http2UpgradeHandler {
         @Override
         public void receivePing(byte[] payload, boolean ack) throws 
IOException {
             if (ack) {
-                super.receivePing(payload, ack);
+                super.receivePing(payload, true);
             } else {
                 // Client originated ping. Echo it back.
                 socketWrapper.write(BlockingMode.SEMI_BLOCK, 
protocol.getWriteTimeout(), TimeUnit.MILLISECONDS, null,
diff --git a/java/org/apache/coyote/http2/Http2Protocol.java 
b/java/org/apache/coyote/http2/Http2Protocol.java
index c0c8f0fde9..f9b57bb00f 100644
--- a/java/org/apache/coyote/http2/Http2Protocol.java
+++ b/java/org/apache/coyote/http2/Http2Protocol.java
@@ -98,7 +98,7 @@ public class Http2Protocol implements UpgradeProtocol {
     // Reference to HTTP/1.1 protocol that this instance is configured under
     private AbstractHttp11Protocol<?> http11Protocol = null;
 
-    private RequestGroupInfo global = new RequestGroupInfo();
+    private final RequestGroupInfo global = new RequestGroupInfo();
 
     /*
      * Setting discardRequestsAndResponses can have a significant performance 
impact. The magnitude of the impact is
@@ -133,11 +133,9 @@ public class Http2Protocol implements UpgradeProtocol {
 
     @Override
     public Processor getProcessor(SocketWrapperBase<?> socketWrapper, Adapter 
adapter) {
-        String upgradeProtocol = getUpgradeProtocolName();
-        UpgradeProcessorInternal processor = new 
UpgradeProcessorInternal(socketWrapper,
-                new UpgradeToken(getInternalUpgradeHandler(socketWrapper, 
adapter, null), null, null, upgradeProtocol),
-                null);
-        return processor;
+        return new UpgradeProcessorInternal(socketWrapper,
+                new UpgradeToken(getInternalUpgradeHandler(socketWrapper, 
adapter, null), null,
+                    null, getUpgradeProtocolName()),null);
     }
 
 
@@ -312,11 +310,7 @@ public class Http2Protocol implements UpgradeProtocol {
 
 
     public void setOverheadResetFactor(int overheadResetFactor) {
-        if (overheadResetFactor < 0) {
-            this.overheadResetFactor = 0;
-        } else {
-            this.overheadResetFactor = overheadResetFactor;
-        }
+        this.overheadResetFactor = Math.max(overheadResetFactor, 0);
     }
 
 
diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java 
b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
index 5883095240..823addd6f3 100644
--- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -101,7 +101,7 @@ class Http2UpgradeHandler extends AbstractStream implements 
InternalHttpUpgradeH
     private volatile Http2Parser parser;
 
     // Simple state machine (sequence of states)
-    private AtomicReference<ConnectionState> connectionState = new 
AtomicReference<>(ConnectionState.NEW);
+    private final AtomicReference<ConnectionState> connectionState = new 
AtomicReference<>(ConnectionState.NEW);
     private volatile long pausedNanoTime = Long.MAX_VALUE;
 
     /**
@@ -152,7 +152,7 @@ class Http2UpgradeHandler extends AbstractStream implements 
InternalHttpUpgradeH
         // Over time the count should be a slowly decreasing negative number.
         // Therefore, the longer a connection is 'well-behaved', the greater
         // tolerance it will have for a period of 'bad' behaviour.
-        overheadCount = new AtomicLong(-10 * 
protocol.getOverheadCountFactor());
+        overheadCount = new AtomicLong(-10L * 
protocol.getOverheadCountFactor());
 
         lastNonFinalDataPayload = protocol.getOverheadDataThreshold() * 2;
         lastWindowUpdate = protocol.getOverheadWindowUpdateThreshold() * 2;
@@ -1183,12 +1183,7 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
             int leftToAllocate = allocation;
 
             if (stream.getConnectionAllocationRequested() > 0) {
-                int allocatedThisTime;
-                if (allocation >= stream.getConnectionAllocationRequested()) {
-                    allocatedThisTime = 
stream.getConnectionAllocationRequested();
-                } else {
-                    allocatedThisTime = allocation;
-                }
+                int allocatedThisTime = Math.min(allocation, 
stream.getConnectionAllocationRequested());
                 
stream.setConnectionAllocationRequested(stream.getConnectionAllocationRequested()
 - allocatedThisTime);
                 
stream.setConnectionAllocationMade(stream.getConnectionAllocationMade() + 
allocatedThisTime);
                 leftToAllocate = leftToAllocate - allocatedThisTime;
@@ -1404,7 +1399,7 @@ class Http2UpgradeHandler extends AbstractStream 
implements InternalHttpUpgradeH
         int len = length;
         int pos = offset;
         boolean nextReadBlock = block;
-        int thisRead = 0;
+        int thisRead;
 
         while (len > 0) {
             // Blocking reads use the protocol level read timeout. Non-blocking
diff --git a/java/org/apache/coyote/http2/Setting.java 
b/java/org/apache/coyote/http2/Setting.java
index cd86c09296..07fdd80737 100644
--- a/java/org/apache/coyote/http2/Setting.java
+++ b/java/org/apache/coyote/http2/Setting.java
@@ -44,37 +44,17 @@ enum Setting {
     }
 
     static Setting valueOf(int i) {
-        switch (i) {
-            case 1: {
-                return HEADER_TABLE_SIZE;
-            }
-            case 2: {
-                return ENABLE_PUSH;
-            }
-            case 3: {
-                return MAX_CONCURRENT_STREAMS;
-            }
-            case 4: {
-                return INITIAL_WINDOW_SIZE;
-            }
-            case 5: {
-                return MAX_FRAME_SIZE;
-            }
-            case 6: {
-                return MAX_HEADER_LIST_SIZE;
-            }
-            case 8: {
-                return ENABLE_CONNECT_PROTOCOL;
-            }
-            case 9: {
-                return NO_RFC7540_PRIORITIES;
-            }
-            case 10: {
-                return TLS_RENEG_PERMITTED;
-            }
-            default: {
-                return UNKNOWN;
-            }
-        }
+        return switch (i) {
+            case 1 -> HEADER_TABLE_SIZE;
+            case 2 -> ENABLE_PUSH;
+            case 3 -> MAX_CONCURRENT_STREAMS;
+            case 4 -> INITIAL_WINDOW_SIZE;
+            case 5 -> MAX_FRAME_SIZE;
+            case 6 -> MAX_HEADER_LIST_SIZE;
+            case 8 -> ENABLE_CONNECT_PROTOCOL;
+            case 9 -> NO_RFC7540_PRIORITIES;
+            case 10 -> TLS_RENEG_PERMITTED;
+            default -> UNKNOWN;
+        };
     }
 }
diff --git a/java/org/apache/coyote/http2/Stream.java 
b/java/org/apache/coyote/http2/Stream.java
index e514914fe7..27eccd661a 100644
--- a/java/org/apache/coyote/http2/Stream.java
+++ b/java/org/apache/coyote/http2/Stream.java
@@ -100,7 +100,7 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
     private volatile StringBuilder cookieHeader = null;
     private volatile boolean hostHeaderSeen = false;
 
-    private Object pendingWindowUpdateForStreamLock = new Object();
+    private final Object pendingWindowUpdateForStreamLock = new Object();
     private int pendingWindowUpdateForStream = 0;
 
     private volatile int urgency = Priority.DEFAULT_URGENCY;
@@ -342,7 +342,7 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
             return;
         }
 
-        if (name.length() == 0) {
+        if (name.isEmpty()) {
             throw new HpackException(sm.getString("stream.header.empty", 
getConnectionId(), getIdAsString()));
         }
 
@@ -387,7 +387,7 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
                     throw new HpackException(
                             sm.getString("stream.header.duplicate", 
getConnectionId(), getIdAsString(), ":path"));
                 }
-                if (value.length() == 0) {
+                if (value.isEmpty()) {
                     throw new 
HpackException(sm.getString("stream.header.noPath", getConnectionId(), 
getIdAsString()));
                 }
                 int queryStart = value.indexOf('?');
@@ -689,10 +689,7 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
 
     final boolean isContentLengthInconsistent() {
         long contentLengthHeader = coyoteRequest.getContentLengthLong();
-        if (contentLengthHeader > -1 && contentLengthReceived != 
contentLengthHeader) {
-            return true;
-        }
-        return false;
+        return contentLengthHeader > -1 && contentLengthReceived != 
contentLengthHeader;
     }
 
 
@@ -1059,12 +1056,8 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
                 // Bug 63682
                 // Only want to return false if the window size is zero AND we 
are
                 // already waiting for an allocation.
-                if (getWindowSize() > 0 && 
allocationManager.isWaitingForStream() ||
-                        handler.getWindowSize() > 0 && 
allocationManager.isWaitingForConnection() || dataLeft) {
-                    return false;
-                } else {
-                    return true;
-                }
+                return (getWindowSize() <= 0 || 
!allocationManager.isWaitingForStream()) &&
+                    (handler.getWindowSize() <= 0 || 
!allocationManager.isWaitingForConnection()) && !dataLeft;
             } finally {
                 writeLock.unlock();
             }
@@ -1182,7 +1175,7 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
 
             ensureBuffersExist();
 
-            int written = -1;
+            int written;
 
             // It is still possible that the stream has been closed and 
inBuffer
             // set to null between the call to ensureBuffersExist() above and
@@ -1448,7 +1441,7 @@ class Stream extends AbstractNonZeroStream implements 
HeaderEmitter {
                 readStateLock.unlock();
             }
             if (inBuffer != null) {
-                int unreadByteCount = 0;
+                int unreadByteCount;
                 synchronized (inBuffer) {
                     unreadByteCount = inBuffer.position();
                     if (log.isTraceEnabled()) {


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org

Reply via email to