Boxlang 1.x Stable Released
BoxLang : A Modern Dynamic JVM Language
LogoLogo
APIDocsDownloadTrySourceSupport
  • Introduction
    • Contributing Guide
    • Release History
      • 1.2.0
      • 1.1.0
      • 1.0.1
      • 1.0.0
      • RC Stage
        • 1.0.0-RC.1
        • 1.0.0-RC.2
        • 1.0.0-RC.3
      • Beta Stage
        • 1.0.0-Beta27
        • 1.0.0-Beta26
        • 1.0.0-Beta25
        • 1.0.0-Beta24
        • 1.0.0-Beta23
        • 1.0.0-Beta22
        • 1.0.0-Beta21
        • 1.0.0-Beta20
        • 1.0.0-Beta19
        • 1.0.0-Beta18
        • 1.0.0-Beta17
        • 1.0.0-Beta16
        • 1.0.0-Beta15
        • 1.0.0-Beta14
        • 1.0.0-Beta13
        • 1.0.0-Beta12
        • 1.0.0-Beta11
        • 1.0.0-Beta10
        • 1.0.0-Beta9
        • 1.0.0-Beta8
        • 1.0.0-Beta7
        • 1.0.0-Beta6
        • 1.0.0-Beta5
        • 1.0.0-Beta 4
        • 1.0.0-Beta3
        • 1.0.0-Beta2
    • About This Book
      • Authors
  • Getting Started
    • Overview
      • Multi-Runtime
      • Instructions & Interpreters
      • CommandBox CLI
      • Quick Syntax Guide
        • Differences From CFML
      • Frequently Asked Questions
      • Running ColdFusion/CFML Apps
        • Migrating from Adobe ColdFusion
        • Migrating From Lucee CFML
    • Installation
      • Modules
    • Running BoxLang
      • AWS Lambda
      • CommandBox
      • Chromebooks
      • CLI Scripting
      • Docker
      • GitHub Actions
      • JSR-223 Scripting
      • MiniServer
      • Try BoxLang!
    • BoxLang Cloud Servers
      • Microsoft Azure
      • Amazon Web Services
    • IDE & Tooling
      • BoxLang Debugger
        • MiniServer Debugging
        • CommandBox Debugging
      • BoxLang Compiler
      • CFML Feature Audit
      • CFML to BoxLang Transpiler
    • Runtime Configuration
      • Directives
      • Caches
      • Datasources
      • Experimental
      • Executors
      • Logging
      • Modules
      • Security
  • BoxLang Language
    • Program Structure
    • Syntax & Semantics
      • Comments
      • Variables
      • Variable Scopes
      • Operators
      • Null & Nothingness
      • Strings
      • Numbers
      • Dates & Times
      • JSON
      • Arrays
      • Structures
      • Queries
      • Datasources
      • Conditionals
      • Attempts
      • Data Navigators
      • Exception Management
      • Code Locking
      • Closures => Context Aware
      • Lambdas -> Pure Functions
      • Includes
      • Threading
    • Classes & O.O.
      • Properties
      • Functions
      • Static Constructs
      • Final Constructs
      • Abstract Constructs
      • Interfaces
    • Reference
      • API Docs
      • Lexical Elements
        • Scopes and Constants
        • Keywords
        • Operators
        • Literals
        • Comments
        • Tokens
        • Semicolons
        • Identifiers
        • Packages and Imports
        • Java Interoperability
        • Errors
      • Types
        • array
        • class
        • datetime
        • file
        • numeric
        • query
        • stream
        • string
        • struct
        • xml
      • Built-in Functions
        • array
          • ArrayAppend
          • ArrayAvg
          • ArrayClear
          • ArrayContains
          • ArrayContainsNoCase
          • ArrayDelete
          • ArrayDeleteAt
          • ArrayDeleteNoCase
          • ArrayEach
          • ArrayEvery
          • ArrayFilter
          • ArrayFind
          • ArrayFindAll
          • ArrayFindAllNoCase
          • ArrayFindNoCase
          • ArrayFirst
          • ArrayGetMetadata
          • ArrayIndexExists
          • ArrayInsertAt
          • ArrayIsDefined
          • ArrayLast
          • ArrayMap
          • ArrayMax
          • ArrayMedian
          • ArrayMerge
          • ArrayMid
          • ArrayMin
          • ArrayNew
          • ArrayPop
          • ArrayPrepend
          • ArrayPush
          • ArrayRange
          • ArrayReduce
          • ArrayReduceRight
          • ArrayResize
          • ArrayReverse
          • ArraySet
          • ArrayShift
          • ArraySlice
          • ArraySome
          • ArraySort
          • ArraySplice
          • ArraySum
          • ArraySwap
          • ArrayToList
          • ArrayToStruct
          • ArrayUnshift
        • async
          • ExecutorGet
          • ExecutorHas
          • ExecutorList
          • ExecutorNew
          • ExecutorShutdown
          • ExecutorStatus
          • FutureNew
          • IsInThread
          • isThreadAlive
          • IsThreadInterrupted
          • RunAsync
          • ThreadInterrupt
          • ThreadJoin
          • ThreadNew
          • ThreadTerminate
        • binary
          • BinaryDecode
          • BinaryEncode
          • BitAnd
          • BitMaskClear
          • BitMaskRead
          • BitMaskSet
          • BitNot
          • BitOr
          • bitShln
          • bitShrn
          • BitXor
        • cache
          • Cache
          • CacheFilter
          • CacheNames
          • CacheProviders
          • CacheService
        • cli
          • CLIClear
          • CLIExit
          • CLIGetArgs
          • CLIRead
        • conversion
          • DataNavigate
          • JSONDeserialize
          • JSONPrettify
          • JSONSerialize
          • LSParseNumber
          • ParseNumber
          • ToBase64
          • ToBinary
          • ToModifiable
          • ToNumeric
          • ToScript
          • ToString
          • ToUnmodifiable
        • decision
          • ArrayIsEmpty
          • arrayIsEmpty
          • Attempt
          • IsArray
          • IsBinary
          • IsBoolean
          • IsClosure
          • IsCustomFunction
          • IsDate
          • IsDateObject
          • IsDebugMode
          • IsDefined
          • IsEmpty
          • IsFileObject
          • IsIPv6
          • IsJSON
          • IsLeapYear
          • IsLocalHost
          • IsNull
          • IsNumeric
          • IsNumericDate
          • IsObject
          • IsQuery
          • IsSimpleValue
          • IsStruct
          • IsValid
          • IsXML
          • IsXmlAttribute
          • IsXMLDoc
          • IsXMLElem
          • IsXMLNode
          • IsXMLRoot
          • LSIsNumeric
          • structIsEmpty
        • encryption
          • Decrypt
          • DecryptBinary
          • Encrypt
          • EncryptBinary
          • GeneratePBKDFKey
          • GenerateSecretKey
          • Hash
          • Hash40
          • Hmac
        • format
          • BooleanFormat
          • DecimalFormat
          • LSNumberFormat
          • NumberFormat
        • i18n
          • ClearLocale
          • CurrencyFormat
          • GetLocale
          • GetLocaleDisplayName
          • GetLocaleInfo
          • IsCurrency
          • LSCurrencyFormat
          • LSIsCurrency
          • LSParseCurrency
          • ParseCurrency
          • SetLocale
        • io
          • ContractPath
          • CreateTempDirectory
          • CreateTempFile
          • DirectoryCopy
          • DirectoryCreate
          • DirectoryDelete
          • DirectoryExists
          • DirectoryList
          • DirectoryMove
          • DirectoryRename
          • ExpandPath
          • FileAppend
          • FileClose
          • FileCopy
          • FileDelete
          • FileExists
          • FileGetMimeType
          • FileInfo
          • FileIsEOF
          • FileMove
          • FileOpen
          • FileRead
          • FileReadBinary
          • FileReadLine
          • FileSeek
          • FileSetAccessMode
          • FileSetAttribute
          • FileSetLastModified
          • FileSkipBytes
          • FileWrite
          • FileWriteLine
          • GetCanonicalPath
          • GetDirectoryFromPath
          • GetFileInfo
          • getTempFile
        • java
          • CreateDynamicProxy
        • jdbc
          • IsInTransaction
          • IsWithinTransaction
          • PreserveSingleQuotes
          • QueryExecute
          • TransactionCommit
          • TransactionRollback
          • TransactionSetSavepoint
        • list
          • GetToken
          • ListAppend
          • ListAvg
          • ListChangeDelims
          • ListCompact
          • ListContains
          • ListContainsNoCase
          • ListDeleteAt
          • ListEach
          • ListEvery
          • ListFilter
          • ListFind
          • ListFindNoCase
          • ListFirst
          • ListGetAt
          • ListIndexExists
          • ListInsertAt
          • ListItemTrim
          • ListLast
          • ListLen
          • ListMap
          • ListPrepend
          • ListQualify
          • ListReduceRight
          • ListRemoveDuplicates
          • ListRest
          • ListSetAt
          • ListSome
          • ListSort
          • ListToArray
          • ListTrim
          • ListValueCount
          • ListValueCountNoCase
        • math
          • Abs
          • Acos
          • Asin
          • Atn
          • Ceiling
          • Cos
          • DecrementValue
          • Exp
          • Fix
          • Floor
          • FormatBaseN
          • IncrementValue
          • InputBaseN
          • Int
          • Log
          • Log10
          • Max
          • Min
          • Pi
          • PrecisionEvaluate
          • Rand
          • Randomize
          • RandRange
          • Round
          • Sgn
          • Sin
          • Sqr
          • Tan
        • query
          • QueryAddColumn
          • QueryAddRow
          • QueryAppend
          • QueryClear
          • QueryColumnArray
          • QueryColumnCount
          • QueryColumnData
          • QueryColumnExists
          • QueryColumnList
          • QueryCurrentRow
          • QueryDeleteColumn
          • QueryDeleteRow
          • QueryEach
          • QueryEvery
          • QueryFilter
          • QueryGetCell
          • QueryGetResult
          • QueryInsertAt
          • QueryKeyExists
          • QueryMap
          • QueryNew
          • QueryPrepend
          • QueryRecordCount
          • QueryReduce
          • QueryRegisterFunction
          • QueryReverse
          • QueryRowData
          • QueryRowSwap
          • QuerySetCell
          • QuerySetRow
          • QuerySlice
          • QuerySome
          • QuerySort
        • runtime
          • BoxLangBIFProxy
        • scheduler
          • SchedulerGet
          • SchedulerGetAll
          • SchedulerList
          • SchedulerRestart
          • SchedulerShutdown
          • SchedulerStart
          • SchedulerStats
        • string
          • Ascii
          • CamelCase
          • Char
          • CharsetDecode
          • CharsetEncode
          • Compare
          • CompareNoCase
          • Find
          • FindNoCase
          • FindOneOf
          • Insert
          • JSStringFormat
          • KebabCase
          • LCase
          • Left
          • ListReduce
          • LJustify
          • LTrim
          • Mid
          • ParagraphFormat
          • PascalCase
          • QueryStringToStruct
          • ReEscape
          • ReFind
          • reFindNoCase
          • ReMatch
          • reMatchNoCase
          • RemoveChars
          • RepeatString
          • Replace
          • ReplaceList
          • ReplaceListNoCase
          • ReplaceNoCase
          • ReReplace
          • reReplaceNoCase
          • Reverse
          • Right
          • RJustify
          • RTrim
          • Slugify
          • SnakeCase
          • SpanExcluding
          • SpanIncluding
          • SQLPrettify
          • StringBind
          • StringEach
          • StringEvery
          • StringFilter
          • StringMap
          • StringReduce
          • StringReduceRight
          • StringSome
          • StringSort
          • StripCR
          • Trim
          • TrueFalseFormat
          • UCase
          • UCFirst
          • Val
          • Wrap
          • YesNoFormat
        • struct
          • StructAppend
          • StructClear
          • StructCopy
          • StructDelete
          • StructEach
          • StructEquals
          • StructEvery
          • StructFilter
          • StructFind
          • StructFindKey
          • StructFindValue
          • StructGet
          • StructGetMetadata
          • StructInsert
          • StructIsCaseSensitive
          • StructIsOrdered
          • StructKeyArray
          • StructKeyExists
          • StructKeyList
          • StructKeyTranslate
          • StructMap
          • StructNew
          • StructReduce
          • StructSome
          • StructSort
          • StructToQueryString
          • StructToSorted
          • StructUpdate
          • StructValueArray
        • system
          • ApplicationRestart
          • ApplicationStartTime
          • ApplicationStop
          • BoxAnnounce
          • BoxAnnounceAsync
          • BoxModuleReload
          • BoxRegisterInterceptionPoints
          • BoxRegisterInterceptor
          • BoxRegisterRequestInterceptor
          • BoxUnregisterInterceptor
          • BoxUnregisterRequestInterceptor
          • CallStackGet
          • CreateGUID
          • CreateObject
          • CreateUUID
          • DE
          • DebugBoxContexts
          • Dump
          • Duplicate
          • echo
          • EncodeForHTML
          • GetApplicationMetadata
          • GetBaseTagData
          • GetBaseTagList
          • GetBaseTemplatePath
          • GetBoxContext
          • GetBoxRuntime
          • GetBoxVersionInfo
          • GetClassMetadata
          • GetComponentList
          • GetContextRoot
          • GetCurrentTemplatePath
          • GetFileFromPath
          • GetFunctionCalledName
          • GetFunctionList
          • GetModuleInfo
          • GetModuleList
          • GetRequestClassLoader
          • GetSemver
          • GetSystemSetting
          • GetTempDirectory
          • GetTickCount
          • htmlEditFormat
          • IIF
          • Invoke
          • IsInstanceOf
          • JavaCast
          • ObjectDeserialize
          • ObjectSerialize
          • PagePoolClear
          • Print
          • Println
          • RunThreadInContext
          • SessionInvalidate
          • SessionRotate
          • SessionStartTime
          • Sleep
          • SystemCacheClear
          • SystemExecute
          • SystemOutput
          • Throw
          • Trace
          • URLDecode
          • URLEncodedFormat
          • writeDump
          • WriteLog
          • WriteOutput
        • temporal
          • ClearTimezone
          • CreateDate
          • CreateDateTime
          • CreateODBCDate
          • CreateODBCDateTime
          • CreateODBCTime
          • CreateTime
          • CreateTimeSpan
          • DateAdd
          • DateCompare
          • DateConvert
          • DateDiff
          • DateFormat
          • DatePart
          • DateTimeFormat
          • Day
          • DayOfWeek
          • DayOfWeekAsString
          • DayOfWeekShortAsString
          • DayOfYear
          • DaysInMonth
          • DaysInYear
          • FirstDayOfMonth
          • GetNumericDate
          • GetTime
          • GetTimezone
          • GetTimezoneInfo
          • Hour
          • Millisecond
          • Minute
          • Month
          • MonthAsString
          • MonthShortAsString
          • Nanosecond
          • Now
          • Offset
          • ParseDateTime
          • Quarter
          • Second
          • SetTimezone
          • TimeFormat
          • Week
          • Year
        • type
          • ArrayLen
          • GetMetaData
          • Len
          • NullValue
          • StringLen
          • StructCount
        • xml
          • XMLChildPos
          • XMLElemNew
          • XMLFormat
          • XMLGetNodeType
          • XMLNew
          • XMLParse
          • XMLSearch
          • XMLTransform
          • XMLValidate
        • zip
          • Compress
          • Extract
          • IsZipFile
      • Components
        • async
          • Thread
        • cache
          • Cache
        • debug
          • Timer
        • io
          • Directory
          • File
        • jdbc
          • ProcParam
          • StoredProc
          • DBInfo
          • ProcResult
          • Query
          • QueryParam
          • Transaction
        • net
          • HTTPParam
          • HTTP
        • system
          • Throw
          • InvokeArgument
          • Application
          • Invoke
          • Abort
          • Include
          • Component
          • Execute
          • Flush
          • SaveContent
          • Output
          • Log
          • Sleep
          • Setting
          • Param
          • Lock
          • Associate
          • Silent
          • ProcessingDirective
          • Trace
          • Exit
          • Dump
          • Loop
        • xml
          • XML
        • zip
          • Zip
      • Exceptions
  • BoxLang Framework
    • Application.bx
    • Asynchronous Programming
    • Caching
      • Cache Service
      • BoxCache Provider
      • Custom Cache Providers
      • Custom Object Stores
      • Custom Eviction Policies
    • File Handling
    • Interceptors
      • Core Interception Points
        • Application Events
        • Cache Service Events
        • Cache Provider Events
        • Cache Object Store Events
        • Datasource Service Events
        • Dump Events
        • Dynamic Object Events
        • Function Invocations
        • HTTP Events
        • Life-cycle Events
        • Logging Events
        • Module Events
        • Module Service Events
        • Object Marshalling Events
        • Query Invocations
        • Runtime Events
        • Request Context Events
        • Scheduler Events
        • Scheduler Service Events
        • Template Invocations
        • Transaction Events
      • Request Interception Points
    • HTTP/S Calls
    • Java Interop
    • JDBC Transactions
    • Modules
      • AI
      • Compat CFML
        • Reference
          • Types
            • array
            • datetime
            • numeric
            • string
            • struct
          • Built-in Functions
            • cache
              • CacheCount
              • CacheGetAsAttempt
              • CacheRegionRemove
              • CacheRemoveAll
              • CachePut
              • CacheRegionExists
              • CacheGetSession
              • CacheGetEngineProperties
              • CacheGet
              • CacheGetDefaultCacheName
              • CacheGetProperties
              • CacheSetProperties
              • CacheGetAllIds
              • CacheIdExists
              • cacheKeyExists
              • CacheRemove
              • cacheDelete
              • CacheGetAll
              • CacheGetMetadata
              • CacheGetOrFail
              • CacheClear
              • CacheRegionNew
            • conversion
              • JSONDeserialize
            • encryption
              • Hash
              • Hash40
            • format
              • HTMLCodeFormat
              • DollarFormat
            • struct
              • DeleteClientVariable
            • system
              • Throw
              • ObjectSave
              • GetFunctionData
              • GetComponentMetadata
              • GetVariable
              • GetTagData
              • GetClientVariablesList
              • GetContextRoot
              • ObjectLoad
              • SetVariable
            • temporal
              • LSWeek
              • LSDayOfWeek
              • LSIsDate
              • DateCompare
              • GetHTTPTimestring
              • LSDateTimeFormat
              • LSDateFormat
              • LSTimeFormat
              • DayOfWeekAsString
              • DayOfWeekShortAsString
              • MonthAsString
              • MonthShortAsString
              • ToLegacyDate
              • createDate
              • LSParseDateTime
              • DateTimeFormat
              • DateFormat
              • TimeFormat
            • type
              • GetMetaData
          • Components
            • net
              • HTTP
      • CSRF
      • ESAPI
      • Evaluating Code
      • FTP
      • Image Manipulation
      • INI Files
      • JDBC
      • Jython
      • Mail
      • Markdown
      • ORM
      • OSHI - Operating System + Hardware
      • Password Encryption
      • PDF
      • Redis
      • UI Forms
      • WDDX
      • Web Support
      • Yaml
  • Extra Credit
    • MVC
    • Dependency Injection
