Top Description Inners Fields Constructors Methods
net.sf.ehcache.store.disk

public Class Segment

extends ReentrantReadWriteLock
Class Inheritance
Imports
net.sf.ehcache.CacheOperationOutcomes.EvictionOutcome, .Element, net.sf.ehcache.config.CacheConfiguration, .PinningConfiguration, net.sf.ehcache.event.RegisteredEventListeners, net.sf.ehcache.pool.PoolAccessor, net.sf.ehcache.store.ElementValueComparator, net.sf.ehcache.store.disk.DiskStorageFactory.DiskMarker, .DiskStorageFactory.DiskSubstitute, .DiskStorageFactory.Placeholder, net.sf.ehcache.util.FindBugsSuppressWarnings, org.slf4j.Logger, .LoggerFactory, org.terracotta.statistics.observer.OperationObserver, java.io.Serializable, java.util.Collection, .Iterator, .NoSuchElementException, java.util.concurrent.atomic.AtomicBoolean, java.util.concurrent.locks.ReentrantReadWriteLock

Segment implementation used in LocalStore.

The segment extends ReentrantReadWriteLock to allow read locking on read operations. In addition to the typical CHM-like methods, this classes additionally supports replacement under a read lock - which is accomplished using an atomic CAS on the associated HashEntry.

Authors
Chris Dennis, Ludovic Orban

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv class
Segment.HashIterator

An iterator over the HashEntry objects within this Segment.

Field Summary

Modifier and TypeField and Description
private final RegisteredEventListeners
private volatile boolean
protected volatile int
count

Count of elements in the map.

private final DiskStorageFactory
disk

The primary substitute factory.

private final OperationObserver<CacheOperationOutcomes.EvictionOutcome>
private static final float
private static final Logger
private static final int
protected int
modCount

Mod-count used to track concurrent modifications when doing size calculations or iterating over the store.

private static final HashEntry
private final PoolAccessor<T extends PoolParticipant>
private final PoolAccessor<T extends PoolParticipant>
private volatile HashEntry[]
table

Table of HashEntry linked lists, indexed by the least-significant bits of the spread-hash value.

private int
threshold

Size at which the next rehashing of this Segment should occur

Constructor Summary

AccessConstructor and Description
public
Segment(int
initial capacity of store
initialCapacity
,
float
fraction of capacity at which rehash occurs
loadFactor
,
DiskStorageFactory
primary element substitute factory
primary
,
CacheConfiguration
the cache configuration
cacheConfiguration
,
PoolAccessor<T extends PoolParticipant>
the pool tracking on-heap usage
onHeapPoolAccessor
,
PoolAccessor<T extends PoolParticipant>
the pool tracking on-disk usage
onDiskPoolAccessor
,
RegisteredEventListeners cacheEventNotificationService, OperationObserver<CacheOperationOutcomes.EvictionOutcome> evictionObserver)

Create a Segment with the given initial capacity, load-factor, primary element substitute factory, and identity element substitute factory.

Method Summary

Modifier and TypeMethod and Description
pack-priv void
addRandomSample(ElementSubstituteFilter
filter of substitute types
filter
,
int
minimum number of elements to return
sampleSize
,
Collection<DiskStorageFactory.DiskSubstitute>
collection in which to place the elements
sampled
,
int
random seed for the selection
seed
)

Select a random sample of elements generated by the supplied factory.

pack-priv boolean

Returns:

true if a failed marker was or is still there, false otherwise
cleanUpFailedMarker
(final Serializable
the key
key
,
final int
the key's hash
hash
)

Will check whether a Placeholder that failed to flush to disk is lying around If so, it'll try to evict it

pack-priv void
clear()

Removes all mappings from this segment.

pack-priv void
clearFaultedBit()

Clears the faulted but on all entries

pack-priv boolean

Returns:

true if there is a mapping for this key
containsKey
(Object
key to check for
key
,
int
spread-hash for key
hash
)

Return true if this segment contains a mapping for this key

private Element

Returns:

the decoded DiskSubstitute
decode
(Object
the DiskSubstitute to decode
object
)

Decode the possible DiskSubstitute

private Element

Returns:

the decoded DiskSubstitute
decodeHit
(Object
the DiskSubstitute to decode
object
)

Decode the possible DiskSubstitute, updating the statistics

private static boolean
pack-priv Element

Returns:

true on a successful remove
evict
(Object
key to match against
key
,
int
spread-hash for the key
hash
,
DiskStorageFactory.DiskSubstitute
optional value to match against
value
)

Remove the matching mapping.

pack-priv Element

