2626#include " memory/allocation.inline.hpp"
2727#include " memory/metaspace.hpp"
2828#include " runtime/mutex.hpp"
29+ #include " runtime/mutexLocker.hpp"
2930#include " runtime/os.hpp"
3031#include " utilities/align.hpp"
3132#include " utilities/debug.hpp"
@@ -104,7 +105,12 @@ class MetaspaceAllocationTest : public ::testing::Test {
104105 // Let every ~10th space be an anonymous one to test different allocation patterns.
105106 const Metaspace::MetaspaceType msType = (os::random () % 100 < 10 ) ?
106107 Metaspace::AnonymousMetaspaceType : Metaspace::StandardMetaspaceType;
107- _spaces[i].space = new ClassLoaderMetaspace (_spaces[i].lock , msType);
108+ {
109+ // Pull lock during space creation, since this is what happens in the VM too
110+ // (see ClassLoaderData::metaspace_non_null(), which we mimick here).
111+ MutexLockerEx ml (_spaces[i].lock , Mutex::_no_safepoint_check_flag);
112+ _spaces[i].space = new ClassLoaderMetaspace (_spaces[i].lock , msType);
113+ }
108114 _spaces[i].allocated = 0 ;
109115 ASSERT_TRUE (_spaces[i].space != NULL );
110116 }
@@ -171,6 +177,7 @@ class MetaspaceAllocationTest : public ::testing::Test {
171177 } else {
172178 size = os::random () % 64 ;
173179 }
180+ // Note: In contrast to space creation, no need to lock here. ClassLoaderMetaspace::allocate() will lock itself.
174181 MetaWord* const p = _spaces[index].space ->allocate (size, mdType);
175182 if (p == NULL ) {
176183 // We very probably did hit the metaspace "until-gc" limit.
@@ -196,6 +203,7 @@ class MetaspaceAllocationTest : public ::testing::Test {
196203 force_switch = true ;
197204 } else {
198205 assert (_spaces[index].space != NULL && _spaces[index].allocated > 0 , " Sanity" );
206+ // Note: do not lock here. In the "wild" (the VM), we do not so either (see ~ClassLoaderData()).
199207 delete _spaces[index].space ;
200208 _spaces[index].space = NULL ;
201209 _spaces[index].allocated = 0 ;
0 commit comments