Powered by GitBook
LogoLogo

Social Media

  • X
  • FaceBook
  • LinkedIn
  • YouTube

Bug Tracking

  • Runtimes
  • IDE
  • Modules

Support

  • Professional
  • Community
  • Slack

Copyright & Register Trademark by Ortus Solutions, Corp

On this page

Was this helpful?

Edit on GitHub
Export as PDF

Object stores are the foundational storage layer of the BoxLang cache engine. They provide the actual mechanism for storing, retrieving, and managing cached objects. While cache providers coordinate user interactions and act as a service layer, object stores handle the low-level data persistence and retrieval operations.

What are Object Stores?

An object store is a pluggable storage backend that implements the IObjectStore interface. It determines how and where your cached data is stored - whether in memory, on disk, or in any custom storage mechanism you design.

Key Characteristics:

  • Storage Abstraction: Object stores abstract the underlying storage mechanism from the cache provider

  • Key Handling: They work with Key objects, allowing for case-sensitive or case-insensitive storage decisions

  • Entry Management: All data is stored as ICacheEntry objects for consistency across implementations

  • Eviction Support: Integration with configurable eviction policies (LRU, MRU, LFU, etc.)

  • Lifecycle Management: Support for initialization, shutdown, and maintenance operations

Built-in Object Store Types