Returns:

true on a successful remove
evict
(Object
key to match against
key
,
int
spread-hash for the key
hash
,
DiskStorageFactory.DiskSubstitute
optional value to match against
value
,
boolean
whether to notify if we evict something
notify
)

Remove the matching mapping.

pack-priv boolean

Returns:

true if fault was installed
fault
(Object
key to which this element (proxy) is mapped
key
,
int
the hash of the key
hash
,
DiskStorageFactory.Placeholder
element (proxy) expected
expect
,
DiskStorageFactory.DiskMarker
element (proxy) to install
fault
,
final boolean skipFaulted)

Try to atomically switch (CAS) the expect representation of this element for the fault representation.

private boolean
faultInternal(final Object key, final int hash, final DiskStorageFactory.Placeholder expect, final DiskStorageFactory.DiskMarker fault, final boolean skipFaulted)

private boolean
findAndFree(final Object key, final int hash, final DiskStorageFactory.Placeholder expect, final DiskStorageFactory.DiskMarker fault)

pack-priv boolean

Returns:

true if succeeded
flush
(final Object
the key
key
,
final int
they hash
hash
,
final Element
the expected element
element
)

Marks an entry as flushable to disk (i.e. not faulted in higher tiers) Also updates the access stats

private void
free(Object
the DiskSubstitute to free
object
)

Free the DiskSubstitute

private void
free(Object
the DiskSubstitute to free
object
,
boolean
true if the DiskSubstitute should be freed because of a fault failure
faultFailure
)

Free the DiskSubstitute indicating if it could not be faulted

pack-priv Element

Returns:

mapped element
get
(Object
key to lookup
key
,
int
spread-hash for this key
hash
,
final boolean markFaulted)

Get the element mapped to this key (or null if there is no mapping for this key)

private HashEntry
getFirst(int hash)

pack-priv Iterator<HashEntry>

Returns:

an iterator over the HashEntry objects within this Segment.
hashIterator
()

Creates an iterator over the HashEntry objects within this Segment.

public boolean

Returns:

true if faulted, false otherwise (including no mapping)
isFaulted
(final int hash, final Object
the key to check the mapping for
key
)

Verifies if the mapping for a key is marked as faulted

private void
notifyEviction(final Element evicted)

pack-priv Element

Returns:

previous element mapped to this key
put
(Object
key to map the element to
key
,
int
spread-hash for the key
hash
,
Element
element to store
element
,
boolean
if true does not replace existing mappings
onlyIfAbsent
,
boolean faulted)

Add the supplied mapping.

pack-priv boolean

Returns:

true if the encoded element was installed
putRawIfAbsent
(Object
key to map the element to
key
,
int
spread-hash for the key
hash
,
DiskStorageFactory.DiskMarker
encoded element to store
encoded
)

Add the supplied pre-encoded mapping.

private void
pack-priv Element

Returns:

removed element
remove
(Object
key to match against
key
,
int
spread-hash for the key
hash
,
Element
optional value to match against
value
,
ElementValueComparator
the comparator to use to compare values
comparator
)

Remove the matching mapping.

pack-priv boolean

Returns:

true on a successful replace
replace
(Object
key to map the element to
key
,
int
spread-hash for the key
hash
,
Element
expected element
oldElement
,
Element
element to add
newElement
,
ElementValueComparator
the comparator to use to compare values
comparator
)

Replace the element mapped to this key only if currently mapped to the given element.

pack-priv Element

Returns:

previous element mapped to this key
replace
(Object
key to map the element to
key
,
int
spread-hash for the key
hash
,
Element
element to add
newElement
)

Replace the entry for this key only if currently mapped to some element.

private boolean
returnSafeDeprecated(final Object key, final int hash, final Element element)

Deprecated
public String
toString()

Overrides java.util.concurrent.locks.ReentrantReadWriteLock.toString.

Returns a string identifying this lock, as well as its lock state.
pack-priv Object

Returns:

Element or ElementSubstitute
unretrievedGet
(Object
key to lookup
key
,
int
spread-hash for the key
hash
)

Return the unretrieved (undecoded) value for this key

Inherited from java.util.concurrent.locks.ReentrantReadWriteLock:
getOwnergetQueuedReaderThreadsgetQueuedThreadsgetQueuedWriterThreadsgetQueueLengthgetReadHoldCountgetReadLockCountgetWaitingThreadsgetWaitQueueLengthgetWriteHoldCounthasQueuedThreadhasQueuedThreadshasWaitersisFairisWriteLockedisWriteLockedByCurrentThreadreadLockwriteLock

