Skip to content

Commit 8e7ab9f

Browse files
hferentschikgunnarmorling
authored andcommitted
BVAL-298 The current caching of the ValidationProviders don't work, because the providers themselves keep a hard reference to the class loaders. Wrapping the list of providers into a SoftReference instead (see also ValidationTest)
1 parent 17ccf14 commit 8e7ab9f

File tree

4 files changed

+191
-11
lines changed

4 files changed

+191
-11
lines changed

src/main/java/javax/validation/Validation.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616
*/
1717
package javax.validation;
1818

19+
import java.lang.ref.SoftReference;
1920
import java.security.AccessController;
2021
import java.security.PrivilegedAction;
2122
import java.util.ArrayList;
2223
import java.util.Iterator;
2324
import java.util.List;
24-
import java.util.Map;
2525
import java.util.ServiceConfigurationError;
2626
import java.util.ServiceLoader;
2727
import java.util.WeakHashMap;
@@ -295,8 +295,8 @@ private static class DefaultValidationProviderResolver implements ValidationProv
295295
//cache per classloader for an appropriate discovery
296296
//keep them in a weak hashmap to avoid memory leaks and allow proper hot redeployment
297297
//TODO use a WeakConcurrentHashMap
298-
private static final Map<ClassLoader, List<ValidationProvider<?>>> providersPerClassloader =
299-
new WeakHashMap<ClassLoader, List<ValidationProvider<?>>>();
298+
private static final WeakHashMap<ClassLoader, SoftReference<List<ValidationProvider<?>>>> providersPerClassloader =
299+
new WeakHashMap<ClassLoader, SoftReference<List<ValidationProvider<?>>>>();
300300

301301
public List<ValidationProvider<?>> getValidationProviders() {
302302
List<ValidationProvider<?>> validationProviderList = new ArrayList<ValidationProvider<?>>();
@@ -340,11 +340,12 @@ public List<ValidationProvider<?>> getValidationProviders() {
340340
}
341341

342342
private synchronized List<ValidationProvider<?>> getCachedValidationProviders(ClassLoader classLoader) {
343-
return providersPerClassloader.get( classLoader );
343+
SoftReference<List<ValidationProvider<?>>> ref = providersPerClassloader.get( classLoader );
344+
return ref != null ? ref.get() : null;
344345
}
345346

346347
private synchronized void cacheValidationProviders(ClassLoader classLoader, List<ValidationProvider<?>> providers) {
347-
providersPerClassloader.put( classLoader, providers );
348+
providersPerClassloader.put( classLoader, new SoftReference<List<ValidationProvider<?>>>( providers ) );
348349
}
349350
}
350351

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/*
2+
* JBoss, Home of Professional Open Source
3+
* Copyright 2012, Red Hat, Inc. and/or its affiliates, and individual contributors
4+
* by the @authors tag. See the copyright.txt in the distribution for a
5+
* full listing of individual contributors.
6+
*
7+
* Licensed under the Apache License, Version 2.0 (the "License");
8+
* you may not use this file except in compliance with the License.
9+
* You may obtain a copy of the License at
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
package javax.validation;
18+
19+
import java.io.InputStream;
20+
import java.lang.ref.SoftReference;
21+
import java.util.ArrayList;
22+
import java.util.List;
23+
import javax.validation.spi.BootstrapState;
24+
import javax.validation.spi.ConfigurationState;
25+
import javax.validation.spi.ValidationProvider;
26+
27+
/**
28+
* @author Hardy Ferentschik
29+
*/
30+
public class DummyValidationProvider implements ValidationProvider {
31+
public static List<SoftReference<DummyValidationProvider>> createdValidationProviders = new ArrayList<SoftReference<DummyValidationProvider>>();
32+
33+
public DummyValidationProvider() {
34+
createdValidationProviders.add( new SoftReference<DummyValidationProvider>( this ) );
35+
}
36+
37+
public Configuration createSpecializedConfiguration(BootstrapState state) {
38+
return null;
39+
}
40+
41+
public Configuration<?> createGenericConfiguration(BootstrapState state) {
42+
return new DummyConfiguration();
43+
}
44+
45+
public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
46+
return null;
47+
}
48+
49+
50+
public static class DummyConfiguration implements Configuration {
51+
52+
public Configuration ignoreXmlConfiguration() {
53+
return null;
54+
}
55+
56+
public Configuration messageInterpolator(MessageInterpolator interpolator) {
57+
return null;
58+
}
59+
60+
public Configuration traversableResolver(TraversableResolver resolver) {
61+
return null;
62+
}
63+
64+
public Configuration constraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
65+
return null;
66+
}
67+
68+
public Configuration parameterNameProvider(ParameterNameProvider parameterNameProvider) {
69+
return null;
70+
}
71+
72+
public Configuration addMapping(InputStream stream) {
73+
return null;
74+
}
75+
76+
public Configuration addProperty(String name, String value) {
77+
return null;
78+
}
79+
80+
public MessageInterpolator getDefaultMessageInterpolator() {
81+
return null;
82+
}
83+
84+
public TraversableResolver getDefaultTraversableResolver() {
85+
return null;
86+
}
87+
88+
public ConstraintValidatorFactory getDefaultConstraintValidatorFactory() {
89+
return null;
90+
}
91+
92+
public ParameterNameProvider getDefaultParameterNameProvider() {
93+
return null;
94+
}
95+
96+
public ConfigurationSource getConfigurationSource() {
97+
return null;
98+
}
99+
100+
public ValidatorFactory buildValidatorFactory() {
101+
return null;
102+
}
103+
}
104+
}
105+
106+