BoxLang provides several built-in object store implementations:

  • ConcurrentHashMap: Fast in-memory storage using Java's ConcurrentHashMap

  • ConcurrentSoftReference: Memory-conscious storage with soft references for automatic GC cleanup

  • Disk: Persistent disk-based storage for cache durability

  • Custom: Your own implementations

The IObjectStore Interface

To create a custom object store, you must implement the IObjectStore interface in the Java language or in BoxLang by using implements="java:ortus.boxlang.runtime.cache.store.IObjectStore

Creating a Custom Object Store

Step 1: Extend AbstractStore (Recommended)

While you can implement IObjectStore directly, extending AbstractStore provides useful functionality like eviction policy management:

Step 2: Implement Core Storage Methods

The most critical methods to implement are the storage operations:

Step 3: Implement Introspection Methods

Provide methods for cache inspection and filtering:

Step 4: Implement Eviction Support

Integrate with the eviction policy system:

Step 5: Handle Bulk Operations

Implement bulk operations for better performance:

Configuration

You can register and use your custom object store via the caches configuration section by putting the full Java class path of the object store as the objectStore key

Or you can use the createCache( name, provider, propertes ) method on the CacheService and pass in a class or object instance for the objectStore

Best Practices

Performance Considerations

  1. Thread Safety: Ensure your implementation is thread-safe as multiple threads will access it concurrently

  2. Efficient Lookups: Optimize for fast key lookups as get() and lookup() are called frequently

  3. Bulk Operations: Implement bulk operations efficiently rather than iterating single operations

  4. Memory Management: Consider memory usage patterns, especially for in-memory stores