Field Detail

cacheEventNotificationServiceback to summary
private final RegisteredEventListeners cacheEventNotificationService
cachePinnedback to summary
private volatile boolean cachePinned
countback to summary
protected volatile int count

Count of elements in the map.

A volatile reference is needed here for the same reasons as in the table reference.

diskback to summary
private final DiskStorageFactory disk

The primary substitute factory.

This is the substitute type used to store Elements when they are first added to the store.

evictionObserverback to summary
private final OperationObserver<CacheOperationOutcomes.EvictionOutcome> evictionObserver
LOAD_FACTORback to summary
private static final float LOAD_FACTOR
LOGback to summary
private static final Logger LOG
MAXIMUM_CAPACITYback to summary
private static final int MAXIMUM_CAPACITY
modCountback to summary
protected int modCount

Mod-count used to track concurrent modifications when doing size calculations or iterating over the store.

Note that we don't actually have any iterators yet...

NULL_HASH_ENTRYback to summary
private static final HashEntry NULL_HASH_ENTRY
onDiskPoolAccessorback to summary
private final PoolAccessor<T extends PoolParticipant> onDiskPoolAccessor
onHeapPoolAccessorback to summary
private final PoolAccessor<T extends PoolParticipant> onHeapPoolAccessor
tableback to summary
private volatile HashEntry[] table

Table of HashEntry linked lists, indexed by the least-significant bits of the spread-hash value.

A volatile reference is needed to ensure the visibility of table changes made during rehash operations to size operations. Key operations are done under read-locks so there is no need for volatility in that regard. Hence if we switched to read-locked size operations, we wouldn't need a volatile reference here.

thresholdback to summary
private int threshold

Size at which the next rehashing of this Segment should occur

Constructor Detail

Segmentback to summary
public Segment(int initialCapacity, float loadFactor, DiskStorageFactory primary, CacheConfiguration cacheConfiguration, PoolAccessor<T extends PoolParticipant> onHeapPoolAccessor, PoolAccessor<T extends PoolParticipant> onDiskPoolAccessor, RegisteredEventListeners cacheEventNotificationService, OperationObserver<CacheOperationOutcomes.EvictionOutcome> evictionObserver)

Create a Segment with the given initial capacity, load-factor, primary element substitute factory, and identity element substitute factory.

An identity element substitute factory is specified at construction time because only one subclass of IdentityElementProxyFactory can be used with a Segment. Without this requirement the mapping between bare net.sf.ehcache.Element instances and the factory responsible for them would be ambiguous.

If a null identity element substitute factory is specified then encountering a raw element (i.e. as a result of using an identity element substitute factory) will result in a null pointer exception during decode.

Parameters
initialCapacity:int

initial capacity of store

loadFactor:float

fraction of capacity at which rehash occurs

primary:DiskStorageFactory

primary element substitute factory

cacheConfiguration:CacheConfiguration

the cache configuration

onHeapPoolAccessor:PoolAccessor<T extends PoolParticipant>

the pool tracking on-heap usage

onDiskPoolAccessor:PoolAccessor<T extends PoolParticipant>

the pool tracking on-disk usage

Method Detail

addRandomSampleback to summary
pack-priv void addRandomSample(ElementSubstituteFilter filter, int sampleSize, Collection<DiskStorageFactory.DiskSubstitute> sampled, int seed)

Select a random sample of elements generated by the supplied factory.

Parameters
filter:ElementSubstituteFilter

filter of substitute types

sampleSize:int

minimum number of elements to return

sampled:Collection<DiskStorageFactory.DiskSubstitute>

collection in which to place the elements

seed:int

random seed for the selection

cleanUpFailedMarkerback to summary
pack-priv boolean cleanUpFailedMarker(final Serializable key, final int hash)

Will check whether a Placeholder that failed to flush to disk is lying around If so, it'll try to evict it

Parameters
key:Serializable

the key

hash:int

the key's hash

Returns:boolean

true if a failed marker was or is still there, false otherwise

Annotations
@FindBugsSuppressWarnings:UL_UNRELEASED_LOCK
clearback to summary
pack-priv void clear()

Removes all mappings from this segment.

clearFaultedBitback to summary
pack-priv void clearFaultedBit()

Clears the faulted but on all entries

containsKeyback to summary
pack-priv boolean containsKey(Object key, int hash)

Return true if this segment contains a mapping for this key

Parameters
key:Object

key to check for

hash:int

spread-hash for key

Returns:boolean

true if there is a mapping for this key

decodeback to summary
private Element decode(Object object)