src/test/java/javax/validation/ValidationTest.java

Lines changed: 78 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,18 @@
1717
package javax.validation;
1818

1919

20+
import java.io.IOException;
21+
import java.lang.ref.SoftReference;
2022
import java.net.URL;
2123
import java.net.URLClassLoader;
24+
import java.util.Enumeration;
25+
import javax.validation.spi.ValidationProvider;
2226

2327
import org.testng.annotations.Test;
2428

25-
import static org.testng.AssertJUnit.assertEquals;
26-
import static org.testng.AssertJUnit.fail;
29+
import static org.testng.Assert.assertEquals;
30+
import static org.testng.Assert.assertTrue;
31+
import static org.testng.Assert.fail;
2732

2833
/**
2934
* @author Hardy Ferentschik
@@ -41,9 +46,11 @@ public void testCurrentClassLoaderIsUsedInCaseContextClassLoaderCannotLoadServic
4146
fail();
4247
}
4348
catch ( ValidationException e ) {
49+
// the custom context URL class loader cannot load the service file, so the exception
50+
// must be triggered by using the current class loader
4451
assertEquals(
45-
"Unable to load Bean Validation provider non.existent.ValidationProvider",
46-
e.getMessage()
52+
e.getMessage(),
53+
"Unable to load Bean Validation provider non.existent.ValidationProvider"
4754
);
4855
}
4956
finally {
@@ -61,15 +68,80 @@ public void testCurrentClassLoaderIsUsedInCaseContextClassLoaderIsNull() {
6168
fail();
6269
}
6370
catch ( ValidationException e ) {
71+
// context class loader is not. exception must be caused by using the current class loader
6472
assertEquals(
65-
"Unable to load Bean Validation provider non.existent.ValidationProvider",
66-
e.getMessage()
73+
e.getMessage(),
74+
"Unable to load Bean Validation provider non.existent.ValidationProvider"
6775
);
6876
}
6977
finally {
7078
Thread.currentThread().setContextClassLoader( contextClassLoader );
7179
}
7280
}
81+
82+
// BVAL-298
83+
@Test
84+
public void testCachedProvidersCanBeGarbageCollected() {
85+
int LOOP_COUNT = 100;
86+
87+
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
88+
try {
89+
for ( int i = 1; i <= LOOP_COUNT; i++ ) {
90+
Thread.currentThread().setContextClassLoader( new CustomValidationXmlClassLoader( "-2" ) );
91+
Validation.buildDefaultValidatorFactory();
92+
}
93+
94+
int createdProviders = countInMemoryProviders();
95+
assertTrue( createdProviders > 1, "There should be cached providers" );
96+
97+
try {
98+
byte[][] buf = new byte[1024][];
99+
for ( int i = 0; i < buf.length; i++ ) {
100+
buf[i] = new byte[10 * 1024 * 1024];
101+
}
102+
fail( "The byte array allocation should have triggered a OutOfMemoryError" );
103+
}
104+
catch ( OutOfMemoryError ex ) {
105+
// expected
106+
}
107+
108+
// the VM guarantees that all soft references are cleared before a OutOfMemoryError occurs
109+
assertEquals( countInMemoryProviders(), 0 );
110+
}
111+
finally {
112+
Thread.currentThread().setContextClassLoader( contextClassLoader );
113+
}
114+
}
115+
116+
private int countInMemoryProviders() {
117+
int count = 0;
118+
// we cannot access Validation.DefaultValidationProviderResolver#providersPerClassloader, so we have to
119+
// indirectly count the providers via DummyValidationProvider#createdValidationProviders
120+
for ( SoftReference<DummyValidationProvider> ref : DummyValidationProvider.createdValidationProviders ) {
121+
if ( ref.get() != null ) {
122+
count++;
123+
}
124+
}
125+
return count;
126+
}
127+
128+
public static class CustomValidationXmlClassLoader extends ClassLoader {
129+
private static final String SERVICES_FILE = "META-INF/services/" + ValidationProvider.class.getName();
130+
private final String validationXmlSuffix;
131+
132+
133+
public CustomValidationXmlClassLoader(String suffix) {
134+
super( CustomValidationXmlClassLoader.class.getClassLoader() );
135+
this.validationXmlSuffix = suffix;
136+
}
137+
138+
public Enumeration<URL> getResources(String name) throws IOException {
139+
if ( SERVICES_FILE.equals( name ) && validationXmlSuffix != null ) {
140+
name = name + validationXmlSuffix;
141+
}
142+
return super.getResources( name );
143+
}
144+
}
73145
}
74146

75147

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
javax.validation.DummyValidationProvider

0 commit comments

Comments
 (0)