Error Handling

Eviction Integration

Resource Management

Integration with Cache Providers

Your object store will be used by cache providers like BoxCacheProvider. The provider handles:

  • Cache entry creation and metadata management

  • Event announcements (insert, update, remove)

  • Statistics tracking

  • Eviction scheduling

  • Configuration validation

Your object store focuses purely on storage operations, making the separation of concerns clean and maintainable.

Testing Your Custom Store

Create comprehensive tests for your custom object store:

Conclusion

Custom object stores provide powerful extensibility for the BoxLang cache engine. By implementing the IObjectStore interface and following these patterns, you can create storage backends that meet your specific requirements, whether for performance, persistence, distribution, or integration with external systems.

The clean separation between cache providers and object stores ensures that your custom storage logic remains focused and testable while integrating seamlessly with the broader caching infrastructure.

Last updated 1 day ago

Was this helpful?

public interface IObjectStore {
    // Basic metadata
    public String getName();
    public IStruct getConfig();
    public ICacheProvider getProvider();
    
    // Lifecycle methods
    public IObjectStore init(ICacheProvider provider, IStruct config);
    public void shutdown();
    
    // Storage operations
    public void set(Key key, ICacheEntry entry);
    public void set(IStruct entries);
    public ICacheEntry get(Key key);
    public ICacheEntry getQuiet(Key key);
    