Decode the possible DiskSubstitute

Parameters
object:Object

the DiskSubstitute to decode

Returns:Element

the decoded DiskSubstitute

decodeHitback to summary
private Element decodeHit(Object object)

Decode the possible DiskSubstitute, updating the statistics

Parameters
object:Object

the DiskSubstitute to decode

Returns:Element

the decoded DiskSubstitute

determineCachePinnedback to summary
private static boolean determineCachePinned(CacheConfiguration cacheConfiguration)
evictback to summary
pack-priv Element evict(Object key, int hash, DiskStorageFactory.DiskSubstitute value)

Remove the matching mapping. Unlike the net.sf.ehcache.store.disk.Segment#remove(Object, int, net.sf.ehcache.Element, net.sf.ehcache.store.ElementValueComparator) method evict does referential comparison of the unretrieved substitute against the argument value.

Parameters
key:Object

key to match against

hash:int

spread-hash for the key

value:DiskStorageFactory.DiskSubstitute

optional value to match against

Returns:Element

true on a successful remove

evictback to summary
pack-priv Element evict(Object key, int hash, DiskStorageFactory.DiskSubstitute value, boolean notify)

Remove the matching mapping. Unlike the net.sf.ehcache.store.disk.Segment#remove(Object, int, net.sf.ehcache.Element, net.sf.ehcache.store.ElementValueComparator) method evict does referential comparison of the unretrieved substitute against the argument value.

Parameters
key:Object

key to match against

hash:int

spread-hash for the key

value:DiskStorageFactory.DiskSubstitute

optional value to match against

notify:boolean

whether to notify if we evict something

Returns:Element

true on a successful remove

faultback to summary
pack-priv boolean fault(Object key, int hash, DiskStorageFactory.Placeholder expect, DiskStorageFactory.DiskMarker fault, final boolean skipFaulted)

Try to atomically switch (CAS) the expect representation of this element for the fault representation.

A successful switch will return true, and free the replaced element/element-proxy. A failed switch will return false and free the element/element-proxy which was not installed. Unlike fault this method can return false if the object could not be installed due to lock contention.

Parameters
key:Object

key to which this element (proxy) is mapped

hash:int

the hash of the key

expect:DiskStorageFactory.Placeholder

element (proxy) expected

fault:DiskStorageFactory.DiskMarker

element (proxy) to install

Returns:boolean

true if fault was installed

faultInternalback to summary
private boolean faultInternal(final Object key, final int hash, final DiskStorageFactory.Placeholder expect, final DiskStorageFactory.DiskMarker fault, final boolean skipFaulted)
findAndFreeback to summary
private boolean findAndFree(final Object key, final int hash, final DiskStorageFactory.Placeholder expect, final DiskStorageFactory.DiskMarker fault)
flushback to summary
pack-priv boolean flush(final Object key, final int hash, final Element element)

Marks an entry as flushable to disk (i.e. not faulted in higher tiers) Also updates the access stats

Parameters
key:Object

the key

hash:int

they hash

element:Element

the expected element

Returns:boolean

true if succeeded

freeback to summary
private void free(Object object)

Free the DiskSubstitute

Parameters
object:Object

the DiskSubstitute to free

freeback to summary
private void free(Object object, boolean faultFailure)

Free the DiskSubstitute indicating if it could not be faulted

Parameters
object:Object

the DiskSubstitute to free

faultFailure:boolean

true if the DiskSubstitute should be freed because of a fault failure

getback to summary
pack-priv Element get(Object key, int hash, final boolean markFaulted)

Get the element mapped to this key (or null if there is no mapping for this key)

Parameters
key:Object

key to lookup

hash:int

spread-hash for this key

Returns:Element

mapped element

getFirstback to summary
private HashEntry getFirst(int hash)
hashIteratorback to summary
pack-priv Iterator<HashEntry> hashIterator()

Creates an iterator over the HashEntry objects within this Segment.

Returns:Iterator<HashEntry>

an iterator over the HashEntry objects within this Segment.

isFaultedback to summary
public boolean isFaulted(final int hash, final Object key)

Verifies if the mapping for a key is marked as faulted

Parameters
key:Object

the key to check the mapping for

Returns:boolean

true if faulted, false otherwise (including no mapping)

notifyEvictionback to summary
private void notifyEviction(final Element evicted)
putback to summary
pack-priv Element put(Object key, int hash, Element element, boolean onlyIfAbsent, boolean faulted)

Add the supplied mapping.

The supplied element is substituted using the primary element proxy factory before being stored in the cache. If onlyIfAbsent is set then the mapping will only be added if no element is currently mapped to that key.

