private Region getRegion ( ) { while ( true ) { // Try to get the region Region region = currentRegion . get ( ) ; if ( region != null ) return region ; // No current region, so we want to allocate one. We race // against other allocators to CAS in a Region, and if we fail we stash the region for re-use region = RACE_ALLOCATED . poll ( ) ; if ( region == null ) region = new Region ( allocateOnHeapOnly ? ByteBuffer . allocate ( REGION_SIZE ) : ByteBuffer . allocateDirect ( REGION_SIZE ) ) ; if ( currentRegion . compareAndSet ( null , region ) ) { if ( ! allocateOnHeapOnly ) offHeapRegions . add ( region ) ; regionCount . incrementAndGet ( ) ; logger . trace ( "{} regions now allocated in {}" , regionCount , this ) ; return region ; } // someone else won race - that's fine, we'll try to grab theirs // in the next iteration of the loop. RACE_ALLOCATED . add ( region ) ; } }
Get the current region or if there is no current region allocate a new one