    // Bulk operations
    public IStruct get(Key... keys);
    public IStruct get(ICacheKeyFilter filter);
    public IStruct getQuiet(Key... keys);
    public IStruct getQuiet(ICacheKeyFilter filter);
    
    // Cache management
    public boolean clear(Key key);
    public IStruct clear(Key... keys);
    public void clearAll();
    public boolean clearAll(ICacheKeyFilter filter);
    
    // Introspection
    public Key[] getKeys();
    public Key[] getKeys(ICacheKeyFilter filter);
    public Stream<Key> getKeysStream();
    public Stream<Key> getKeysStream(ICacheKeyFilter filter);
    public boolean lookup(Key key);
    public IStruct lookup(Key... keys);
    public IStruct lookup(ICacheKeyFilter filter);
    
    // Maintenance
    public int getSize();
    public int flush();
    public void evict();
}
public class MyCustomStore extends AbstractStore {
    
    private Map<String, ICacheEntry> storage;
    
    @Override
    public IObjectStore init(ICacheProvider provider, IStruct config) {
        // Call parent initialization
        super.init(provider, config);
        
        // Initialize your storage mechanism
        this.storage = new ConcurrentHashMap<>();
        
        // Configure based on properties
        var initialCapacity = config.getAsInteger("initialCapacity", 1000);
        // ... additional configuration
        
        return this;
    }
    
