Skip to content

Commit ea19ad2

Browse files
SentryManMichael-Mc-Mahon
authored andcommitted
8347167: Reduce allocation in com.sun.net.httpserver.Headers::normalize
Reviewed-by: vyazici, dfuchs, michaelm
1 parent 267ce91 commit ea19ad2

File tree

3 files changed

+268
-20
lines changed

3 files changed

+268
-20
lines changed

src/jdk.httpserver/share/classes/com/sun/net/httpserver/Headers.java

Lines changed: 59 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
2+
* Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
33
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
*
55
* This code is free software; you can redistribute it and/or modify it
@@ -109,29 +109,69 @@ public Headers(Map<String,List<String>> headers) {
109109
}
110110

111111
/**
112-
* Normalize the key by converting to following form.
113-
* First {@code char} upper case, rest lower case.
114-
* key is presumed to be {@code ASCII}.
112+
* {@return the normalized header name of the following form: the first
113+
* character in upper-case, the rest in lower-case}
114+
* The input header name is assumed to be encoded in ASCII.
115+
*
116+
* @implSpec
117+
* This method is performance-sensitive; update with care.
118+
*
119+
* @param key an ASCII-encoded header name
120+
* @throws NullPointerException on null {@code key}
121+
* @throws IllegalArgumentException if {@code key} contains {@code \r} or {@code \n}
115122
*/
116-
private String normalize(String key) {
123+
private static String normalize(String key) {
124+
125+
// Fast path for the empty key
117126
Objects.requireNonNull(key);
118-
int len = key.length();
119-
if (len == 0) {
127+
int l = key.length();
128+
if (l == 0) {
129+
return key;
130+
}
131+
132+
// Find the first non-normalized `char`
133+
int i = 0;
134+
char c = key.charAt(i);
135+
if (!(c == '\r' || c == '\n' || (c >= 'a' && c <= 'z'))) {
136+
i++;
137+
for (; i < l; i++) {
138+
c = key.charAt(i);
139+
if (c == '\r' || c == '\n' || (c >= 'A' && c <= 'Z')) {
140+
break;
141+
}
142+
}
143+
}
144+
145+
// Fast path for the already normalized key
146+
if (i == l) {
120147
return key;
121148
}
122-
char[] b = key.toCharArray();
123-
if (b[0] >= 'a' && b[0] <= 'z') {
124-
b[0] = (char)(b[0] - ('a' - 'A'));
125-
} else if (b[0] == '\r' || b[0] == '\n')
126-
throw new IllegalArgumentException("illegal character in key");
127-
128-
for (int i=1; i<len; i++) {
129-
if (b[i] >= 'A' && b[i] <= 'Z') {
130-
b[i] = (char) (b[i] + ('a' - 'A'));
131-
} else if (b[i] == '\r' || b[i] == '\n')
132-
throw new IllegalArgumentException("illegal character in key");
149+
150+
// Upper-case the first `char`
151+
char[] cs = key.toCharArray();
152+
int o = 'a' - 'A';
153+
if (i == 0) {
154+
if (c == '\r' || c == '\n') {
155+
throw new IllegalArgumentException("illegal character in key at index " + i);
156+
}
157+
if (c >= 'a' && c <= 'z') {
158+
cs[0] = (char) (c - o);
159+
}
160+
i++;
133161
}
134-
return new String(b);
162+
163+
// Lower-case the secondary `char`s
164+
for (; i < l; i++) {
165+
c = cs[i];
166+
if (c >= 'A' && c <= 'Z') {
167+
cs[i] = (char) (c + o);
168+
} else if (c == '\r' || c == '\n') {
169+
throw new IllegalArgumentException("illegal character in key at index " + i);
170+
}
171+
}
172+
173+
return new String(cs);
174+
135175
}
136176

137177
@Override

test/jdk/com/sun/net/httpserver/HeadersTest.java

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.
2+
* Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
33
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
*
55
* This code is free software; you can redistribute it and/or modify it
@@ -49,6 +49,9 @@
4949
import java.util.List;
5050
import java.util.Map;
5151
import java.util.concurrent.CompletableFuture;
52+
import java.util.stream.IntStream;
53+
import java.util.stream.Stream;
54+
5255
import com.sun.net.httpserver.Headers;
5356
import com.sun.net.httpserver.HttpExchange;
5457
import com.sun.net.httpserver.HttpHandler;
@@ -62,6 +65,8 @@
6265
import static org.testng.Assert.assertEquals;
6366
import static org.testng.Assert.assertFalse;
6467
import static org.testng.Assert.assertNotEquals;
68+
import static org.testng.Assert.assertNotSame;
69+
import static org.testng.Assert.assertSame;
6570
import static org.testng.Assert.assertThrows;
6671
import static org.testng.Assert.assertTrue;
6772

@@ -288,7 +293,14 @@ public static void testPutAll() {
288293
final var list = new ArrayList<String>();
289294
list.add(null);
290295
assertThrows(NPE, () -> h0.putAll(Map.of("a", list)));
296+
assertThrows(IAE, () -> h0.putAll(Map.of("a", List.of("\r"))));
291297
assertThrows(IAE, () -> h0.putAll(Map.of("a", List.of("\n"))));
298+
assertThrows(IAE, () -> h0.putAll(Map.of("a", List.of("a\r"))));
299+
assertThrows(IAE, () -> h0.putAll(Map.of("a", List.of("a\n"))));
300+
assertThrows(IAE, () -> h0.putAll(Map.of("\r", List.of("a"))));
301+
assertThrows(IAE, () -> h0.putAll(Map.of("\n", List.of("a"))));
302+
assertThrows(IAE, () -> h0.putAll(Map.of("a\r", List.of("a"))));
303+
assertThrows(IAE, () -> h0.putAll(Map.of("a\n", List.of("a"))));
292304

293305
final var h1 = new Headers();
294306
h1.put("a", List.of("1"));
@@ -443,5 +455,81 @@ public static void testOfMultipleValues() {
443455
List.of(List.of("1"), List.of("1", "2", "3")).forEach(v -> assertTrue(h.containsValue(v)));
444456
}
445457

458+
@Test
459+
public static void testNormalizeOnNull() {
460+
assertThrows(NullPointerException.class, () -> normalize(null));
461+
}
462+
463+
@DataProvider
464+
public static Object[][] illegalKeys() {
465+
var illegalChars = List.of('\r', '\n');
466+
var illegalStrings = Stream
467+
// Insert an illegal char at every possible position of following strings
468+
.of("Ab", "ab", "_a", "2a")
469+
.flatMap(s -> IntStream
470+
.range(0, s.length() + 1)
471+
.boxed()
472+
.flatMap(i -> illegalChars
473+
.stream()
474+
.map(c -> s.substring(0, i) + c + s.substring(i))));
475+
return Stream
476+
.concat(illegalChars.stream().map(c -> "" + c), illegalStrings)
477+
.map(s -> new Object[]{s})
478+
.toArray(Object[][]::new);
479+
}
480+
481+
@Test(dataProvider = "illegalKeys")
482+
public static void testNormalizeOnIllegalKeys(String illegalKey) {
483+
assertThrows(IllegalArgumentException.class, () -> normalize(illegalKey));
484+
}
485+
486+
@DataProvider
487+
public static Object[][] normalizedKeys() {
488+
return new Object[][]{
489+
// Empty string
490+
{""},
491+
// Non-alpha prefix
492+
{"_"},
493+
{"0"},
494+
{"_xy-@"},
495+
{"0xy-@"},
496+
// Upper-case prefix
497+
{"A"},
498+
{"B"},
499+
{"Ayz-@"},
500+
{"Byz-@"},
501+
};
502+
}
503+
504+
@Test(dataProvider = "normalizedKeys")
505+
public static void testNormalizeOnNormalizedKeys(String normalizedKey) {
506+
// Verify that the fast-path is taken
507+
assertSame(normalize(normalizedKey), normalizedKey);
508+
}
509+
510+
@DataProvider
511+
public static Object[][] notNormalizedKeys() {
512+
return new Object[][]{
513+
{"a"},
514+
{"b"},
515+
{"axy-@"},
516+
{"bxy-@"},
517+
};
518+
}
519+
520+
@Test(dataProvider = "notNormalizedKeys")
521+
public static void testNormalizeOnNotNormalizedKeys(String notNormalizedKey) {
522+
var normalizedKey = normalize(notNormalizedKey);
523+
// Verify that the fast-path is *not* taken
524+
assertNotSame(normalizedKey, notNormalizedKey);
525+
// Verify the result
526+
var expectedNormalizedKey = normalizedKey.substring(0, 1).toUpperCase() + normalizedKey.substring(1);
527+
assertEquals(normalizedKey, expectedNormalizedKey);
528+
}
529+
530+
private static String normalize(String key) {
531+
return Headers.of(key, "foo").keySet().iterator().next();
532+
}
533+
446534
// Immutability tests in UnmodifiableHeadersTest.java
447535
}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/*
2+
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation.
8+
*
9+
* This code is distributed in the hope that it will be useful, but WITHOUT
10+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12+
* version 2 for more details (a copy is included in the LICENSE file that
13+
* accompanied this code).
14+
*
15+
* You should have received a copy of the GNU General Public License version
16+
* 2 along with this work; if not, write to the Free Software Foundation,
17+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18+
*
19+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20+
* or visit www.oracle.com if you need additional information or have any
21+
* questions.
22+
*/
23+
package org.openjdk.bench.sun.net.httpserver;
24+
25+
import com.sun.net.httpserver.Headers;
26+
import org.openjdk.jmh.annotations.*;
27+
28+
import java.lang.invoke.MethodHandle;
29+
import java.lang.invoke.MethodHandles;
30+
import java.lang.invoke.MethodType;
31+
import java.util.Objects;
32+
import java.util.concurrent.TimeUnit;
33+
import java.util.function.Function;
34+
35+
/**
36+
* Benchmarks {@code jdk.httpserver} header normalization.
37+
* <p>
38+
* You can run this benchmark as follows:
39+
* <pre>{@code
40+
* make run-test TEST="micro:HeaderNormalization" MICRO="OPTIONS=-prof gc"
41+
* }</pre>
42+
*/
43+
@BenchmarkMode(Mode.AverageTime)
44+
@Warmup(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS)
45+
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
46+
@State(org.openjdk.jmh.annotations.Scope.Thread)
47+
@OutputTimeUnit(TimeUnit.NANOSECONDS)
48+
@Fork(value = 3, jvmArgs = {
49+
"--add-exports", "jdk.httpserver/com.sun.net.httpserver=ALL-UNNAMED",
50+
"--add-opens", "jdk.httpserver/com.sun.net.httpserver=ALL-UNNAMED",
51+
})
52+
public class HeaderNormalization {
53+
54+
private static final Function<String, String> NORMALIZE = findNormalize();
55+
56+
private static Function<String, String> findNormalize() {
57+
var lookup = MethodHandles.lookup();
58+
MethodHandle handle;
59+
try {
60+
handle = MethodHandles
61+
.privateLookupIn(Headers.class, lookup)
62+
.findStatic(
63+
Headers.class, "normalize",
64+
MethodType.methodType(String.class, String.class));
65+
} catch (Exception e) {
66+
throw new RuntimeException(e);
67+
}
68+
return key -> {
69+
try {
70+
return (String) handle.invokeExact(key);
71+
} catch (Throwable e) {
72+
throw new RuntimeException(e);
73+
}
74+
};
75+
}
76+
77+
@Param({
78+
"Accept-charset", // Already normalized
79+
"4ccept-charset", // Already normalized with a non-alpha first letter
80+
"accept-charset", // Only the first `a` must be upper-cased
81+
"Accept-Charset", // Only `c` must be lower-cased
82+
"ACCEPT-CHARSET", // All secondary must be lower-cased
83+
})
84+
private String key;
85+
86+
@Benchmark
87+
public String n26() {
88+
return NORMALIZE.apply(key);
89+
}
90+
91+
@Benchmark
92+
public String n25() {
93+
return normalize25(key);
94+
}
95+
96+
/**
97+
* The {@code com.sun.net.httpserver.Headers::normalize} method used in Java 25 and before.
98+
*/
99+
private static String normalize25(String key) {
100+
Objects.requireNonNull(key);
101+
int len = key.length();
102+
if (len == 0) {
103+
return key;
104+
}
105+
char[] b = key.toCharArray();
106+
if (b[0] >= 'a' && b[0] <= 'z') {
107+
b[0] = (char)(b[0] - ('a' - 'A'));
108+
} else if (b[0] == '\r' || b[0] == '\n')
109+
throw new IllegalArgumentException("illegal character in key");
110+
111+
for (int i=1; i<len; i++) {
112+
if (b[i] >= 'A' && b[i] <= 'Z') {
113+
b[i] = (char) (b[i] + ('a' - 'A'));
114+
} else if (b[i] == '\r' || b[i] == '\n')
115+
throw new IllegalArgumentException("illegal character in key");
116+
}
117+
return new String(b);
118+
}
119+
120+
}

0 commit comments

Comments
 (0)