Parameters
key:Object

key to map the element to

hash:int

spread-hash for the key

element:Element

element to store

onlyIfAbsent:boolean

if true does not replace existing mappings

Returns:Element

previous element mapped to this key

putRawIfAbsentback to summary
pack-priv boolean putRawIfAbsent(Object key, int hash, DiskStorageFactory.DiskMarker encoded) throws IllegalArgumentException

Add the supplied pre-encoded mapping.

The supplied encoded element is directly inserted into the segment if there is no other mapping for this key.

Parameters
key:Object

key to map the element to

hash:int

spread-hash for the key

encoded:DiskStorageFactory.DiskMarker

encoded element to store

Returns:boolean

true if the encoded element was installed

Exceptions
IllegalArgumentException:
if the supplied key is already present
rehashback to summary
private void rehash()
removeback to summary
pack-priv Element remove(Object key, int hash, Element value, ElementValueComparator comparator)

Remove the matching mapping.

If value is null then match on the key only, else match on both the key and the value.

Parameters
key:Object

key to match against

hash:int

spread-hash for the key

value:Element

optional value to match against

comparator:ElementValueComparator

the comparator to use to compare values

Returns:Element

removed element

replaceback to summary
pack-priv boolean replace(Object key, int hash, Element oldElement, Element newElement, ElementValueComparator comparator)

Replace the element mapped to this key only if currently mapped to the given element.

Parameters
key:Object

key to map the element to

hash:int

spread-hash for the key

oldElement:Element

expected element

newElement:Element

element to add

comparator:ElementValueComparator

the comparator to use to compare values

Returns:boolean

true on a successful replace

replaceback to summary
pack-priv Element replace(Object key, int hash, Element newElement)

Replace the entry for this key only if currently mapped to some element.

Parameters
key:Object

key to map the element to

hash:int

spread-hash for the key

newElement:Element

element to add

Returns:Element

previous element mapped to this key

returnSafeDeprecatedback to summary
private boolean returnSafeDeprecated(final Object key, final int hash, final Element element)

Deprecated

Annotations
@Deprecated
toStringback to summary
public String toString()

Overrides java.util.concurrent.locks.ReentrantReadWriteLock.toString.

Doc from java.util.concurrent.locks.ReentrantReadWriteLock.toString.

Returns a string identifying this lock, as well as its lock state. The state, in brackets, includes the String "Write locks =" followed by the number of reentrantly held write locks, and the String "Read locks =" followed by the number of held read locks.

Returns:String

a string identifying this lock, as well as its lock state

Annotations
@Override
unretrievedGetback to summary
pack-priv Object unretrievedGet(Object key, int hash)

Return the unretrieved (undecoded) value for this key

Parameters
key:Object

key to lookup

hash:int

spread-hash for the key

Returns:Object

Element or ElementSubstitute

net.sf.ehcache.store.disk back to summary

pack-priv final Class Segment.HashIterator

extends Object
implements Iterator<HashEntry>
Class Inheritance
All Implemented Interfaces
java.util.Iterator

An iterator over the HashEntry objects within this Segment.

Field Summary

Modifier and TypeField and Description
private HashEntry
private HashEntry
private int
private final HashEntry[]

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
private void
public boolean
hasNext()

Implements java.util.Iterator.hasNext.

Returns true if the iteration has more elements.
public HashEntry
next()

Implements java.util.Iterator.next.

Returns the next element in the iteration.
public void
remove()

Overrides default java.util.Iterator.remove.

Removes from the underlying collection the last element returned by this iterator (optional operation).
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

lastReturnedback to summary
private HashEntry lastReturned
nextEntryback to summary
private HashEntry nextEntry
nextTableIndexback to summary
private int nextTableIndex
ourTableback to summary
private final HashEntry[] ourTable

Constructor Detail

HashIteratorback to summary
private HashIterator()

Method Detail

advanceback to summary
private void advance()
hasNextback to summary
public boolean hasNext()

Implements java.util.Iterator.hasNext.

Doc from java.util.Iterator.hasNext.

Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)

Returns:boolean

true if the iteration has more elements

nextback to summary
public HashEntry next()

Implements java.util.Iterator.next.

Doc from java.util.Iterator.next.

Returns the next element in the iteration.

Returns:HashEntry

the next element in the iteration

removeback to summary
public void remove()

Overrides default java.util.Iterator.remove.

Doc from java.util.Iterator.remove.

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next.

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy.

The behavior of an iterator is unspecified if this method is called after a call to the forEachRemaining method.