    @Override
    public void shutdown() {
        // Clean up resources
        if (storage != null) {
            storage.clear();
            storage = null;
        }
    }
    
    // Implement required methods...
}
@Override
public void set(Key key, ICacheEntry entry) {
    storage.put(key.getName(), entry);
}

@Override
public ICacheEntry get(Key key) {
    ICacheEntry entry = storage.get(key.getName());
    if (entry != null) {
        // Update last accessed time
        entry.updateLastAccessed();
    }
    return entry;
}

@Override
public ICacheEntry getQuiet(Key key) {
    // Get without updating access metadata
    return storage.get(key.getName());
}

@Override
public boolean clear(Key key) {
    return storage.remove(key.getName()) != null;
}

@Override
public void clearAll() {
    storage.clear();
}

@Override
public int getSize() {
    return storage.size();
}
@Override
public Key[] getKeys() {
    return storage.keySet().stream()
        .map(Key::of)
        .toArray(Key[]::new);
}

@Override
public Key[] getKeys(ICacheKeyFilter filter) {
    return storage.keySet().stream()
        .map(Key::of)
        .filter(filter)
        .toArray(Key[]::new);
}

@Override
public Stream<Key> getKeysStream() {
    return storage.keySet().stream().map(Key::of);
}

@Override
public Stream<Key> getKeysStream(ICacheKeyFilter filter) {
    return getKeysStream().filter(filter);
}

@Override
public boolean lookup(Key key) {
    return storage.containsKey(key.getName());
}
@Override
public void evict() {
    ICachePolicy policy = getPolicy(); // From AbstractStore
    
    if (policy != null && getSize() > 0) {
        // Get eviction candidates
        Key[] candidates = policy.getEvictionCandidates(
            this, 
            getKeysStream().collect(Collectors.toList())
        );
        
        // Remove candidates
        for (Key candidate : candidates) {
            clear(candidate);
        }
    }
}
@Override
public IStruct get(Key... keys) {
    IStruct results = new Struct();
    for (Key key : keys) {
        results.put(key, get(key));
    }
    return results;
}

@Override
public IStruct clear(Key... keys) {
    IStruct results = new Struct();
    for (Key key : keys) {
        results.put(key, clear(key));
    }
    return results;
}

@Override
public void set(IStruct entries) {
    entries.forEach((key, entry) -> {
        if (entry instanceof ICacheEntry) {
            set((Key) key, (ICacheEntry) entry);
        }
    });
}
// In your cache configuration
objectStore : "my.class.MyStore"
// Create and configure your store instance
MyCustomStore customStore = new MyCustomStore();

// Use it in cache configuration
myCache = cacheService.createCache( "myCache", "BoxCache", {
    "objectStore" : customStore
} );
@Override
public ICacheEntry get(Key key) {
    try {
        // Your storage retrieval logic
        return performStorageGet(key);
    } catch (StorageException e) {
        // Log the error but don't throw - return null for cache miss
        logger.warn("Storage error retrieving key {}: {}", key.getName(), e.getMessage());
        return null;
    } catch (Exception e) {
        // Unexpected errors should be thrown
        throw new BoxRuntimeException("Unexpected error in object store", e);
    }
}
@Override
public void evict() {
    ICachePolicy policy = getPolicy();
    int maxObjects = getIntProperty("maxObjects", 10000);
    
    if (getSize() > maxObjects) {
        int itemsToEvict = getSize() - maxObjects;
        Key[] candidates = policy.selectEvictionCandidates(this, itemsToEvict);
        
        for (Key candidate : candidates) {
            clear(candidate);
        }
    }
}
@Override
public void shutdown() {
    try {
        // Flush any pending operations
        flush();
        
        // Close connections/resources
        closeConnections();
        
        // Clear references
        cleanup();
    } catch (Exception e) {
        logger.error("Error during object store shutdown", e);
    }
}

@Override
public int flush() {
    int flushedCount = 0;
    // Implement persistence operations if applicable
    return flushedCount;
}
@Test
public void testBasicOperations() {
    // Initialize store
    MyCustomStore store = new MyCustomStore();
    store.init(mockProvider, testConfig);
    
    // Test set/get
    Key testKey = Key.of("testKey");
    ICacheEntry entry = new BoxCacheEntry(/* parameters */);
    
    store.set(testKey, entry);
    ICacheEntry retrieved = store.get(testKey);
    
    assertNotNull(retrieved);
    assertEquals(entry.value(), retrieved.value());
    
    // Test clear
    assertTrue(store.clear(testKey));
    assertNull(store.get(testKey));
    
    // Cleanup
    store.shutdown();
}
  1. BoxLang Framework
  2. Caching

Custom Object Stores

Object stores are the foundational storage layer of the BoxLang cache engine

PreviousCustom Cache ProvidersNextCustom Eviction Policies
  • What are Object Stores?
  • Key Characteristics:
  • Built-in Object Store Types
  • The IObjectStore Interface
  • Creating a Custom Object Store
  • Step 1: Extend AbstractStore (Recommended)
  • Step 2: Implement Core Storage Methods
  • Step 3: Implement Introspection Methods
  • Step 4: Implement Eviction Support
  • Step 5: Handle Bulk Operations
  • Configuration
  • Best Practices
  • Integration with Cache Providers
  • Testing Your Custom Store
  • Conclusion