├── .editorconfig ├── .github └── workflows │ ├── benchmark.yml │ ├── build.yml │ ├── comment.yml │ ├── main.yml │ └── pr.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benchmark ├── build.gradle.kts ├── reports │ └── jvmBenchmark.json └── src │ ├── commonMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── cachemap │ │ └── benchmark │ │ └── BenchmarkConfig.kt │ ├── jvmMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── cachemap │ │ └── benchmark │ │ ├── CacheMapMultiThreadedBenchmark.kt │ │ ├── CacheMapSingleThreadBenchmark.kt │ │ ├── ConcurrentHashMapMultiThreadedBenchmark.kt │ │ ├── ConcurrentHashMapSingleThreadedBenchmark.kt │ │ ├── RWHashMapMultiThreadedBenchmark.kt │ │ └── RWHashMapSingleThreadedBenchmark.kt │ └── nativeMain │ └── kotlin │ └── io │ └── github │ └── charlietap │ └── cachemap │ └── benchmark │ ├── CacheMapMultiThreadedBenchmark.kt │ ├── CacheMapSingleThreadBenchmark.kt │ ├── RWHashMapMultiThreadedBenchmark.kt │ └── RWHashMapSingleThreadedBenchmark.kt ├── build.gradle.kts ├── cachemap-suspend ├── build.gradle.kts └── src │ ├── commonMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── cachemap │ │ ├── InternalSuspendCacheMap.kt │ │ └── SuspendCacheMap.kt │ └── commonTest │ └── kotlin │ └── io │ └── github │ └── charlietap │ └── cachemap │ └── SuspendCacheMapTest.kt ├── cachemap ├── build.gradle.kts └── src │ ├── commonMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── cachemap │ │ ├── CacheMap.kt │ │ └── InternalCacheMap.kt │ └── commonTest │ └── kotlin │ └── io │ └── github │ └── charlietap │ └── cachemap │ └── CacheMapTest.kt ├── gradle.properties ├── gradle ├── libs.versions.toml ├── plugins │ ├── kmp-conventions │ │ ├── build.gradle.kts │ │ ├── settings.gradle.kts │ │ └── src │ │ │ └── main │ │ │ └── kotlin │ │ │ └── kmp-conventions.gradle.kts │ ├── linting-conventions │ │ ├── build.gradle.kts │ │ ├── settings.gradle.kts │ │ └── src │ │ │ └── main │ │ │ └── kotlin │ │ │ └── linting-conventions.gradle.kts │ ├── publishing-conventions │ │ ├── build.gradle.kts │ │ ├── settings.gradle.kts │ │ └── src │ │ │ └── main │ │ │ └── kotlin │ │ │ ├── PublishingConventionsExtension.kt │ │ │ └── PublishingConventionsPlugin.kt │ └── versions-conventions │ │ ├── build.gradle.kts │ │ ├── settings.gradle.kts │ │ └── src │ │ └── main │ │ └── kotlin │ │ └── versions-conventions.gradle.kts └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── leftright-shared ├── build.gradle.kts └── src │ ├── commonMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ ├── CacheAlignedCounter.kt │ │ ├── CoreProvider.kt │ │ ├── ReadEpochIndex.kt │ │ ├── ReaderParallelism.kt │ │ └── Yield.kt │ ├── commonTest │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ └── ReaderParallelismTest.kt │ ├── ffi │ └── cinterop │ │ └── libcounter.def │ ├── jvmMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ ├── CacheAlignedCounter.kt │ │ ├── CoreProvider.kt │ │ ├── ReadEpochIndex.kt │ │ └── Yield.kt │ ├── mingwMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ └── CoreProvider.kt │ ├── nativeMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ ├── CacheAlignedCounter.kt │ │ ├── ReadEpochIndex.kt │ │ └── Yield.kt │ └── unixMain │ └── kotlin │ └── io │ └── github │ └── charlietap │ └── leftright │ └── CoreProvider.kt ├── leftright-suspend ├── build.gradle.kts └── src │ ├── commonMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ └── SuspendLeftRight.kt │ └── commonTest │ └── kotlin │ └── io │ └── github │ └── charlietap │ └── leftright │ └── SuspendLeftRightTest.kt ├── leftright ├── build.gradle.kts └── src │ ├── commonMain │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ └── LeftRight.kt │ ├── commonTest │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ └── LeftRightTest.kt │ ├── jvmTest │ └── kotlin │ │ └── io │ │ └── github │ │ └── charlietap │ │ └── leftright │ │ └── LeftRightTest.kt │ └── nativeTest │ └── kotlin │ └── io │ └── github │ └── charlietap │ └── leftright │ └── LeftRightTest.kt └── settings.gradle.kts /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | 5 | end_of_line = lf 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 4 9 | insert_final_newline = true 10 | max_line_length = 140 11 | trim_trailing_whitespace = true 12 | 13 | [*.{kt,kts}] 14 | 15 | ktlint_code_style = ktlint_official 16 | ktlint_ignore_back_ticked_identifier = true 17 | 18 | ktlint_standard = enabled 19 | 20 | ktlint_standard_function-signature = default 21 | ktlint_standard_class-naming = disabled 22 | ktlint_standard_class-signature = disabled 23 | ktlint_standard_filename = disabled 24 | ktlint_standard_function-expression-body = disabled 25 | ktlint_standard_function-naming = disabled 26 | ktlint_standard_function-signature = disabled 27 | ktlint_standard_max-line-length = disabled 28 | ktlint_standard_no-empty-first-line-in-class-body = disabled 29 | ktlint_standard_no-empty-first-line-in-method-block = disabled 30 | ktlint_standard_multiline-expression-wrapping = disabled 31 | ktlint_standard_property-naming = disabled 32 | ktlint_standard_string-template-indent = disabled 33 | 34 | ij_kotlin_allow_trailing_comma = true 35 | ij_kotlin_allow_trailing_comma_on_call_site = true 36 | ij_kotlin_packages_to_use_import_on_demand = unset 37 | 38 | [*.{yml,yaml}] 39 | indent_size = 2 40 | -------------------------------------------------------------------------------- /.github/workflows/benchmark.yml: -------------------------------------------------------------------------------- 1 | name: Benchmark ⌛ 2 | 3 | on: 4 | workflow_call: 5 | inputs: 6 | runner: 7 | type: string 8 | description: 'The machine runner the workflow should run on' 9 | default: macos-13 10 | required: false 11 | branch: 12 | type: string 13 | description: 'The branch to be benchmarked' 14 | required: true 15 | should-commit-benchmark: 16 | type: boolean 17 | description: 'If the produced report should be commited to the active branch' 18 | default: false 19 | required: false 20 | workflow_dispatch: 21 | inputs: 22 | runner: 23 | type: string 24 | description: 'The machine runner the workflow should run on' 25 | default: macos-13 26 | required: true 27 | branch: 28 | type: string 29 | description: 'The branch to be benchmarked' 30 | required: true 31 | should-commit-benchmark: 32 | type: boolean 33 | description: 'If the produced report should be committed to the active branch' 34 | default: false 35 | required: false 36 | 37 | jobs: 38 | build: 39 | runs-on: ${{ inputs.runner }} 40 | permissions: 41 | contents: write 42 | steps: 43 | 44 | - name: Clone Repo 45 | uses: actions/checkout@v4 46 | with: 47 | ref: ${{ inputs.branch }} 48 | 49 | - name: Set up jdk@17 50 | uses: actions/setup-java@v3 51 | with: 52 | distribution: 'corretto' 53 | java-version: '21' 54 | 55 | - name: Setup Gradle 56 | uses: gradle/gradle-build-action@v2 57 | 58 | - name: Execute Gradle build 59 | run: ./gradlew benchmark 60 | 61 | - name: Upload any new reports 62 | uses: actions/upload-artifact@v3 63 | with: 64 | name: reports 65 | path: | 66 | **/build/**/*Benchmark.csv 67 | **/build/**/*Benchmark.json 68 | 69 | - name: Move benchmark files 70 | run: | 71 | mkdir -p benchmark/reports 72 | find benchmark -type f \( -iname '*benchmark.json' -o -iname '*benchmark.csv' \) -exec mv {} ./benchmark/reports/ \; 73 | 74 | - name: Commit benchmark files 75 | if: ${{ inputs.should-commit-benchmark }} 76 | run: | 77 | git config --local user.email "action@github.com" 78 | git config --local user.name "GitHub Action" 79 | git add benchmark/* 80 | git commit -m "Commit benchmark results" -a 81 | git push 82 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 🔨 2 | 3 | on: 4 | workflow_call: 5 | inputs: 6 | runner: 7 | type: string 8 | description: 'The machine runner the workflow should run on' 9 | default: macos-latest 10 | required: false 11 | workflow_dispatch: 12 | inputs: 13 | runner: 14 | type: string 15 | description: 'The machine runner the workflow should run on' 16 | default: macos-latest 17 | required: true 18 | 19 | jobs: 20 | build: 21 | runs-on: ${{ inputs.runner }} 22 | steps: 23 | 24 | - name: Clone Repo 25 | uses: actions/checkout@v4 26 | 27 | - name: Set up jdk@21 28 | uses: actions/setup-java@v4 29 | with: 30 | distribution: 'corretto' 31 | java-version: '21' 32 | 33 | - name: Setup Gradle 34 | uses: gradle/actions/setup-gradle@v3 35 | with: 36 | cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }} 37 | 38 | - name: Execute Gradle build 39 | run: ./gradlew build 40 | -------------------------------------------------------------------------------- /.github/workflows/comment.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Comment 2 | on: 3 | issue_comment: 4 | types: [created, edited, deleted] 5 | 6 | jobs: 7 | derive-branch: 8 | runs-on: ubuntu-latest 9 | outputs: 10 | branch: ${{ steps.set-output.outputs.branch }} 11 | steps: 12 | - id: set-output 13 | run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})" 14 | 15 | benchmark: 16 | needs: derive-branch 17 | if: github.event.issue.pull_request && contains(github.event.comment.body, '/benchmark') 18 | permissions: 19 | contents: write 20 | with: 21 | runner: macos-13 22 | branch: ${{ needs.derive-branch.outputs.branch }} 23 | should-commit-benchmark: true 24 | uses: ./.github/workflows/benchmark.yml 25 | 26 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI for main 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | build: 10 | strategy: 11 | matrix: 12 | os: [ macos-latest, ubuntu-latest, windows-latest ] 13 | uses: ./.github/workflows/build.yml 14 | with: 15 | runner: ${{ matrix.os }} 16 | -------------------------------------------------------------------------------- /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request and Merge Workflow 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | paths-ignore: 8 | - 'benchmark/**' 9 | 10 | jobs: 11 | build: 12 | strategy: 13 | matrix: 14 | os: [ macos-latest, ubuntu-latest, windows-latest ] 15 | uses: ./.github/workflows/build.yml 16 | with: 17 | runner: ${{ matrix.os }} 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore Gradle GUI config 2 | gradle-app.setting 3 | 4 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 5 | !gradle/wrapper/gradle-wrapper.jar 6 | 7 | # Cache of project 8 | .gradletasknamecache 9 | 10 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 11 | # gradle/wrapper/gradle-wrapper.properties 12 | 13 | .idea 14 | .gradle 15 | .kotlin 16 | /local.properties 17 | /.idea/caches 18 | /.idea/libraries 19 | /.idea/modules.xml 20 | /.idea/workspace.xml 21 | /.idea/navEditor.xml 22 | /.idea/assetWizardSettings.xml 23 | /build 24 | /captures 25 | 26 | *.xcworkspacedata 27 | *.xcuserstate 28 | *.xcscheme 29 | xcschememanagement.plist 30 | *.xcbkptlist 31 | ### Kotlin template 32 | # Compiled class file 33 | *.class 34 | 35 | # Log file 36 | *.log 37 | 38 | # BlueJ files 39 | *.ctxt 40 | 41 | # Mobile Tools for Java (J2ME) 42 | .mtj.tmp/ 43 | 44 | # Package Files # 45 | *.jar 46 | *.war 47 | *.nar 48 | *.ear 49 | *.zip 50 | *.tar.gz 51 | *.rar 52 | 53 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 54 | hs_err_pid* 55 | 56 | ### Gradle template 57 | **/build/ 58 | !src/**/build/ 59 | 60 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 61 | # gradle/wrapper/gradle-wrapper.properties 62 | 63 | ### Windows template 64 | # Windows thumbnail cache files 65 | Thumbs.db 66 | Thumbs.db:encryptable 67 | ehthumbs.db 68 | ehthumbs_vista.db 69 | 70 | # Dump file 71 | *.stackdump 72 | 73 | # Folder config file 74 | [Dd]esktop.ini 75 | 76 | # Recycle Bin used on file shares 77 | $RECYCLE.BIN/ 78 | 79 | # Windows Installer files 80 | *.cab 81 | *.msi 82 | *.msix 83 | *.msm 84 | *.msp 85 | 86 | # Windows shortcuts 87 | *.lnk 88 | 89 | ### Android template 90 | # Built application files 91 | *.apk 92 | *.aar 93 | *.ap_ 94 | *.aab 95 | 96 | # Files for the ART/Dalvik VM 97 | *.dex 98 | 99 | # Java class files 100 | 101 | # Generated files 102 | bin/ 103 | gen/ 104 | out/ 105 | # Uncomment the following line in case you need and you don't have the release build type files in your app 106 | # release/ 107 | 108 | # Gradle files 109 | .gradle/ 110 | build/ 111 | 112 | # Local configuration file (sdk path, etc) 113 | local.properties 114 | 115 | # Proguard folder generated by Eclipse 116 | proguard/ 117 | 118 | # Log Files 119 | 120 | # Android Studio Navigation editor temp files 121 | .navigation/ 122 | 123 | # Android Studio captures folder 124 | captures/ 125 | 126 | # IntelliJ 127 | *.iml 128 | .idea/workspace.xml 129 | .idea/tasks.xml 130 | .idea/gradle.xml 131 | .idea/assetWizardSettings.xml 132 | .idea/dictionaries 133 | .idea/libraries 134 | # Android Studio 3 in .gitignore file. 135 | .idea/caches 136 | .idea/modules.xml 137 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 138 | .idea/navEditor.xml 139 | 140 | # Keystore files 141 | # Uncomment the following lines if you do not want to check your keystore files in. 142 | #*.jks 143 | #*.keystore 144 | 145 | # External native build folder generated in Android Studio 2.2 and later 146 | .externalNativeBuild 147 | .cxx/ 148 | 149 | # Google Services (e.g. APIs or Firebase) 150 | # google-services.json 151 | 152 | # Freeline 153 | freeline.py 154 | freeline/ 155 | freeline_project_description.json 156 | 157 | # fastlane 158 | fastlane/report.xml 159 | fastlane/Preview.html 160 | fastlane/screenshots 161 | fastlane/test_output 162 | fastlane/readme.md 163 | 164 | # Version control 165 | vcs.xml 166 | 167 | # lint 168 | lint/intermediates/ 169 | lint/generated/ 170 | lint/outputs/ 171 | lint/tmp/ 172 | # lint/reports/ 173 | 174 | # Android Profiling 175 | *.hprof 176 | 177 | ### Xcode template 178 | # Xcode 179 | # 180 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 181 | 182 | ## User settings 183 | xcuserdata/ 184 | 185 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 186 | *.xcscmblueprint 187 | *.xccheckout 188 | 189 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 190 | DerivedData/ 191 | *.moved-aside 192 | *.pbxuser 193 | !default.pbxuser 194 | *.mode1v3 195 | !default.mode1v3 196 | *.mode2v3 197 | !default.mode2v3 198 | *.perspectivev3 199 | !default.perspectivev3 200 | 201 | ## Gcc Patch 202 | /*.gcno 203 | 204 | ### macOS template 205 | # General 206 | .DS_Store 207 | .AppleDouble 208 | .LSOverride 209 | 210 | # Icon must end with two \r 211 | Icon 212 | 213 | # Thumbnails 214 | ._* 215 | 216 | # Files that might appear in the root of a volume 217 | .DocumentRevisions-V100 218 | .fseventsd 219 | .Spotlight-V100 220 | .TemporaryItems 221 | .Trashes 222 | .VolumeIcon.icns 223 | .com.apple.timemachine.donotpresent 224 | 225 | # Directories potentially created on remote AFP share 226 | .AppleDB 227 | .AppleDesktop 228 | Network Trash Folder 229 | Temporary Items 230 | .apdisk 231 | 232 | ### Swift template 233 | # Xcode 234 | # 235 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 236 | 237 | ## User settings 238 | 239 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 240 | 241 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 242 | 243 | ## Obj-C/Swift specific 244 | *.hmap 245 | 246 | ## App packaging 247 | *.ipa 248 | *.dSYM.zip 249 | *.dSYM 250 | 251 | ## Playgrounds 252 | timeline.xctimeline 253 | playground.xcworkspace 254 | 255 | # Swift Package Manager 256 | # 257 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 258 | # Packages/ 259 | # Package.pins 260 | # Package.resolved 261 | # *.xcodeproj 262 | # 263 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 264 | # hence it is not needed unless you have added a package configuration file to your project 265 | # .swiftpm 266 | 267 | .build/ 268 | 269 | # CocoaPods 270 | # 271 | # We recommend against adding the Pods directory to your .gitignore. However 272 | # you should judge for yourself, the pros and cons are mentioned at: 273 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 274 | # 275 | # Pods/ 276 | # 277 | # Add this line if you want to avoid checking in source code from the Xcode workspace 278 | # *.xcworkspace 279 | 280 | # Carthage 281 | # 282 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 283 | # Carthage/Checkouts 284 | 285 | Carthage/Build/ 286 | 287 | # Accio dependency management 288 | Dependencies/ 289 | .accio/ 290 | 291 | # fastlane 292 | # 293 | # It is recommended to not store the screenshots in the git repo. 294 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 295 | # For more information about the recommended setup visit: 296 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 297 | 298 | fastlane/screenshots/**/*.png 299 | 300 | # Code Injection 301 | # 302 | # After new code Injection tools there's a generated folder /iOSInjectionProject 303 | # https://github.com/johnno1962/injectionforxcode 304 | 305 | iOSInjectionProject/ 306 | 307 | ### JetBrains template 308 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 309 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 310 | 311 | # User-specific stuff 312 | .idea/**/workspace.xml 313 | .idea/**/tasks.xml 314 | .idea/**/usage.statistics.xml 315 | .idea/**/dictionaries 316 | .idea/**/shelf 317 | 318 | # Generated files 319 | .idea/**/contentModel.xml 320 | 321 | # Sensitive or high-churn files 322 | .idea/**/dataSources/ 323 | .idea/**/dataSources.ids 324 | .idea/**/dataSources.local.xml 325 | .idea/**/sqlDataSources.xml 326 | .idea/**/dynamic.xml 327 | .idea/**/uiDesigner.xml 328 | .idea/**/dbnavigator.xml 329 | 330 | # Gradle 331 | .idea/**/gradle.xml 332 | .idea/**/libraries 333 | 334 | # Gradle and Maven with auto-import 335 | # When using Gradle or Maven with auto-import, you should exclude module files, 336 | # since they will be recreated, and may cause churn. Uncomment if using 337 | # auto-import. 338 | # .idea/artifacts 339 | # .idea/compiler.xml 340 | # .idea/jarRepositories.xml 341 | # .idea/modules.xml 342 | # .idea/*.iml 343 | # .idea/modules 344 | # *.iml 345 | # *.ipr 346 | 347 | # CMake 348 | cmake-build-*/ 349 | 350 | # Mongo Explorer plugin 351 | .idea/**/mongoSettings.xml 352 | 353 | # File-based project format 354 | *.iws 355 | 356 | # IntelliJ 357 | 358 | # mpeltonen/sbt-idea plugin 359 | .idea_modules/ 360 | 361 | # JIRA plugin 362 | atlassian-ide-plugin.xml 363 | 364 | # Cursive Clojure plugin 365 | .idea/replstate.xml 366 | 367 | # Crashlytics plugin (for Android Studio and IntelliJ) 368 | com_crashlytics_export_strings.xml 369 | crashlytics.properties 370 | crashlytics-build.properties 371 | fabric.properties 372 | 373 | # Editor-based Rest Client 374 | .idea/httpRequests 375 | 376 | # Android studio 3.1+ serialized cache file 377 | .idea/caches/build_file_checksums.ser 378 | 379 | ### Linux template 380 | *~ 381 | 382 | # temporary files which can be created if a process still has a handle open of a deleted file 383 | .fuse_hidden* 384 | 385 | # KDE directory preferences 386 | .directory 387 | 388 | # Linux trash folder which might appear on any partition or disk 389 | .Trash-* 390 | 391 | # .nfs files are created when an open file is removed but is still being accessed 392 | .nfs* 393 | *.trace 394 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to cachemap 2 | 3 | 4 | ## License of Contributions 5 | 6 | By contributing to this project, you agree that your contributions will be licensed under both the MIT and the Apache 2.0 licenses, to give users a choice of which terms they use the software under. 7 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Charlie Tapping 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cachemap 2 | 3 | ![badge][badge-android] 4 | ![badge][badge-jvm] 5 | ![badge][badge-ios] 6 | ![badge][badge-linux] 7 | ![badge][badge-mac] 8 | ![badge][badge-windows] 9 | 10 | --- 11 | 12 | CacheMap is single writer concurrent hashmap implementation. 13 | 14 | Reads from the hashmap can proceed concurrently to writes from any thread with zero coordination necessary... No locks 15 | and no waits 16 | 17 | CacheMap implements `Map` so can be used in place of existing map instances. 18 | 19 | CacheMap implements all of MutableMap with the exception of `val entries: Set>` 20 | as exposing MutableEntry's would allow mutation without the necessary write coordination. 21 | 22 | CacheMap is ultimately a thin wrapper around the [left-right concurrency primitive](#leftright). 23 | 24 | # Setup 25 | 26 | ```kotlin 27 | dependencies { 28 | implementation("io.github.charlietap:cachemap:0.2.4") 29 | // Or 30 | implementation("io.github.charlietap:cachemap-suspend:0.2.4") 31 | } 32 | ``` 33 | 34 | # Usage 35 | 36 | Instance creation follows the typical Kotlin convention 37 | 38 | ```kotlin 39 | val cachemap = cacheMapOf() 40 | ``` 41 | 42 | For sizing the initial capacity you can use 43 | ```kotlin 44 | val cachemap = cacheMapOf(9000) 45 | ``` 46 | And for pre-population a varargs constructor exists 47 | ```kotlin 48 | val cachemap = cacheMapOf(key to value,...) 49 | ``` 50 | Use cachemap like any MutableMap in Kotlin 51 | ```kotlin 52 | cachemap[key] = value 53 | // or 54 | cachemap.put(key, value) 55 | ``` 56 | 57 | ### Coroutines 58 | 59 | For reasons [documented in leftright](#coroutines-1) cachemap may block or yield within methods that 60 | mutate the map. If you would prefer to not block the underlying thread you can use the suspending variant 61 | of cachemap: 62 | 63 | ```kotlin 64 | val cachemap = suspendCacheMapOf() 65 | ``` 66 | Use cachemap like any MutableMap in Kotlin 67 | ```kotlin 68 | scope.launch { 69 | cachemap.put(key, value) 70 | } 71 | 72 | // Unfortunately operator functions cannot suspend so this is not possible 73 | // scope.launch { 74 | // cachemap[key] = value 75 | // } 76 | ``` 77 | 78 | # leftright 79 | 80 | left-right is a concurrency primitive which allows lock-free/wait-free reads of any mutable datastructure. 81 | 82 | Conceptually left-right can be understood as a concurrency primitive that maintains two copies of a datastructure with a pointer (switch) 83 | directing traffic for reads and writes in separate directions. 84 | 85 | ```mermaid 86 | graph TD; 87 | Switch--reads-->Left; 88 | Switch--writes-->Right; 89 | ``` 90 | 91 | If you're interested in learning more about the intricacies of the algorithm I would recommend an [incredible video from John Gjengset](https://youtu.be/eLNAMEoKAAc?si=OwLcy5kWJRFxCHtH) 92 | which details his creation of an eventually-consistent implementation of a left-right. 93 | My implementation borrows the same epoch counter algorithm for waiting on departing readers with a deviation to avoid the global epoch array lock 94 | by imposing a max parallelism invariant and leveraging ThreadLocal state. 95 | 96 | You can also find what I believe to be the first paper on the primitive [here](https://hal.science/hal-01207881/document). 97 | 98 | # Setup 99 | 100 | ```kotlin 101 | dependencies { 102 | implementation("io.github.charlietap:leftright:0.2.4") 103 | // Or 104 | implementation("io.github.charlietap:leftright-suspend:0.2.4") 105 | } 106 | ``` 107 | 108 | # Usage 109 | 110 | LeftRight is generic over any given datastructure and can be constructed like so 111 | 112 | ```kotlin 113 | val leftright = LeftRight(::constructorForT) 114 | 115 | // For example 116 | 117 | val leftRightSet = LeftRight>(::mutableSetOf) 118 | ``` 119 | 120 | ### Coroutines 121 | 122 | Whilst reads avoid locks and waits, writes are not so lucky. A write is capable of both 123 | blocking on a mutex and yielding back to the scheduler if readers take too long to depart. 124 | Rather than blocking valuable thread resources you can yield back to the coroutines runtime 125 | using with the suspend variant: 126 | 127 | ```kotlin 128 | val leftright = SuspendLeftRight(::constructorForT) 129 | 130 | // For example 131 | 132 | val leftRightSet = SuspendLeftRight>(::mutableSetOf) 133 | 134 | // mutate is now suspending 135 | scope.launch { 136 | leftRightSet.mutate { 137 | it.add("Hello worlds") 138 | } 139 | } 140 | ``` 141 | 142 | ## Additional Reading 143 | 144 | - [Making my concurrent algo 6000% better](https://dev.to/charlietap/making-my-concurrent-algorithm-6000-better-24oo) 145 | 146 | 147 | ## License 148 | 149 | This project is dual-licensed under both the MIT and Apache 2.0 licenses. You can choose which one you want to use the software under. 150 | 151 | - For details on the MIT license, please see the [LICENSE-MIT](LICENSE-MIT) file. 152 | - For details on the Apache 2.0 license, please see the [LICENSE-APACHE](LICENSE-APACHE) file. 153 | 154 | [badge-android]: http://img.shields.io/badge/-android-6EDB8D.svg?style=flat 155 | [badge-jvm]: http://img.shields.io/badge/-jvm-DB413D.svg?style=flat 156 | [badge-linux]: http://img.shields.io/badge/-linux-2D3F6C.svg?style=flat 157 | [badge-ios]: http://img.shields.io/badge/-ios-CDCDCD.svg?style=flat 158 | [badge-mac]: http://img.shields.io/badge/-macos-111111.svg?style=flat 159 | [badge-windows]: http://img.shields.io/badge/-windows-4D76CD.svg?style=flat 160 | -------------------------------------------------------------------------------- /benchmark/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | // temp fix for benchmark embedded compiler bug 4 | buildscript { 5 | configurations.all { 6 | resolutionStrategy { 7 | eachDependency { 8 | if (requested.group == "org.jetbrains.kotlin") { 9 | val kv = libs.versions.kotlin.get() 10 | logger.warn("${requested.group}:${requested.name}:${requested.version} --> $kv") 11 | useVersion(kv) 12 | } 13 | } 14 | } 15 | } 16 | } 17 | 18 | plugins { 19 | alias(libs.plugins.kotlin.multiplatform) 20 | alias(libs.plugins.kotlin.serialization) 21 | alias(libs.plugins.kotlin.allopen) 22 | alias(libs.plugins.kotlin.atomic.fu) 23 | alias(libs.plugins.kotlin.benchmark) 24 | id("linting-conventions") 25 | } 26 | 27 | allOpen { 28 | annotation("org.openjdk.jmh.annotations.State") 29 | annotation("kotlinx.benchmark.State") 30 | } 31 | 32 | benchmark { 33 | targets { 34 | register("jvm") 35 | register("macosArm64") 36 | } 37 | } 38 | 39 | kotlin { 40 | 41 | jvm() 42 | macosArm64() 43 | 44 | jvmToolchain { 45 | languageVersion.set(JavaLanguageVersion.of(libs.versions.java.compiler.version.get().toInt())) 46 | vendor.set(JvmVendorSpec.matching(libs.versions.java.vendor.get())) 47 | } 48 | 49 | targets.configureEach { 50 | compilations.configureEach { 51 | kotlinOptions { 52 | 53 | } 54 | } 55 | } 56 | 57 | sourceSets { 58 | 59 | commonMain { 60 | dependencies { 61 | implementation(projects.cachemap) 62 | implementation(projects.cachemapSuspend) 63 | implementation(libs.kotlinx.atomic.fu) 64 | implementation(libs.kotlinx.benchmark) 65 | implementation(libs.kotlinx.coroutines.core) 66 | } 67 | } 68 | 69 | commonTest { 70 | dependencies { 71 | implementation(libs.kotlin.test) 72 | } 73 | } 74 | 75 | jvmMain { 76 | dependencies { 77 | 78 | } 79 | } 80 | } 81 | } 82 | 83 | tasks.withType().configureEach { 84 | kotlinOptions.jvmTarget = libs.versions.java.bytecode.version.get() 85 | } 86 | -------------------------------------------------------------------------------- /benchmark/src/commonMain/kotlin/io/github/charlietap/cachemap/benchmark/BenchmarkConfig.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | object BenchmarkConfig { 4 | const val WARMUP_ITERATIONS = 10 5 | const val MEASUREMENT_ITERATIONS = 10 6 | const val FORKS = 10 7 | } 8 | -------------------------------------------------------------------------------- /benchmark/src/jvmMain/kotlin/io/github/charlietap/cachemap/benchmark/CacheMapMultiThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | import org.openjdk.jmh.annotations.Threads 4 | 5 | @Threads(Threads.MAX) 6 | class CacheMapMultiThreadedBenchmark : CacheMapSingleThreadBenchmark() 7 | -------------------------------------------------------------------------------- /benchmark/src/jvmMain/kotlin/io/github/charlietap/cachemap/benchmark/CacheMapSingleThreadBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | import io.github.charlietap.cachemap.cacheMapOf 3 | import org.openjdk.jmh.annotations.Benchmark 4 | import org.openjdk.jmh.annotations.BenchmarkMode 5 | import org.openjdk.jmh.annotations.Fork 6 | import org.openjdk.jmh.annotations.Level 7 | import org.openjdk.jmh.annotations.Measurement 8 | import org.openjdk.jmh.annotations.Mode 9 | import org.openjdk.jmh.annotations.OutputTimeUnit 10 | import org.openjdk.jmh.annotations.Scope 11 | import org.openjdk.jmh.annotations.Setup 12 | import org.openjdk.jmh.annotations.State 13 | import org.openjdk.jmh.annotations.TearDown 14 | import org.openjdk.jmh.annotations.Warmup 15 | import org.openjdk.jmh.infra.Blackhole 16 | import java.util.concurrent.TimeUnit 17 | 18 | @State(Scope.Benchmark) 19 | @Fork(value = BenchmarkConfig.FORKS) 20 | @BenchmarkMode(Mode.AverageTime, Mode.Throughput) 21 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 22 | @Warmup(iterations = BenchmarkConfig.WARMUP_ITERATIONS, time = 1, timeUnit = TimeUnit.SECONDS) 23 | @Measurement(iterations = BenchmarkConfig.MEASUREMENT_ITERATIONS, time = 1, timeUnit = TimeUnit.SECONDS) 24 | class CacheMapSingleThreadBenchmark { 25 | 26 | private val cacheMap = cacheMapOf() 27 | 28 | @Setup(Level.Iteration) 29 | fun setup() { 30 | for (i in 1..1000) { 31 | cacheMap.put("key$i", "value$i") 32 | } 33 | } 34 | 35 | @Benchmark 36 | fun put(blackhole: Blackhole) { 37 | val result = cacheMap.put("Hello", "World") 38 | blackhole.consume(result) 39 | } 40 | 41 | @Benchmark 42 | fun overwrite(blackhole: Blackhole) { 43 | val result = cacheMap.put("key1", "value2") 44 | blackhole.consume(result) 45 | } 46 | 47 | @Benchmark 48 | fun putAll(blackhole: Blackhole) { 49 | val anotherMap = mapOf("Hello" to "World", "SecondKey" to "SecondValue") 50 | val result = cacheMap.putAll(anotherMap) 51 | blackhole.consume(result) 52 | } 53 | 54 | @Benchmark 55 | fun get(blackhole: Blackhole) { 56 | val result: String? = cacheMap["key1"] 57 | blackhole.consume(result) 58 | } 59 | 60 | @Benchmark 61 | fun getMiss(blackhole: Blackhole) { 62 | val result: String? = cacheMap["Hello"] 63 | blackhole.consume(result) 64 | } 65 | 66 | @Benchmark 67 | fun remove(blackhole: Blackhole) { 68 | val result = cacheMap.remove("key1") 69 | blackhole.consume(result) 70 | } 71 | 72 | @Benchmark 73 | fun stressTest(blackhole: Blackhole) { 74 | for (i in 1..1000) { 75 | val putResult = cacheMap.put("newKey$i", "newValue$i") 76 | blackhole.consume(putResult) 77 | 78 | val getResult: String? = cacheMap["key$i"] 79 | blackhole.consume(getResult) 80 | 81 | val removeResult = cacheMap.remove("newKey$i") 82 | blackhole.consume(removeResult) 83 | } 84 | } 85 | 86 | @TearDown(Level.Iteration) 87 | fun tearDown() { 88 | cacheMap.clear() 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /benchmark/src/jvmMain/kotlin/io/github/charlietap/cachemap/benchmark/ConcurrentHashMapMultiThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | import org.openjdk.jmh.annotations.Threads 4 | 5 | @Threads(Threads.MAX) 6 | class ConcurrentHashMapMultiThreadedBenchmark : ConcurrentHashMapSingleThreadedBenchmark() 7 | -------------------------------------------------------------------------------- /benchmark/src/jvmMain/kotlin/io/github/charlietap/cachemap/benchmark/ConcurrentHashMapSingleThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | import org.openjdk.jmh.annotations.Benchmark 4 | import org.openjdk.jmh.annotations.BenchmarkMode 5 | import org.openjdk.jmh.annotations.Fork 6 | import org.openjdk.jmh.annotations.Level 7 | import org.openjdk.jmh.annotations.Measurement 8 | import org.openjdk.jmh.annotations.Mode 9 | import org.openjdk.jmh.annotations.OutputTimeUnit 10 | import org.openjdk.jmh.annotations.Scope 11 | import org.openjdk.jmh.annotations.Setup 12 | import org.openjdk.jmh.annotations.State 13 | import org.openjdk.jmh.annotations.TearDown 14 | import org.openjdk.jmh.annotations.Warmup 15 | import org.openjdk.jmh.infra.Blackhole 16 | import java.util.concurrent.ConcurrentHashMap 17 | import java.util.concurrent.TimeUnit 18 | 19 | @State(Scope.Benchmark) 20 | @Fork(value = BenchmarkConfig.FORKS) 21 | @BenchmarkMode(Mode.AverageTime, Mode.Throughput) 22 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 23 | @Warmup(iterations = BenchmarkConfig.WARMUP_ITERATIONS, time = 1, timeUnit = TimeUnit.SECONDS) 24 | @Measurement(iterations = BenchmarkConfig.MEASUREMENT_ITERATIONS, time = 1, timeUnit = TimeUnit.SECONDS) 25 | class ConcurrentHashMapSingleThreadedBenchmark { 26 | 27 | private val cacheMap = ConcurrentHashMap() 28 | 29 | @Setup(Level.Iteration) 30 | fun setup() { 31 | for (i in 1..1000) { 32 | cacheMap["key$i"] = "value$i" 33 | } 34 | } 35 | 36 | @Benchmark 37 | fun put(blackhole: Blackhole) { 38 | val result = cacheMap.put("Hello", "World") 39 | blackhole.consume(result) 40 | } 41 | 42 | @Benchmark 43 | fun overwrite(blackhole: Blackhole) { 44 | val result = cacheMap.put("key1", "value2") 45 | blackhole.consume(result) 46 | } 47 | 48 | @Benchmark 49 | fun putAll(blackhole: Blackhole) { 50 | val anotherMap = mapOf("Hello" to "World", "SecondKey" to "SecondValue") 51 | cacheMap.putAll(anotherMap) 52 | blackhole.consume(anotherMap) 53 | } 54 | 55 | @Benchmark 56 | fun get(blackhole: Blackhole) { 57 | val result: String? = cacheMap["key1"] 58 | blackhole.consume(result) 59 | } 60 | 61 | @Benchmark 62 | fun getMiss(blackhole: Blackhole) { 63 | val result: String? = cacheMap["Hello"] 64 | blackhole.consume(result) 65 | } 66 | 67 | @Benchmark 68 | fun remove(blackhole: Blackhole) { 69 | val result = cacheMap.remove("key1") 70 | blackhole.consume(result) 71 | } 72 | 73 | @Benchmark 74 | fun stressTest(blackhole: Blackhole) { 75 | for (i in 1..1000) { 76 | val putResult = cacheMap.put("newKey$i", "newValue$i") 77 | blackhole.consume(putResult) 78 | 79 | val getResult: String? = cacheMap["key$i"] 80 | blackhole.consume(getResult) 81 | 82 | val removeResult = cacheMap.remove("newKey$i") 83 | blackhole.consume(removeResult) 84 | } 85 | } 86 | 87 | @TearDown(Level.Iteration) 88 | fun tearDown() { 89 | cacheMap.clear() 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /benchmark/src/jvmMain/kotlin/io/github/charlietap/cachemap/benchmark/RWHashMapMultiThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | import org.openjdk.jmh.annotations.Threads 4 | 5 | @Threads(Threads.MAX) 6 | class RWHashMapMultiThreadedBenchmark : RWHashMapSingleThreadedBenchmark() 7 | -------------------------------------------------------------------------------- /benchmark/src/jvmMain/kotlin/io/github/charlietap/cachemap/benchmark/RWHashMapSingleThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | import org.openjdk.jmh.annotations.Benchmark 4 | import org.openjdk.jmh.annotations.BenchmarkMode 5 | import org.openjdk.jmh.annotations.Fork 6 | import org.openjdk.jmh.annotations.Level 7 | import org.openjdk.jmh.annotations.Measurement 8 | import org.openjdk.jmh.annotations.Mode 9 | import org.openjdk.jmh.annotations.OutputTimeUnit 10 | import org.openjdk.jmh.annotations.Scope 11 | import org.openjdk.jmh.annotations.Setup 12 | import org.openjdk.jmh.annotations.State 13 | import org.openjdk.jmh.annotations.TearDown 14 | import org.openjdk.jmh.annotations.Warmup 15 | import org.openjdk.jmh.infra.Blackhole 16 | import java.util.concurrent.TimeUnit 17 | import java.util.concurrent.locks.ReentrantReadWriteLock 18 | import kotlin.concurrent.read 19 | import kotlin.concurrent.write 20 | 21 | @State(Scope.Benchmark) 22 | @Fork(value = BenchmarkConfig.FORKS) 23 | @BenchmarkMode(Mode.AverageTime, Mode.Throughput) 24 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 25 | @Warmup(iterations = BenchmarkConfig.WARMUP_ITERATIONS, time = 1, timeUnit = TimeUnit.SECONDS) 26 | @Measurement(iterations = BenchmarkConfig.MEASUREMENT_ITERATIONS, time = 1, timeUnit = TimeUnit.SECONDS) 27 | class RWHashMapSingleThreadedBenchmark { 28 | 29 | private val map = HashMap() 30 | private val rwLock = ReentrantReadWriteLock() 31 | 32 | @Setup(Level.Iteration) 33 | fun setup() { 34 | for (i in 1..1000) { 35 | map["key$i"] = "value$i" 36 | } 37 | } 38 | 39 | @Benchmark 40 | fun put(blackhole: Blackhole) { 41 | val result = rwLock.write { 42 | map.put("Hello", "World") 43 | } 44 | blackhole.consume(result) 45 | } 46 | 47 | @Benchmark 48 | fun overwrite(blackhole: Blackhole) { 49 | val result = rwLock.write { 50 | map.put("key1", "value2") 51 | } 52 | blackhole.consume(result) 53 | } 54 | 55 | @Benchmark 56 | fun putAll(blackhole: Blackhole) { 57 | val anotherMap = mapOf("Hello" to "World", "SecondKey" to "SecondValue") 58 | rwLock.write { 59 | map.putAll(anotherMap) 60 | } 61 | blackhole.consume(anotherMap) 62 | } 63 | 64 | @Benchmark 65 | fun get(blackhole: Blackhole) { 66 | val result: String? = rwLock.read { 67 | map["key1"] 68 | } 69 | blackhole.consume(result) 70 | } 71 | 72 | @Benchmark 73 | fun getMiss(blackhole: Blackhole) { 74 | val result: String? = rwLock.read { 75 | map["Hello"] 76 | } 77 | blackhole.consume(result) 78 | } 79 | 80 | @Benchmark 81 | fun remove(blackhole: Blackhole) { 82 | val result = rwLock.write { 83 | map.remove("key1") 84 | } 85 | blackhole.consume(result) 86 | } 87 | 88 | @Benchmark 89 | fun stressTest(blackhole: Blackhole) { 90 | for (i in 1..1000) { 91 | val putResult = rwLock.write { 92 | map.put("newKey$i", "newValue$i") 93 | } 94 | blackhole.consume(putResult) 95 | 96 | val getResult: String? = rwLock.read { 97 | map["key$i"] 98 | } 99 | blackhole.consume(getResult) 100 | 101 | val removeResult = rwLock.write { 102 | map.remove("newKey$i") 103 | } 104 | blackhole.consume(removeResult) 105 | } 106 | } 107 | 108 | @TearDown(Level.Iteration) 109 | fun tearDown() { 110 | map.clear() 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /benchmark/src/nativeMain/kotlin/io/github/charlietap/cachemap/benchmark/CacheMapMultiThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | // Todo enable threading 4 | class CacheMapMultiThreadedBenchmark : CacheMapSingleThreadBenchmark() 5 | -------------------------------------------------------------------------------- /benchmark/src/nativeMain/kotlin/io/github/charlietap/cachemap/benchmark/CacheMapSingleThreadBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | import io.github.charlietap.cachemap.cacheMapOf 4 | import kotlinx.benchmark.Benchmark 5 | import kotlinx.benchmark.BenchmarkMode 6 | import kotlinx.benchmark.BenchmarkTimeUnit 7 | import kotlinx.benchmark.Blackhole 8 | import kotlinx.benchmark.Measurement 9 | import kotlinx.benchmark.Mode 10 | import kotlinx.benchmark.OutputTimeUnit 11 | import kotlinx.benchmark.Scope 12 | import kotlinx.benchmark.Setup 13 | import kotlinx.benchmark.State 14 | import kotlinx.benchmark.TearDown 15 | import kotlinx.benchmark.Warmup 16 | 17 | @State(Scope.Benchmark) 18 | @BenchmarkMode(Mode.AverageTime) 19 | @OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) 20 | @Warmup(iterations = BenchmarkConfig.WARMUP_ITERATIONS) 21 | @Measurement(iterations = BenchmarkConfig.MEASUREMENT_ITERATIONS, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) 22 | class CacheMapSingleThreadBenchmark { 23 | 24 | private val cacheMap = cacheMapOf() 25 | 26 | @Setup() 27 | fun setup() { 28 | for (i in 1..1000) { 29 | cacheMap.put("key$i", "value$i") 30 | } 31 | } 32 | 33 | @Benchmark 34 | fun put(blackhole: Blackhole) { 35 | val result = cacheMap.put("Hello", "World") 36 | blackhole.consume(result) 37 | } 38 | 39 | @Benchmark 40 | fun overwrite(blackhole: Blackhole) { 41 | val result = cacheMap.put("key1", "value2") 42 | blackhole.consume(result) 43 | } 44 | 45 | @Benchmark 46 | fun putAll(blackhole: Blackhole) { 47 | val anotherMap = mapOf("Hello" to "World", "SecondKey" to "SecondValue") 48 | val result = cacheMap.putAll(anotherMap) 49 | blackhole.consume(result) 50 | } 51 | 52 | @Benchmark 53 | fun get(blackhole: Blackhole) { 54 | val result: String? = cacheMap["key1"] 55 | blackhole.consume(result) 56 | } 57 | 58 | @Benchmark 59 | fun getMiss(blackhole: Blackhole) { 60 | val result: String? = cacheMap["Hello"] 61 | blackhole.consume(result) 62 | } 63 | 64 | @Benchmark 65 | fun remove(blackhole: Blackhole) { 66 | val result = cacheMap.remove("key1") 67 | blackhole.consume(result) 68 | } 69 | 70 | @Benchmark 71 | fun stressTest(blackhole: Blackhole) { 72 | for (i in 1..1000) { 73 | val putResult = cacheMap.put("newKey$i", "newValue$i") 74 | blackhole.consume(putResult) 75 | 76 | val getResult: String? = cacheMap["key$i"] 77 | blackhole.consume(getResult) 78 | 79 | val removeResult = cacheMap.remove("newKey$i") 80 | blackhole.consume(removeResult) 81 | } 82 | } 83 | 84 | @TearDown() 85 | fun tearDown() { 86 | cacheMap.clear() 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /benchmark/src/nativeMain/kotlin/io/github/charlietap/cachemap/benchmark/RWHashMapMultiThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | // todo add threads 4 | class RWHashMapMultiThreadedBenchmark : RWHashMapSingleThreadedBenchmark() 5 | -------------------------------------------------------------------------------- /benchmark/src/nativeMain/kotlin/io/github/charlietap/cachemap/benchmark/RWHashMapSingleThreadedBenchmark.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap.benchmark 2 | 3 | import kotlinx.atomicfu.locks.ReentrantLock 4 | import kotlinx.atomicfu.locks.withLock 5 | import kotlinx.benchmark.Benchmark 6 | import kotlinx.benchmark.BenchmarkMode 7 | import kotlinx.benchmark.BenchmarkTimeUnit 8 | import kotlinx.benchmark.Blackhole 9 | import kotlinx.benchmark.Measurement 10 | import kotlinx.benchmark.Mode 11 | import kotlinx.benchmark.OutputTimeUnit 12 | import kotlinx.benchmark.Scope 13 | import kotlinx.benchmark.Setup 14 | import kotlinx.benchmark.State 15 | import kotlinx.benchmark.TearDown 16 | import kotlinx.benchmark.Warmup 17 | 18 | @State(Scope.Benchmark) 19 | @BenchmarkMode(Mode.AverageTime) 20 | @OutputTimeUnit(BenchmarkTimeUnit.NANOSECONDS) 21 | @Warmup(iterations = BenchmarkConfig.WARMUP_ITERATIONS) 22 | @Measurement(iterations = BenchmarkConfig.MEASUREMENT_ITERATIONS, time = 1, timeUnit = BenchmarkTimeUnit.SECONDS) 23 | class RWHashMapSingleThreadedBenchmark { 24 | 25 | private val map = HashMap() 26 | private val lock = ReentrantLock() 27 | 28 | @Setup() 29 | fun setup() { 30 | for (i in 1..1000) { 31 | map["key$i"] = "value$i" 32 | } 33 | } 34 | 35 | @Benchmark 36 | fun put(blackhole: Blackhole) { 37 | val result = lock.withLock { 38 | map.put("Hello", "World") 39 | } 40 | blackhole.consume(result) 41 | } 42 | 43 | @Benchmark 44 | fun overwrite(blackhole: Blackhole) { 45 | val result = lock.withLock { 46 | map.put("key1", "value2") 47 | } 48 | blackhole.consume(result) 49 | } 50 | 51 | @Benchmark 52 | fun putAll(blackhole: Blackhole) { 53 | val anotherMap = mapOf("Hello" to "World", "SecondKey" to "SecondValue") 54 | lock.withLock { 55 | map.putAll(anotherMap) 56 | } 57 | blackhole.consume(anotherMap) 58 | } 59 | 60 | @Benchmark 61 | fun get(blackhole: Blackhole) { 62 | val result: String? = lock.withLock { 63 | map["key1"] 64 | } 65 | blackhole.consume(result) 66 | } 67 | 68 | @Benchmark 69 | fun getMiss(blackhole: Blackhole) { 70 | val result: String? = lock.withLock { 71 | map["Hello"] 72 | } 73 | blackhole.consume(result) 74 | } 75 | 76 | @Benchmark 77 | fun remove(blackhole: Blackhole) { 78 | val result = lock.withLock { 79 | map.remove("key1") 80 | } 81 | blackhole.consume(result) 82 | } 83 | 84 | @Benchmark 85 | fun stressTest(blackhole: Blackhole) { 86 | for (i in 1..1000) { 87 | val putResult = lock.withLock { 88 | map.put("newKey$i", "newValue$i") 89 | } 90 | blackhole.consume(putResult) 91 | 92 | val getResult: String? = lock.withLock { 93 | map["key$i"] 94 | } 95 | blackhole.consume(getResult) 96 | 97 | val removeResult = lock.withLock { 98 | map.remove("newKey$i") 99 | } 100 | blackhole.consume(removeResult) 101 | } 102 | } 103 | 104 | @TearDown() 105 | fun tearDown() { 106 | map.clear() 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.kotlin.multiplatform) apply false 3 | alias(libs.plugins.kotlin.atomic.fu) apply false 4 | alias(libs.plugins.dokka) apply false 5 | id("maven-publish") 6 | id("versions-conventions") 7 | } 8 | 9 | tasks.register("clean",Delete::class){ 10 | delete(rootProject.layout.buildDirectory) 11 | } 12 | -------------------------------------------------------------------------------- /cachemap-suspend/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.dokka.gradle.DokkaTask 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | plugins { 5 | alias(libs.plugins.kotlin.multiplatform) 6 | alias(libs.plugins.kotlin.serialization) 7 | alias(libs.plugins.kotlin.atomic.fu) 8 | id("kmp-conventions") 9 | id("linting-conventions") 10 | id("publishing-conventions") 11 | } 12 | 13 | kotlin { 14 | 15 | sourceSets { 16 | 17 | commonMain { 18 | dependencies { 19 | implementation(projects.leftrightSuspend) 20 | } 21 | } 22 | 23 | commonTest { 24 | dependencies { 25 | implementation(libs.kotlin.test) 26 | implementation(libs.kotlinx.coroutines.test) 27 | } 28 | } 29 | 30 | jvmMain { 31 | dependencies { 32 | 33 | } 34 | } 35 | } 36 | } 37 | 38 | configure { 39 | name = "cachemap-suspend" 40 | description = "A read optimised suspending concurrent map for Kotlin Multiplatform" 41 | } 42 | 43 | tasks.withType().configureEach { 44 | kotlinOptions.jvmTarget = libs.versions.java.bytecode.version.get() 45 | } 46 | -------------------------------------------------------------------------------- /cachemap-suspend/src/commonMain/kotlin/io/github/charlietap/cachemap/InternalSuspendCacheMap.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap 2 | 3 | import io.github.charlietap.leftright.SuspendLeftRight as LeftRight 4 | 5 | internal class InternalSuspendCacheMap( 6 | readerParallelism: Int? = null, 7 | initialCapacity: Int? = null, 8 | initialPopulation: Map? = null, 9 | ) : Map, SuspendCacheMap { 10 | 11 | private val inner = constructor( 12 | readerParallelism, 13 | initialCapacity, 14 | initialPopulation, 15 | ) 16 | 17 | override val entries: Set> 18 | get() = inner.read(MutableMap::entries) 19 | 20 | override val keys: Set 21 | get() = inner.read(MutableMap::keys) 22 | 23 | override val size: Int 24 | get() = inner.read(MutableMap::size) 25 | 26 | override val values: Collection 27 | get() = inner.read(MutableMap::values) 28 | 29 | override fun isEmpty(): Boolean = inner.read(MutableMap::isEmpty) 30 | 31 | override fun get(key: K): V? { 32 | return inner.read { map -> 33 | map[key] 34 | } 35 | } 36 | 37 | override fun containsKey(key: K): Boolean { 38 | return inner.read { map -> 39 | map.containsKey(key) 40 | } 41 | } 42 | 43 | override fun containsValue(value: V): Boolean { 44 | return inner.read { map -> 45 | map.containsValue(value) 46 | } 47 | } 48 | 49 | override suspend fun put(key: K, value: V) { 50 | return inner.mutate { map -> 51 | map[key] = value 52 | } 53 | } 54 | 55 | override suspend fun putAll(from: Map) { 56 | return inner.mutate { map -> 57 | from.forEach { (key, value) -> 58 | map[key] = value 59 | } 60 | } 61 | } 62 | 63 | override suspend fun remove(key: K): V? { 64 | return inner.mutate { map -> 65 | map.remove(key) 66 | } 67 | } 68 | 69 | override suspend fun remove(key: K, value: V): Boolean { 70 | return inner.mutate { map -> 71 | val mapValue = map[key] 72 | if (value == mapValue) { 73 | map.remove(key) 74 | true 75 | } else { 76 | false 77 | } 78 | } 79 | } 80 | 81 | override suspend fun clear() = inner.mutate(MutableMap::clear) 82 | 83 | companion object { 84 | fun constructor( 85 | readerParallelism: Int? = null, 86 | capacity: Int? = null, 87 | population: Map? = null, 88 | ): LeftRight> = if ( 89 | readerParallelism == null && capacity == null && population == null 90 | ) { 91 | LeftRight(::mutableMapOf) 92 | } else { 93 | val constructor = { 94 | if (capacity != null) { 95 | HashMap(capacity) 96 | } else if (population != null) { 97 | HashMap(population) 98 | } else { 99 | HashMap() 100 | } 101 | } 102 | if (readerParallelism != null) { 103 | LeftRight(constructor, readerParallelism) 104 | } else { 105 | LeftRight(constructor) 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /cachemap-suspend/src/commonMain/kotlin/io/github/charlietap/cachemap/SuspendCacheMap.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap 2 | 3 | interface SuspendCacheMap : Map { 4 | 5 | suspend fun put(key: K, value: V) 6 | 7 | suspend fun putAll(from: Map) 8 | 9 | suspend fun remove(key: K): V? 10 | 11 | suspend fun remove(key: K, value: V): Boolean 12 | 13 | suspend fun clear() 14 | } 15 | 16 | fun suspendCacheMapOf(): SuspendCacheMap { 17 | return InternalSuspendCacheMap() 18 | } 19 | 20 | fun suspendCacheMapOf(vararg args: Pair): SuspendCacheMap { 21 | return InternalSuspendCacheMap(initialPopulation = args.toMap()) 22 | } 23 | 24 | fun suspendCacheMapOf(readerParallelism: Int, initialCapacity: Int, initialPopulation: Map): SuspendCacheMap { 25 | return InternalSuspendCacheMap(readerParallelism, initialCapacity, initialPopulation) 26 | } 27 | -------------------------------------------------------------------------------- /cachemap-suspend/src/commonTest/kotlin/io/github/charlietap/cachemap/SuspendCacheMapTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap 2 | 3 | import kotlinx.coroutines.test.runTest 4 | import kotlin.test.Test 5 | import kotlin.test.assertEquals 6 | 7 | class SuspendCacheMapTest { 8 | 9 | @Test 10 | fun `can prepopulate the map on construction`() { 11 | val cachemap = suspendCacheMapOf( 12 | "Hello" to "World", 13 | "Foo" to "Bar", 14 | ) 15 | 16 | assertEquals("World", cachemap["Hello"]) 17 | assertEquals("Bar", cachemap["Foo"]) 18 | } 19 | 20 | @Test 21 | fun `can insert a value and retrieve it`() = runTest { 22 | val cachemap = suspendCacheMapOf() 23 | 24 | cachemap.put("Hello", "World") 25 | val result = cachemap.get("Hello") 26 | 27 | assertEquals("World", result) 28 | } 29 | 30 | @Test 31 | fun `can insert multiple entries`() = runTest { 32 | val cachemap = suspendCacheMapOf() 33 | 34 | val insertees = mapOf( 35 | "Hello" to "World", 36 | "Foo" to "Bar", 37 | ) 38 | 39 | cachemap.putAll(insertees) 40 | 41 | assertEquals("World", cachemap["Hello"]) 42 | assertEquals("Bar", cachemap["Foo"]) 43 | } 44 | 45 | @Test 46 | fun `can remove a value`() = runTest { 47 | val cachemap = suspendCacheMapOf() 48 | 49 | cachemap.put("Hello", "World") 50 | val removed = cachemap.remove("Hello") 51 | val result = cachemap["Hello"] 52 | 53 | assertEquals("World", removed) 54 | assertEquals(null, result) 55 | } 56 | 57 | @Test 58 | fun `can remove an entry`() = runTest { 59 | val cachemap = suspendCacheMapOf() 60 | 61 | cachemap.put("Hello", "World") 62 | val removed = cachemap.remove("Hello", "World") 63 | val result = cachemap["Hello"] 64 | 65 | assertEquals(true, removed) 66 | assertEquals(null, result) 67 | } 68 | 69 | @Test 70 | fun `can clear the cachemap`() = runTest { 71 | val cachemap = suspendCacheMapOf() 72 | 73 | cachemap.put("Hello", "World") 74 | cachemap.put("Foo", "Bar") 75 | 76 | cachemap.clear() 77 | 78 | assertEquals(null, cachemap["Hello"]) 79 | assertEquals(null, cachemap["Foo"]) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /cachemap/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.dokka.gradle.DokkaTask 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | plugins { 5 | alias(libs.plugins.kotlin.multiplatform) 6 | alias(libs.plugins.kotlin.serialization) 7 | alias(libs.plugins.kotlin.atomic.fu) 8 | id("kmp-conventions") 9 | id("linting-conventions") 10 | id("publishing-conventions") 11 | } 12 | 13 | kotlin { 14 | 15 | sourceSets { 16 | 17 | commonMain { 18 | dependencies { 19 | implementation(projects.leftright) 20 | } 21 | } 22 | 23 | commonTest { 24 | dependencies { 25 | implementation(libs.kotlin.test) 26 | } 27 | } 28 | 29 | jvmMain { 30 | dependencies { 31 | 32 | } 33 | } 34 | } 35 | } 36 | 37 | configure { 38 | name = "cachemap" 39 | description = "A read optimised concurrent map for Kotlin Multiplatform" 40 | } 41 | 42 | tasks.withType().configureEach { 43 | kotlinOptions.jvmTarget = libs.versions.java.bytecode.version.get() 44 | } 45 | -------------------------------------------------------------------------------- /cachemap/src/commonMain/kotlin/io/github/charlietap/cachemap/CacheMap.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap 2 | 3 | interface CacheMap : Map { 4 | 5 | operator fun set(key: K, value: V) 6 | 7 | fun put(key: K, value: V) 8 | 9 | fun putAll(from: Map) 10 | 11 | fun remove(key: K): V? 12 | 13 | fun remove(key: K, value: V): Boolean 14 | 15 | fun clear() 16 | } 17 | 18 | fun cacheMapOf(): CacheMap { 19 | return InternalCacheMap() 20 | } 21 | 22 | fun cacheMapOf(vararg args: Pair): CacheMap { 23 | return InternalCacheMap(initialPopulation = args.toMap()) 24 | } 25 | 26 | fun cacheMapOf(readerParallelism: Int, initialCapacity: Int, initialPopulation: Map): CacheMap { 27 | return InternalCacheMap(readerParallelism, initialCapacity, initialPopulation) 28 | } 29 | -------------------------------------------------------------------------------- /cachemap/src/commonMain/kotlin/io/github/charlietap/cachemap/InternalCacheMap.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap 2 | 3 | import io.github.charlietap.leftright.LeftRight 4 | 5 | internal class InternalCacheMap( 6 | readerParallelism: Int? = null, 7 | initialCapacity: Int? = null, 8 | initialPopulation: Map? = null, 9 | ) : Map, CacheMap { 10 | 11 | private val inner = constructor( 12 | readerParallelism, 13 | initialCapacity, 14 | initialPopulation, 15 | ) 16 | 17 | override val entries: Set> 18 | get() = inner.read(MutableMap::entries) 19 | 20 | override val keys: Set 21 | get() = inner.read(MutableMap::keys) 22 | 23 | override val size: Int 24 | get() = inner.read(MutableMap::size) 25 | 26 | override val values: Collection 27 | get() = inner.read(MutableMap::values) 28 | 29 | override fun isEmpty(): Boolean = inner.read(MutableMap::isEmpty) 30 | 31 | override fun get(key: K): V? { 32 | return inner.read { map -> 33 | map[key] 34 | } 35 | } 36 | 37 | override fun containsKey(key: K): Boolean { 38 | return inner.read { map -> 39 | map.containsKey(key) 40 | } 41 | } 42 | 43 | override fun containsValue(value: V): Boolean { 44 | return inner.read { map -> 45 | map.containsValue(value) 46 | } 47 | } 48 | 49 | override fun put(key: K, value: V) { 50 | return inner.mutate { map -> 51 | map[key] = value 52 | } 53 | } 54 | 55 | override fun putAll(from: Map) { 56 | return inner.mutate { map -> 57 | from.forEach { (key, value) -> 58 | map[key] = value 59 | } 60 | } 61 | } 62 | 63 | override fun remove(key: K): V? { 64 | return inner.mutate { map -> 65 | map.remove(key) 66 | } 67 | } 68 | 69 | override fun remove(key: K, value: V): Boolean { 70 | return inner.mutate { map -> 71 | val mapValue = map[key] 72 | if (value == mapValue) { 73 | map.remove(key) 74 | true 75 | } else { 76 | false 77 | } 78 | } 79 | } 80 | 81 | override fun set(key: K, value: V) { 82 | return inner.mutate { map -> 83 | map[key] = value 84 | } 85 | } 86 | 87 | override fun clear() = inner.mutate(MutableMap::clear) 88 | 89 | companion object { 90 | fun constructor( 91 | readerParallelism: Int? = null, 92 | capacity: Int? = null, 93 | population: Map? = null, 94 | ): LeftRight> = if ( 95 | readerParallelism == null && capacity == null && population == null 96 | ) { 97 | LeftRight(::mutableMapOf) 98 | } else { 99 | val constructor = { 100 | if (capacity != null) { 101 | HashMap(capacity) 102 | } else if (population != null) { 103 | HashMap(population) 104 | } else { 105 | HashMap() 106 | } 107 | } 108 | if (readerParallelism != null) { 109 | LeftRight(constructor, readerParallelism) 110 | } else { 111 | LeftRight(constructor) 112 | } 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /cachemap/src/commonTest/kotlin/io/github/charlietap/cachemap/CacheMapTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.cachemap 2 | 3 | import kotlin.test.Test 4 | import kotlin.test.assertEquals 5 | 6 | class CacheMapTest { 7 | 8 | @Test 9 | fun `can prepopulate the map on construction`() { 10 | val cachemap = cacheMapOf( 11 | "Hello" to "World", 12 | "Foo" to "Bar", 13 | ) 14 | 15 | assertEquals("World", cachemap["Hello"]) 16 | assertEquals("Bar", cachemap["Foo"]) 17 | } 18 | 19 | @Test 20 | fun `can insert a value and retrieve it`() { 21 | val cachemap = cacheMapOf() 22 | 23 | cachemap.put("Hello", "World") 24 | val result = cachemap.get("Hello") 25 | 26 | assertEquals("World", result) 27 | } 28 | 29 | @Test 30 | fun `can insert a value and retrieve it using operator syntax`() { 31 | val cachemap = cacheMapOf() 32 | 33 | cachemap["Hello"] = "World" 34 | val result = cachemap["Hello"] 35 | 36 | assertEquals("World", result) 37 | } 38 | 39 | @Test 40 | fun `can insert multiple entries`() { 41 | val cachemap = cacheMapOf() 42 | 43 | val insertees = mapOf( 44 | "Hello" to "World", 45 | "Foo" to "Bar", 46 | ) 47 | 48 | cachemap.putAll(insertees) 49 | 50 | assertEquals("World", cachemap["Hello"]) 51 | assertEquals("Bar", cachemap["Foo"]) 52 | } 53 | 54 | @Test 55 | fun `can remove a value`() { 56 | val cachemap = cacheMapOf() 57 | 58 | cachemap["Hello"] = "World" 59 | val removed = cachemap.remove("Hello") 60 | val result = cachemap["Hello"] 61 | 62 | assertEquals("World", removed) 63 | assertEquals(null, result) 64 | } 65 | 66 | @Test 67 | fun `can remove an entry`() { 68 | val cachemap = cacheMapOf() 69 | 70 | cachemap["Hello"] = "World" 71 | val removed = cachemap.remove("Hello", "World") 72 | val result = cachemap["Hello"] 73 | 74 | assertEquals(true, removed) 75 | assertEquals(null, result) 76 | } 77 | 78 | @Test 79 | fun `can clear the cachemap`() { 80 | val cachemap = cacheMapOf() 81 | 82 | cachemap["Hello"] = "World" 83 | cachemap["Foo"] = "Bar" 84 | 85 | cachemap.clear() 86 | 87 | assertEquals(null, cachemap["Hello"]) 88 | assertEquals(null, cachemap["Foo"]) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.caching=true 2 | org.gradle.parallel=true 3 | org.gradle.configuration-cache=true 4 | org.gradle.jvmargs=-Xmx4096M -Dfile.encoding=UTF-8 5 | 6 | kotlin.code.style=official 7 | kotlin.mpp.stability.nowarn=true 8 | kotlin.mpp.enableCInteropCommonization=true 9 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | 3 | version-name = "0.2.4" 4 | 5 | java-compiler-version = "21" 6 | java-bytecode-version = "11" 7 | java-vendor = "amazon" 8 | 9 | android-build-tools-plugin = "8.0.0" 10 | versions-plugin = "0.47.0" 11 | 12 | androidx-collection = "1.3.0-alpha04" 13 | 14 | dependency-analysis="1.18.0" 15 | dokka="1.9.20" 16 | 17 | faker = "1.14.0" 18 | 19 | junit = "4.13.2" 20 | 21 | kotlin = "2.0.0" 22 | kotlinter = "4.1.0" 23 | kot-compile-testing = "1.5.0" 24 | 25 | kotlinx-atomic-fu = "0.23.1" 26 | kotlinx-benchmark = "0.4.11" 27 | kotlinx-coroutines = "1.7.3" 28 | kotlinx-datetime = "0.4.0" 29 | kotlinx-serialization = "1.5.1" 30 | 31 | [plugins] 32 | 33 | android = { id = "com.android.application", version.ref = "android-build-tools-plugin" } 34 | android-lib = { id = "com.android.library", version.ref = "android-build-tools-plugin" } 35 | android-test = { id = "com.android.test", version.ref = "android-build-tools-plugin" } 36 | dependency-analysis = { id = "com.autonomousapps.dependency-analysis", version.ref="dependency-analysis" } 37 | dokka = { id = "org.jetbrains.dokka", version.ref="dokka" } 38 | kotlin-allopen = { id = "org.jetbrains.kotlin.plugin.allopen", version.ref = "kotlin" } 39 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } 40 | kotlin-benchmark = { id = "org.jetbrains.kotlinx.benchmark", version.ref = "kotlinx-benchmark" } 41 | kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } 42 | kotlin-kapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlin" } 43 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } 44 | kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } 45 | kotlin-atomic-fu = { id = "org.jetbrains.kotlin.plugin.atomicfu", version.ref = "kotlin" } 46 | kotlinter = { id = "org.jmailen.kotlinter", version.ref = "kotlinter" } 47 | 48 | [libraries] 49 | 50 | androidx-collections-kmp = { module = "androidx.collection:collection", version.ref = "androidx-collection" } 51 | 52 | faker = { module = "io.github.serpro69:kotlin-faker", version.ref = "faker"} 53 | 54 | junit = { module = "junit:junit", version.ref = "junit"} 55 | 56 | kotlin-compile-testing-core = { module = "com.github.tschuchortdev:kotlin-compile-testing", version.ref = "kot-compile-testing"} 57 | kotlin-compile-testing-ksp = { module = "com.github.tschuchortdev:kotlin-compile-testing-ksp", version.ref = "kot-compile-testing"} 58 | kotlin-junit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin"} 59 | kotlin-reflection = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin"} 60 | kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin"} 61 | 62 | kotlinx-atomic-fu = { module = "org.jetbrains.kotlinx:atomicfu", version.ref = "kotlinx-atomic-fu"} 63 | kotlinx-benchmark = { module = "org.jetbrains.kotlinx:kotlinx-benchmark-runtime", version.ref = "kotlinx-benchmark"} 64 | kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinx-datetime"} 65 | kotlinx-serialization = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization"} 66 | kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines"} 67 | kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines"} 68 | kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines"} 69 | 70 | dokka-gradle-plugin = { module = "org.jetbrains.dokka:dokka-gradle-plugin", version.ref = "dokka" } 71 | gradle-versions-plugin = { module = "com.github.ben-manes:gradle-versions-plugin", version.ref = "versions-plugin" } 72 | kotlinter-gradle-plugin = { module = "org.jmailen.gradle:kotlinter-gradle", version.ref = "kotlinter" } 73 | kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } 74 | 75 | [bundles] 76 | -------------------------------------------------------------------------------- /gradle/plugins/kmp-conventions/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | } 4 | 5 | repositories { 6 | mavenCentral() 7 | gradlePluginPortal() 8 | google() 9 | } 10 | 11 | dependencies { 12 | implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location)) 13 | implementation(libs.kotlin.gradle.plugin) 14 | } 15 | 16 | kotlin { 17 | jvmToolchain { 18 | languageVersion.set(JavaLanguageVersion.of(libs.versions.java.compiler.version.get().toInt())) 19 | vendor.set(JvmVendorSpec.matching(libs.versions.java.vendor.get())) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /gradle/plugins/kmp-conventions/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | dependencyResolutionManagement { 2 | versionCatalogs { 3 | create("libs") { 4 | from(files("../../libs.versions.toml")) 5 | } 6 | } 7 | } 8 | 9 | rootProject.name = "kmp-conventions" 10 | -------------------------------------------------------------------------------- /gradle/plugins/kmp-conventions/src/main/kotlin/kmp-conventions.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.accessors.dm.LibrariesForLibs 2 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension 3 | 4 | plugins { 5 | id("org.jetbrains.kotlin.multiplatform") 6 | } 7 | 8 | val libs = the() 9 | 10 | fun KotlinMultiplatformExtension.unixTargets() = setOf( 11 | macosArm64(), 12 | macosX64(), 13 | iosArm64(), 14 | iosSimulatorArm64(), 15 | iosX64(), 16 | linuxArm64(), 17 | linuxX64(), 18 | ) 19 | 20 | fun KotlinMultiplatformExtension.nativeTargets() = setOf( 21 | mingwX64() 22 | ) + unixTargets() 23 | 24 | kotlin { 25 | 26 | jvm() 27 | nativeTargets() 28 | 29 | jvmToolchain { 30 | languageVersion.set(JavaLanguageVersion.of(libs.versions.java.compiler.version.get().toInt())) 31 | vendor.set(JvmVendorSpec.matching(libs.versions.java.vendor.get())) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /gradle/plugins/linting-conventions/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | } 4 | 5 | repositories { 6 | gradlePluginPortal() 7 | } 8 | 9 | dependencies { 10 | implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location)) 11 | implementation(libs.kotlinter.gradle.plugin) 12 | } 13 | 14 | kotlin { 15 | jvmToolchain { 16 | languageVersion.set(JavaLanguageVersion.of(libs.versions.java.compiler.version.get().toInt())) 17 | vendor.set(JvmVendorSpec.matching(libs.versions.java.vendor.get())) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /gradle/plugins/linting-conventions/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | dependencyResolutionManagement { 2 | versionCatalogs { 3 | create("libs") { 4 | from(files("../../libs.versions.toml")) 5 | } 6 | } 7 | } 8 | 9 | rootProject.name = "linting-conventions" 10 | -------------------------------------------------------------------------------- /gradle/plugins/linting-conventions/src/main/kotlin/linting-conventions.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jmailen.gradle.kotlinter.tasks.ConfigurableKtLintTask 2 | 3 | plugins { 4 | id("org.jmailen.kotlinter") 5 | } 6 | 7 | tasks.withType().configureEach { 8 | exclude { it.file.path.contains("build/")} 9 | } 10 | -------------------------------------------------------------------------------- /gradle/plugins/publishing-conventions/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | `java-gradle-plugin` 4 | } 5 | 6 | repositories { 7 | mavenCentral() 8 | gradlePluginPortal() 9 | google() 10 | } 11 | 12 | dependencies { 13 | implementation(gradleApi()) 14 | implementation(libs.dokka.gradle.plugin) 15 | } 16 | 17 | kotlin { 18 | jvmToolchain { 19 | languageVersion.set(JavaLanguageVersion.of(libs.versions.java.compiler.version.get().toInt())) 20 | vendor.set(JvmVendorSpec.matching(libs.versions.java.vendor.get())) 21 | } 22 | } 23 | 24 | gradlePlugin { 25 | plugins { 26 | create("publishingConventions") { 27 | id = "publishing-conventions" 28 | implementationClass = "PublishingConventionsPlugin" 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /gradle/plugins/publishing-conventions/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | dependencyResolutionManagement { 2 | versionCatalogs { 3 | create("libs") { 4 | from(files("../../libs.versions.toml")) 5 | } 6 | } 7 | } 8 | 9 | rootProject.name = "publishing-conventions" 10 | -------------------------------------------------------------------------------- /gradle/plugins/publishing-conventions/src/main/kotlin/PublishingConventionsExtension.kt: -------------------------------------------------------------------------------- 1 | import org.gradle.api.provider.Property 2 | 3 | interface PublishingConventionsExtension { 4 | val name: Property 5 | val description: Property 6 | } 7 | -------------------------------------------------------------------------------- /gradle/plugins/publishing-conventions/src/main/kotlin/PublishingConventionsPlugin.kt: -------------------------------------------------------------------------------- 1 | import org.gradle.api.Plugin 2 | import org.gradle.api.Project 3 | import org.gradle.api.artifacts.VersionCatalogsExtension 4 | import org.gradle.api.publish.PublicationContainer 5 | import org.gradle.api.publish.PublishingExtension 6 | import org.gradle.api.publish.maven.MavenPublication 7 | import org.gradle.api.publish.maven.plugins.MavenPublishPlugin 8 | import org.gradle.api.publish.maven.tasks.AbstractPublishToMaven 9 | import org.gradle.api.tasks.TaskProvider 10 | import org.jetbrains.dokka.gradle.DokkaTask 11 | import org.gradle.api.tasks.bundling.Jar 12 | import org.gradle.kotlin.dsl.create 13 | import org.gradle.kotlin.dsl.getByType 14 | import org.gradle.kotlin.dsl.getValue 15 | import org.gradle.kotlin.dsl.getting 16 | import org.gradle.kotlin.dsl.provideDelegate 17 | import org.gradle.kotlin.dsl.registering 18 | import org.gradle.kotlin.dsl.withType 19 | import org.gradle.plugins.signing.Sign 20 | import org.gradle.plugins.signing.SigningExtension 21 | import org.gradle.plugins.signing.SigningPlugin 22 | import org.jetbrains.dokka.gradle.DokkaPlugin 23 | 24 | class PublishingConventionsPlugin : Plugin { 25 | override fun apply(project: Project) { 26 | 27 | project.pluginManager.apply(DokkaPlugin::class.java) 28 | project.pluginManager.apply(MavenPublishPlugin::class.java) 29 | project.pluginManager.apply(SigningPlugin::class.java) 30 | 31 | val extension = project.extensions.create("publishing-convention-extension") 32 | 33 | project.group = "io.github.charlietap" 34 | project.version = project.extensions.getByType(VersionCatalogsExtension::class.java).find("libs").get().findVersion("version-name").get().requiredVersion 35 | 36 | val dokkaHtml by project.tasks.getting(DokkaTask::class) 37 | val javadocTask by project.tasks.registering(Jar::class) { 38 | dependsOn(dokkaHtml) 39 | archiveClassifier.set("javadoc") 40 | from(dokkaHtml.outputDirectory) 41 | } 42 | 43 | project.tasks.withType().configureEach { 44 | val signingTasks = project.tasks.withType() 45 | mustRunAfter(signingTasks) 46 | } 47 | 48 | project.tasks.withType().configureEach { 49 | notCompatibleWithConfigurationCache("https://github.com/Kotlin/dokka/issues/2231") 50 | } 51 | 52 | project.afterEvaluate { 53 | 54 | project.extensions.configure(PublishingExtension::class.java) { 55 | configurePublishing(project, javadocTask, extension) 56 | } 57 | 58 | project.extensions.configure(SigningExtension::class.java) { 59 | configureSigning(project, project.extensions.getByType().publications) 60 | } 61 | } 62 | } 63 | 64 | private fun PublishingExtension.configurePublishing(project: Project, javadocJar: TaskProvider, extension: PublishingConventionsExtension) { 65 | 66 | val manualFileRepo = project.uri("file://${project.rootProject.layout.buildDirectory.get()}/manual") 67 | 68 | repositories { 69 | maven { 70 | name = "manual" 71 | url = manualFileRepo 72 | } 73 | } 74 | 75 | publications.withType().configureEach { 76 | 77 | artifact(javadocJar) 78 | 79 | pom { 80 | name.set(extension.name) 81 | description.set(extension.description) 82 | url.set("https://github.com/CharlieTap/cachemap") 83 | licenses { 84 | license { 85 | name.set("Apache-2.0") 86 | url.set("https://www.apache.org/licenses/LICENSE-2.0") 87 | } 88 | license { 89 | name.set("MIT") 90 | url.set("https://opensource.org/licenses/MIT") 91 | } 92 | } 93 | developers { 94 | developer { 95 | id.set("CharlieTap") 96 | name.set("Charlie Tapping") 97 | } 98 | } 99 | scm { 100 | connection.set("scm:git:https://github.com/CharlieTap/cachemap.git") 101 | developerConnection.set("scm:git:ssh://github.com/CharlieTap/cachemap.git") 102 | url.set("https://github.com/CharlieTap/cachemap") 103 | } 104 | } 105 | } 106 | } 107 | 108 | private fun SigningExtension.configureSigning(project: Project, publications: PublicationContainer) { 109 | val signingKey: String? by project 110 | val signingPassword: String? by project 111 | 112 | if(signingKey != null) { 113 | useInMemoryPgpKeys(signingKey, signingPassword) 114 | } 115 | 116 | sign(publications) 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /gradle/plugins/versions-conventions/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | } 4 | 5 | repositories { 6 | mavenCentral() 7 | gradlePluginPortal() 8 | google() 9 | } 10 | 11 | dependencies { 12 | implementation(libs.gradle.versions.plugin) 13 | } 14 | 15 | kotlin { 16 | jvmToolchain { 17 | languageVersion.set(JavaLanguageVersion.of(libs.versions.java.compiler.version.get().toInt())) 18 | vendor.set(JvmVendorSpec.matching(libs.versions.java.vendor.get())) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /gradle/plugins/versions-conventions/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | dependencyResolutionManagement { 2 | versionCatalogs { 3 | create("libs") { 4 | from(files("../../libs.versions.toml")) 5 | } 6 | } 7 | } 8 | 9 | rootProject.name = "versions-conventions" -------------------------------------------------------------------------------- /gradle/plugins/versions-conventions/src/main/kotlin/versions-conventions.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask 2 | 3 | plugins { 4 | id("com.github.ben-manes.versions") 5 | } 6 | 7 | fun isNonStable(version: String): Boolean { 8 | val stableKeyword = listOf("RELEASE", "FINAL", "GA").any { version.uppercase().contains(it) } 9 | val regex = "^[0-9,.v-]+(-r)?$".toRegex() 10 | val isStable = stableKeyword || regex.matches(version) 11 | return isStable.not() 12 | } 13 | 14 | tasks.withType().configureEach { 15 | rejectVersionIf { 16 | isNonStable(this.candidate.version) && !isNonStable(this.currentVersion) 17 | } 18 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CharlieTap/cachemap/3971f3cfac87bb841d1fc9e4aa44d0e70bfa9167/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /leftright-shared/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.dokka.gradle.DokkaTask 2 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension 3 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 4 | 5 | plugins { 6 | alias(libs.plugins.kotlin.multiplatform) 7 | alias(libs.plugins.kotlin.serialization) 8 | alias(libs.plugins.kotlin.atomic.fu) 9 | id("kmp-conventions") 10 | id("linting-conventions") 11 | id("publishing-conventions") 12 | } 13 | 14 | fun KotlinMultiplatformExtension.unixTargets() = setOf( 15 | macosArm64(), 16 | macosX64(), 17 | iosArm64(), 18 | iosSimulatorArm64(), 19 | iosX64(), 20 | linuxArm64(), 21 | linuxX64(), 22 | ) 23 | 24 | fun KotlinMultiplatformExtension.nativeTargets() = setOf( 25 | mingwX64() 26 | ) + unixTargets() 27 | 28 | kotlin { 29 | 30 | nativeTargets().forEach { 31 | it.compilations.getByName("main") { 32 | cinterops { 33 | val libcounter by creating { 34 | defFile(project.file("src/ffi/cinterop/libcounter.def")) 35 | } 36 | } 37 | } 38 | } 39 | applyDefaultHierarchyTemplate() 40 | 41 | sourceSets { 42 | commonMain { 43 | dependencies {} 44 | } 45 | 46 | commonTest { 47 | dependencies { 48 | implementation(libs.kotlin.test) 49 | } 50 | } 51 | 52 | val unixMain by creating { 53 | dependsOn(commonMain.get()) 54 | } 55 | 56 | unixTargets().forEach { target -> 57 | target.compilations.getByName("main").defaultSourceSet { 58 | dependsOn(unixMain) 59 | } 60 | } 61 | } 62 | } 63 | 64 | configure { 65 | name = "leftright-shared" 66 | description = "A shared runtime library exposing a read optimised concurrency primitive for Kotlin Multiplatform" 67 | } 68 | 69 | tasks.withType().configureEach { 70 | kotlinOptions.jvmTarget = libs.versions.java.bytecode.version.get() 71 | } 72 | -------------------------------------------------------------------------------- /leftright-shared/src/commonMain/kotlin/io/github/charlietap/leftright/CacheAlignedCounter.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | interface CacheAlignedCounter { 4 | 5 | fun increment(): Int 6 | 7 | fun value(): Int 8 | } 9 | 10 | expect fun counter(initial: Int): CacheAlignedCounter 11 | -------------------------------------------------------------------------------- /leftright-shared/src/commonMain/kotlin/io/github/charlietap/leftright/CoreProvider.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | fun interface CoreProvider : () -> Int 4 | 5 | expect fun coreProvider(): CoreProvider 6 | -------------------------------------------------------------------------------- /leftright-shared/src/commonMain/kotlin/io/github/charlietap/leftright/ReadEpochIndex.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | interface ReadEpochIndex { 4 | fun value(): Int 5 | } 6 | 7 | expect fun readEpochIndex(initializer: () -> Int): ReadEpochIndex 8 | -------------------------------------------------------------------------------- /leftright-shared/src/commonMain/kotlin/io/github/charlietap/leftright/ReaderParallelism.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | fun readerParallelism(provider: CoreProvider = coreProvider()): Int = maxOf(64, 4 * provider()) 4 | -------------------------------------------------------------------------------- /leftright-shared/src/commonMain/kotlin/io/github/charlietap/leftright/Yield.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | expect fun yield() 4 | -------------------------------------------------------------------------------- /leftright-shared/src/commonTest/kotlin/io/github/charlietap/leftright/ReaderParallelismTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import kotlin.test.Test 4 | import kotlin.test.assertEquals 5 | 6 | class ReaderParallelismTest { 7 | 8 | @Test 9 | fun `core count multiplied by 4 is returned if larger than 64`() { 10 | val provider = CoreProvider { 17 } // * 4 = 68 11 | val result = readerParallelism(provider) 12 | 13 | assertEquals(68, result) 14 | } 15 | 16 | @Test 17 | fun `core count multiplied by 4 is not returned if less than 64`() { 18 | val provider = CoreProvider { 15 } // * 4 = 60 19 | val result = readerParallelism(provider) 20 | 21 | assertEquals(64, result) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /leftright-shared/src/ffi/cinterop/libcounter.def: -------------------------------------------------------------------------------- 1 | language = C 2 | package = libcounter 3 | --- 4 | #include 5 | 6 | #if defined(__x86_64__) || defined(__aarch64__) || defined(_ARCH_PPC64) 7 | #define CACHE_LINE_SIZE 128 8 | #elif defined(__arm__) || defined(__mips__) || defined(__mips64) || \ 9 | defined(__riscv) || defined(__sparc__) || defined(__hexagon__) 10 | #define CACHE_LINE_SIZE 32 11 | #elif defined(__m68k__) 12 | #define CACHE_LINE_SIZE 16 13 | #elif defined(__s390x__) 14 | #define CACHE_LINE_SIZE 256 15 | #else 16 | #define CACHE_LINE_SIZE 64 17 | #endif 18 | 19 | typedef struct { 20 | alignas(CACHE_LINE_SIZE) volatile int value; 21 | char padding[CACHE_LINE_SIZE - (sizeof(int) % CACHE_LINE_SIZE)]; 22 | } CacheAlignedInt; 23 | 24 | int increment_counter(CacheAlignedInt* counter) { 25 | counter->value += 1; 26 | return counter->value; 27 | } 28 | 29 | int get_counter_value(CacheAlignedInt* counter) { 30 | return counter->value; 31 | } 32 | -------------------------------------------------------------------------------- /leftright-shared/src/jvmMain/kotlin/io/github/charlietap/leftright/CacheAlignedCounter.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | class JvmCacheAlignedCounter(initialValue: Int) : CacheAlignedCounter { 4 | 5 | @Volatile private var p1: Long = 0 6 | 7 | @Volatile private var p2: Long = 0 8 | 9 | @Volatile private var p3: Long = 0 10 | 11 | @Volatile private var p4: Long = 0 12 | 13 | @Volatile private var p5: Long = 0 14 | 15 | @Volatile private var p6: Long = 0 16 | 17 | @Volatile private var p7: Long = 0 18 | 19 | @Volatile private var p8: Long = 0 20 | 21 | @Volatile private var p9: Long = 0 22 | 23 | @Volatile private var p10: Long = 0 24 | 25 | @Volatile private var p11: Long = 0 26 | 27 | @Volatile private var p12: Long = 0 28 | 29 | @Volatile private var p13: Long = 0 30 | 31 | @Volatile private var p14: Long = 0 32 | 33 | @Volatile var value: Int = initialValue 34 | 35 | override fun value(): Int { 36 | return value 37 | } 38 | 39 | override fun increment(): Int { 40 | value += 1 41 | return value 42 | } 43 | } 44 | 45 | actual fun counter(initial: Int): CacheAlignedCounter = JvmCacheAlignedCounter(initial) 46 | -------------------------------------------------------------------------------- /leftright-shared/src/jvmMain/kotlin/io/github/charlietap/leftright/CoreProvider.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | actual fun coreProvider() = CoreProvider { 4 | Runtime.getRuntime().availableProcessors() 5 | } 6 | -------------------------------------------------------------------------------- /leftright-shared/src/jvmMain/kotlin/io/github/charlietap/leftright/ReadEpochIndex.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | class JvmReadEpochIndex(initializer: () -> Int) : ReadEpochIndex { 4 | private val threadLocal = ThreadLocal.withInitial(initializer) 5 | 6 | override fun value(): Int = threadLocal.get() 7 | } 8 | 9 | actual fun readEpochIndex(initializer: () -> Int): ReadEpochIndex = JvmReadEpochIndex(initializer) 10 | -------------------------------------------------------------------------------- /leftright-shared/src/jvmMain/kotlin/io/github/charlietap/leftright/Yield.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | actual fun yield() = Thread.yield() 4 | -------------------------------------------------------------------------------- /leftright-shared/src/mingwMain/kotlin/io/github/charlietap/leftright/CoreProvider.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import kotlinx.cinterop.ExperimentalForeignApi 4 | import kotlinx.cinterop.alloc 5 | import kotlinx.cinterop.memScoped 6 | import kotlinx.cinterop.nativeHeap 7 | import kotlinx.cinterop.ptr 8 | import platform.windows.GetSystemInfo 9 | import platform.windows.SYSTEM_INFO 10 | 11 | @OptIn(ExperimentalForeignApi::class) 12 | actual fun coreProvider() = CoreProvider { 13 | memScoped { 14 | val systemInfo = nativeHeap.alloc() 15 | GetSystemInfo(systemInfo.ptr) 16 | systemInfo.dwNumberOfProcessors.toInt() 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /leftright-shared/src/nativeMain/kotlin/io/github/charlietap/leftright/CacheAlignedCounter.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import kotlinx.cinterop.ExperimentalForeignApi 4 | import kotlinx.cinterop.alloc 5 | import kotlinx.cinterop.nativeHeap 6 | import kotlinx.cinterop.ptr 7 | import libcounter.CacheAlignedInt 8 | import libcounter.get_counter_value 9 | import libcounter.increment_counter 10 | 11 | @OptIn(ExperimentalForeignApi::class) 12 | class NativeCacheAlignedCounter(initialValue: Int) : CacheAlignedCounter { 13 | 14 | private val counter = nativeHeap.alloc() 15 | 16 | init { 17 | counter.value = initialValue 18 | } 19 | 20 | override fun increment(): Int { 21 | return increment_counter(counter.ptr) 22 | } 23 | 24 | override fun value(): Int { 25 | return get_counter_value(counter.ptr) 26 | } 27 | 28 | fun free() { 29 | nativeHeap.free(counter.rawPtr) 30 | } 31 | } 32 | 33 | actual fun counter(initial: Int): CacheAlignedCounter = NativeCacheAlignedCounter(initial) 34 | -------------------------------------------------------------------------------- /leftright-shared/src/nativeMain/kotlin/io/github/charlietap/leftright/ReadEpochIndex.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import kotlin.native.concurrent.ThreadLocal 4 | 5 | @ThreadLocal 6 | private var idx: Int? = null 7 | 8 | private class NativeReadEpochIndex(val initializer: () -> Int) : ReadEpochIndex { 9 | init { 10 | idx = null 11 | } 12 | 13 | override fun value(): Int { 14 | if (idx == null) { 15 | idx = initializer() 16 | } 17 | return idx!! 18 | } 19 | } 20 | 21 | actual fun readEpochIndex(initializer: () -> Int): ReadEpochIndex { 22 | return NativeReadEpochIndex(initializer) 23 | } 24 | -------------------------------------------------------------------------------- /leftright-shared/src/nativeMain/kotlin/io/github/charlietap/leftright/Yield.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import platform.posix.sched_yield 4 | 5 | actual fun yield() { 6 | sched_yield() 7 | } 8 | -------------------------------------------------------------------------------- /leftright-shared/src/unixMain/kotlin/io/github/charlietap/leftright/CoreProvider.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import platform.posix._SC_NPROCESSORS_ONLN 4 | import platform.posix.sysconf 5 | 6 | actual fun coreProvider() = CoreProvider { 7 | sysconf(_SC_NPROCESSORS_ONLN).toInt() 8 | } 9 | -------------------------------------------------------------------------------- /leftright-suspend/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.dokka.gradle.DokkaTask 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | plugins { 5 | alias(libs.plugins.kotlin.multiplatform) 6 | alias(libs.plugins.kotlin.serialization) 7 | alias(libs.plugins.kotlin.atomic.fu) 8 | id("kmp-conventions") 9 | id("linting-conventions") 10 | id("publishing-conventions") 11 | } 12 | 13 | kotlin { 14 | 15 | sourceSets { 16 | 17 | commonMain { 18 | dependencies { 19 | api(projects.leftrightShared) 20 | api(libs.kotlinx.atomic.fu) 21 | api(libs.kotlinx.coroutines.core) 22 | } 23 | } 24 | 25 | commonTest { 26 | dependencies { 27 | implementation(libs.kotlin.test) 28 | implementation(libs.kotlinx.coroutines.test) 29 | } 30 | } 31 | 32 | jvmMain { 33 | dependencies { 34 | 35 | } 36 | } 37 | } 38 | } 39 | 40 | configure { 41 | name = "leftright-suspend" 42 | description = "A read optimised suspending concurrency primitive for Kotlin Multiplatform" 43 | } 44 | 45 | tasks.withType().configureEach { 46 | kotlinOptions.jvmTarget = libs.versions.java.bytecode.version.get() 47 | } 48 | -------------------------------------------------------------------------------- /leftright-suspend/src/commonMain/kotlin/io/github/charlietap/leftright/SuspendLeftRight.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import kotlinx.atomicfu.AtomicBoolean 4 | import kotlinx.atomicfu.AtomicInt 5 | import kotlinx.atomicfu.atomic 6 | import kotlinx.atomicfu.update 7 | import kotlinx.coroutines.sync.Mutex 8 | import kotlinx.coroutines.sync.withLock 9 | import kotlinx.coroutines.yield 10 | 11 | class SuspendLeftRight( 12 | constructor: () -> T, 13 | readerParallelism: Int = readerParallelism(), 14 | @PublishedApi internal val switch: AtomicBoolean = atomic(LEFT), 15 | internal val allEpochs: Array = Array(readerParallelism) { counter(0) }, 16 | internal val readEpochCount: AtomicInt = atomic(0), 17 | internal val readEpochIdx: ReadEpochIndex = readEpochIndex { readEpochCount.getAndIncrement() }, 18 | internal val left: T = constructor(), 19 | internal val right: T = constructor(), 20 | @PublishedApi internal val writeMutex: Mutex = Mutex(), 21 | ) { 22 | 23 | @PublishedApi 24 | internal val readEpoch get() = allEpochs[readEpochIdx.value()] 25 | 26 | @PublishedApi 27 | internal val readSide get() = if (switch.value == LEFT) left else right 28 | 29 | @PublishedApi 30 | internal val writeSide get() = if (switch.value == LEFT) right else left 31 | 32 | suspend inline fun mutate(crossinline update: (T) -> V): V { 33 | return writeMutex.withLock { 34 | update(writeSide) 35 | 36 | switch.update { !it } 37 | 38 | waitForReaders() 39 | 40 | update(writeSide) 41 | } 42 | } 43 | 44 | inline fun read(action: (T) -> V): V { 45 | readEpoch.increment() 46 | 47 | return action(readSide).also { 48 | readEpoch.increment() 49 | } 50 | } 51 | 52 | @PublishedApi 53 | internal suspend fun waitForReaders() { 54 | val activeThreads = readEpochCount.value 55 | 56 | // filter those that are odd because this signifies that they are mid-read 57 | // this is a little inefficient as it could also filter readers that are on the correct side but mid-read 58 | // Its unclear whether the computational effort of filtering these out would have any meaningful impact 59 | val activeIndices = (0 until activeThreads).fold(mutableListOf>()) { acc, idx -> 60 | val epoch = allEpochs[idx].value() 61 | acc.apply { 62 | if (epoch % 2 != 0) { 63 | acc.add(idx to epoch) 64 | } 65 | } 66 | } 67 | 68 | // wait for the epochs to change 69 | var iterations = 0 70 | 71 | while (activeIndices.size > 0) { 72 | if (iterations > 20) { 73 | iterations = 0 74 | yield() 75 | } else { 76 | activeIndices.removeAll { (allEpochsIdx, epoch) -> 77 | epoch != allEpochs[allEpochsIdx].value() 78 | } 79 | } 80 | 81 | iterations++ 82 | } 83 | } 84 | 85 | companion object { 86 | internal const val LEFT = true 87 | internal const val RIGHT = false 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /leftright-suspend/src/commonTest/kotlin/io/github/charlietap/leftright/SuspendLeftRightTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import io.github.charlietap.leftright.SuspendLeftRight.Companion.LEFT 4 | import io.github.charlietap.leftright.SuspendLeftRight.Companion.RIGHT 5 | import kotlinx.atomicfu.atomic 6 | import kotlinx.coroutines.async 7 | import kotlinx.coroutines.delay 8 | import kotlinx.coroutines.sync.Mutex 9 | import kotlinx.coroutines.test.runTest 10 | import kotlin.test.Test 11 | import kotlin.test.assertEquals 12 | import kotlin.test.assertSame 13 | 14 | class SuspendLeftRightTest { 15 | 16 | @Test 17 | fun `ensure thread local index local increments the total epoch count`() { 18 | val allEpochs = Array(1) { counter(0) } 19 | 20 | val totalEpochCount = atomic(0) 21 | 22 | val suspendLeftRight = SuspendLeftRight( 23 | constructor = { 0 }, 24 | allEpochs = allEpochs, 25 | readEpochCount = totalEpochCount, 26 | ) 27 | 28 | assertEquals(0, allEpochs[0].value()) 29 | assertEquals(0, totalEpochCount.value) // before idx access is zero 30 | assertEquals(0, suspendLeftRight.readEpochIdx.value()) // idx access 31 | assertEquals(1, totalEpochCount.value) // after idx access is incremented 32 | assertEquals(0, suspendLeftRight.readEpoch.value()) // ensure read epoch count is at zero 33 | } 34 | 35 | @Test 36 | fun `ensure a read increments the relevant epoch counter by 2`() { 37 | val expectedResult = 117 38 | val allEpochs = Array(1) { counter(0) } 39 | 40 | val suspendLeftRight = SuspendLeftRight( 41 | constructor = { expectedResult }, 42 | allEpochs = allEpochs, 43 | ) 44 | 45 | val result = suspendLeftRight.read { it } 46 | 47 | assertEquals(2, allEpochs[0].value()) 48 | assertEquals(expectedResult, result) 49 | } 50 | 51 | @Test 52 | fun `ensure a write updates the switch`() = runTest { 53 | val expectedResult = mutableSetOf(1, 2) 54 | val switch = atomic(LEFT) 55 | val allEpochs = Array(1) { counter(0) } 56 | 57 | val suspendLeftRight = SuspendLeftRight( 58 | constructor = { mutableSetOf(1) }, 59 | allEpochs = allEpochs, 60 | switch = switch, 61 | ) 62 | 63 | val readSide = suspendLeftRight.readSide 64 | val writeSide = suspendLeftRight.writeSide 65 | 66 | val result = suspendLeftRight.mutate { it.add(2) } 67 | 68 | assertEquals(true, result) 69 | assertEquals(0, allEpochs[0].value()) 70 | assertEquals(RIGHT, switch.value) // assert the switch changed 71 | assertSame(readSide, suspendLeftRight.writeSide) // assert the pointers have switched sides 72 | assertSame(writeSide, suspendLeftRight.readSide) // assert the pointers have switched sides 73 | assertEquals(expectedResult, suspendLeftRight.left) 74 | assertEquals(expectedResult, suspendLeftRight.right) 75 | } 76 | 77 | @Test 78 | fun `ensure only a single writer can access the write side`() = runTest { 79 | val writeMutex = Mutex() 80 | 81 | val suspendLeftRight = SuspendLeftRight( 82 | constructor = { mutableSetOf(1) }, 83 | writeMutex = writeMutex, 84 | ) 85 | 86 | writeMutex.lock() 87 | val routine = async { 88 | suspendLeftRight.mutate { 89 | it.add(2) 90 | } 91 | } 92 | delay(10) 93 | assertEquals(mutableSetOf(1), suspendLeftRight.readSide) 94 | assertEquals(mutableSetOf(1), suspendLeftRight.writeSide) 95 | writeMutex.unlock() 96 | routine.await() 97 | assertEquals(mutableSetOf(1, 2), suspendLeftRight.readSide) 98 | assertEquals(mutableSetOf(1, 2), suspendLeftRight.writeSide) 99 | } 100 | 101 | @Test 102 | fun `ensure reads proceeds whilst writes are taking place`() = runTest { 103 | val writeMutex = Mutex() 104 | 105 | val suspendLeftRight = SuspendLeftRight( 106 | constructor = { mutableSetOf(1) }, 107 | writeMutex = writeMutex, 108 | ) 109 | 110 | assertEquals(0, suspendLeftRight.readEpoch.value()) 111 | writeMutex.lock() 112 | val routine = async { 113 | suspendLeftRight.read { it } 114 | } 115 | val result = routine.await() 116 | assertEquals(mutableSetOf(1), result) 117 | assertEquals(2, suspendLeftRight.readEpoch.value()) // Note coroutines lets us run on the same thread 118 | writeMutex.unlock() 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /leftright/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.dokka.gradle.DokkaTask 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | plugins { 5 | alias(libs.plugins.kotlin.multiplatform) 6 | alias(libs.plugins.kotlin.serialization) 7 | alias(libs.plugins.kotlin.atomic.fu) 8 | id("kmp-conventions") 9 | id("linting-conventions") 10 | id("publishing-conventions") 11 | } 12 | 13 | kotlin { 14 | 15 | sourceSets { 16 | 17 | commonMain { 18 | dependencies { 19 | api(projects.leftrightShared) 20 | api(libs.kotlinx.atomic.fu) 21 | } 22 | } 23 | 24 | commonTest { 25 | dependencies { 26 | implementation(libs.kotlin.test) 27 | } 28 | } 29 | 30 | jvmMain { 31 | dependencies { 32 | 33 | } 34 | } 35 | 36 | nativeTest { 37 | languageSettings.optIn("kotlinx.cinterop.ExperimentalForeignApi") 38 | } 39 | } 40 | } 41 | 42 | configure { 43 | name = "leftright" 44 | description = "A read optimised concurrency primitive for Kotlin Multiplatform" 45 | } 46 | 47 | tasks.withType().configureEach { 48 | kotlinOptions.jvmTarget = libs.versions.java.bytecode.version.get() 49 | } 50 | -------------------------------------------------------------------------------- /leftright/src/commonMain/kotlin/io/github/charlietap/leftright/LeftRight.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import kotlinx.atomicfu.AtomicBoolean 4 | import kotlinx.atomicfu.AtomicInt 5 | import kotlinx.atomicfu.atomic 6 | import kotlinx.atomicfu.locks.ReentrantLock 7 | import kotlinx.atomicfu.locks.reentrantLock 8 | import kotlinx.atomicfu.locks.withLock 9 | import kotlinx.atomicfu.update 10 | 11 | class LeftRight( 12 | constructor: () -> T, 13 | readerParallelism: Int = readerParallelism(), 14 | @PublishedApi internal val switch: AtomicBoolean = atomic(LEFT), 15 | internal val allEpochs: Array = Array(readerParallelism) { counter(0) }, 16 | internal val readEpochCount: AtomicInt = atomic(0), 17 | internal val readEpochIdx: ReadEpochIndex = readEpochIndex { readEpochCount.getAndIncrement() }, 18 | internal val left: T = constructor(), 19 | internal val right: T = constructor(), 20 | @PublishedApi internal val writeMutex: ReentrantLock = reentrantLock(), 21 | ) { 22 | 23 | @PublishedApi 24 | internal val readEpoch get() = allEpochs[readEpochIdx.value()] 25 | 26 | @PublishedApi 27 | internal val readSide get() = if (switch.value == LEFT) left else right 28 | 29 | @PublishedApi 30 | internal val writeSide get() = if (switch.value == LEFT) right else left 31 | 32 | inline fun mutate(crossinline update: (T) -> V): V { 33 | return writeMutex.withLock { 34 | update(writeSide) 35 | 36 | switch.update { !it } 37 | 38 | waitForReaders() 39 | 40 | update(writeSide) 41 | } 42 | } 43 | 44 | inline fun read(action: (T) -> V): V { 45 | readEpoch.increment() 46 | 47 | return action(readSide).also { 48 | readEpoch.increment() 49 | } 50 | } 51 | 52 | @PublishedApi 53 | internal fun waitForReaders() { 54 | val activeThreads = readEpochCount.value 55 | 56 | // filter those that are odd because this signifies that they are mid-read 57 | // this is a little inefficient as it could also filter readers that are on the correct side but mid-read 58 | // Its unclear whether the computational effort of filtering these out would have any meaningful impact 59 | val activeIndices = (0 until activeThreads).fold(mutableListOf>()) { acc, idx -> 60 | val epoch = allEpochs[idx].value() 61 | acc.apply { 62 | if (epoch % 2 != 0) { 63 | acc.add(idx to epoch) 64 | } 65 | } 66 | } 67 | 68 | // wait for the epochs to change 69 | var iterations = 0 70 | 71 | while (activeIndices.size > 0) { 72 | if (iterations > 20) { 73 | iterations = 0 74 | yield() 75 | } else { 76 | activeIndices.removeAll { (allEpochsIdx, epoch) -> 77 | epoch != allEpochs[allEpochsIdx].value() 78 | } 79 | } 80 | 81 | iterations++ 82 | } 83 | } 84 | 85 | companion object { 86 | internal const val LEFT = true 87 | internal const val RIGHT = false 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /leftright/src/commonTest/kotlin/io/github/charlietap/leftright/LeftRightTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import io.github.charlietap.leftright.LeftRight.Companion.LEFT 4 | import io.github.charlietap.leftright.LeftRight.Companion.RIGHT 5 | import kotlinx.atomicfu.atomic 6 | import kotlin.test.Test 7 | import kotlin.test.assertEquals 8 | import kotlin.test.assertSame 9 | 10 | class LeftRightTest { 11 | 12 | @Test 13 | fun `ensure thread local index local increments the total epoch count`() { 14 | val allEpochs = Array(1) { counter(0) } 15 | 16 | val totalEpochCount = atomic(0) 17 | 18 | val leftRight = LeftRight( 19 | constructor = { 0 }, 20 | allEpochs = allEpochs, 21 | readEpochCount = totalEpochCount, 22 | ) 23 | 24 | assertEquals(0, allEpochs[0].value()) 25 | assertEquals(0, totalEpochCount.value) // before idx access is zero 26 | assertEquals(0, leftRight.readEpochIdx.value()) // idx access 27 | assertEquals(1, totalEpochCount.value) // after idx access is incremented 28 | assertEquals(0, leftRight.readEpoch.value()) // ensure read epoch count is at zero 29 | } 30 | 31 | @Test 32 | fun `ensure a read increments the relevant epoch counter by 2`() { 33 | val expectedResult = 117 34 | val allEpochs = Array(1) { counter(0) } 35 | 36 | val leftRight = LeftRight( 37 | constructor = { expectedResult }, 38 | allEpochs = allEpochs, 39 | ) 40 | 41 | val result = leftRight.read { it } 42 | 43 | assertEquals(2, allEpochs[0].value()) 44 | assertEquals(expectedResult, result) 45 | } 46 | 47 | @Test 48 | fun `ensure a write updates the switch`() { 49 | val expectedResult = mutableSetOf(1, 2) 50 | val switch = atomic(LEFT) 51 | val allEpochs = Array(1) { counter(0) } 52 | 53 | val leftRight = LeftRight( 54 | constructor = { mutableSetOf(1) }, 55 | allEpochs = allEpochs, 56 | switch = switch, 57 | ) 58 | 59 | val readSide = leftRight.readSide 60 | val writeSide = leftRight.writeSide 61 | 62 | val result = leftRight.mutate { it.add(2) } 63 | 64 | assertEquals(true, result) 65 | assertEquals(0, allEpochs[0].value()) 66 | assertEquals(RIGHT, switch.value) // assert the switch changed 67 | assertSame(readSide, leftRight.writeSide) // assert the pointers have switched sides 68 | assertSame(writeSide, leftRight.readSide) // assert the pointers have switched sides 69 | assertEquals(expectedResult, leftRight.left) 70 | assertEquals(expectedResult, leftRight.right) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /leftright/src/jvmTest/kotlin/io/github/charlietap/leftright/LeftRightTest.kt: -------------------------------------------------------------------------------- 1 | package io.github.charlietap.leftright 2 | 3 | import kotlinx.atomicfu.locks.ReentrantLock 4 | import kotlin.test.Test 5 | import kotlin.test.assertEquals 6 | 7 | class LeftRightJVMTest { 8 | 9 | @Test 10 | fun `ensure only a single writer can access the write side`() { 11 | val writeMutex = ReentrantLock() 12 | 13 | val leftRight = LeftRight( 14 | constructor = { mutableSetOf(1) }, 15 | writeMutex = writeMutex, 16 | ) 17 | 18 | writeMutex.lock() 19 | val routine = Thread { 20 | leftRight.mutate { 21 | it.add(2) 22 | } 23 | }.apply { 24 | start() 25 | } 26 | 27 | Thread.sleep(10) 28 | assertEquals(mutableSetOf(1), leftRight.readSide) 29 | assertEquals(mutableSetOf(1), leftRight.writeSide) 30 | writeMutex.unlock() 31 | routine.join() 32 | assertEquals(mutableSetOf(1, 2), leftRight.readSide) 33 | assertEquals(mutableSetOf(1, 2), leftRight.writeSide) 34 | } 35 | 36 | @Test 37 | fun `ensure reads proceeds whilst writes are taking place`() { 38 | val writeMutex = ReentrantLock() 39 | 40 | val leftRight = LeftRight( 41 | constructor = { mutableSetOf(1) }, 42 | writeMutex = writeMutex, 43 | ) 44 | 45 | assertEquals(0, leftRight.readEpoch.value()) 46 | writeMutex.lock() 47 | 48 | var result: MutableSet? = null 49 | var epoch = 0 50 | val routine = Thread { 51 | result = leftRight.read { it } 52 | epoch = leftRight.readEpoch.value() 53 | } 54 | routine.run { 55 | start() 56 | join() 57 | } 58 | assertEquals(mutableSetOf(1), result) 59 | assertEquals(0, leftRight.readEpoch.value()) // first threads epoch remains 60 | assertEquals(2, epoch) // spawned threads epoch increments 61 | writeMutex.unlock() 62 | } 63 | 64 | @Test 65 | fun `ensure reads increment separate counters`() { 66 | val writeMutex = ReentrantLock() 67 | 68 | val leftRight = LeftRight( 69 | constructor = { mutableSetOf(1) }, 70 | writeMutex = writeMutex, 71 | ) 72 | 73 | val routine1 = Thread { 74 | leftRight.read { 75 | it.first() 76 | } 77 | }.apply { 78 | start() 79 | } 80 | val routine2 = Thread { 81 | leftRight.read { 82 | it.first() 83 | } 84 | }.apply { 85 | start() 86 | } 87 | 88 | routine1.join() 89 | routine2.join() 90 | 91 | assertEquals(2, leftRight.allEpochs[0].value()) 92 | assertEquals(2, leftRight.allEpochs[1].value()) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /leftright/src/nativeTest/kotlin/io/github/charlietap/leftright/LeftRightTest.kt: -------------------------------------------------------------------------------- 1 | @file:OptIn(ExperimentalForeignApi::class) 2 | 3 | package io.github.charlietap.leftright 4 | 5 | import kotlinx.atomicfu.locks.reentrantLock 6 | import kotlinx.cinterop.ExperimentalForeignApi 7 | import kotlinx.cinterop.StableRef 8 | import kotlinx.cinterop.alloc 9 | import kotlinx.cinterop.asStableRef 10 | import kotlinx.cinterop.memScoped 11 | import kotlinx.cinterop.ptr 12 | import kotlinx.cinterop.staticCFunction 13 | import kotlinx.cinterop.value 14 | import platform.posix.PTHREAD_CREATE_JOINABLE 15 | import platform.posix.pthread_attr_destroy 16 | import platform.posix.pthread_attr_init 17 | import platform.posix.pthread_attr_setdetachstate 18 | import platform.posix.pthread_attr_t 19 | import platform.posix.pthread_create 20 | import platform.posix.pthread_join 21 | import platform.posix.pthread_tVar 22 | import platform.posix.sleep 23 | import kotlin.test.Test 24 | import kotlin.test.assertEquals 25 | 26 | class LeftRightNativeTest { 27 | 28 | private data class ThreadData( 29 | val leftRight: LeftRight>, 30 | var result: MutableSet? = null, 31 | var epoch: Int = 0, 32 | ) 33 | 34 | @Test 35 | fun `ensure only a single writer can access the write side`() { 36 | val writeMutex = reentrantLock() 37 | 38 | val leftRight = LeftRight( 39 | constructor = { mutableSetOf(1) }, 40 | writeMutex = writeMutex, 41 | ) 42 | 43 | writeMutex.lock() 44 | 45 | memScoped { 46 | val thread = alloc() 47 | val attr = alloc() 48 | pthread_attr_init(attr.ptr) 49 | pthread_attr_setdetachstate(attr.ptr, PTHREAD_CREATE_JOINABLE) 50 | 51 | pthread_create( 52 | thread.ptr, 53 | attr.ptr, 54 | staticCFunction { lp -> 55 | val lr = lp?.asStableRef>>()?.get() 56 | lr?.mutate { 57 | it.add(2) 58 | } 59 | null 60 | }, 61 | StableRef.create(leftRight).asCPointer(), 62 | ) 63 | 64 | sleep(1u) 65 | 66 | assertEquals(mutableSetOf(1), leftRight.readSide) 67 | assertEquals(mutableSetOf(1), leftRight.writeSide) 68 | 69 | writeMutex.unlock() 70 | 71 | pthread_join(thread.value, null) 72 | 73 | assertEquals(mutableSetOf(1, 2), leftRight.readSide) 74 | assertEquals(mutableSetOf(1, 2), leftRight.writeSide) 75 | 76 | pthread_attr_destroy(attr.ptr) 77 | } 78 | } 79 | 80 | @Test 81 | fun `ensure reads proceeds whilst writes are taking place`() { 82 | val writeMutex = reentrantLock() 83 | 84 | val leftRight = LeftRight( 85 | constructor = { mutableSetOf(1) }, 86 | writeMutex = writeMutex, 87 | ) 88 | 89 | val threadData = ThreadData( 90 | leftRight, 91 | ) 92 | 93 | assertEquals(0, leftRight.readEpoch.value()) 94 | writeMutex.lock() 95 | 96 | memScoped { 97 | val thread = alloc() 98 | val attr = alloc() 99 | pthread_attr_init(attr.ptr) 100 | pthread_attr_setdetachstate(attr.ptr, PTHREAD_CREATE_JOINABLE) 101 | 102 | pthread_create( 103 | thread.ptr, 104 | attr.ptr, 105 | staticCFunction { tdp -> 106 | val td = tdp?.asStableRef()?.get() 107 | 108 | td?.result = td?.leftRight?.read { it } 109 | td?.epoch = td?.leftRight?.readEpoch?.value() ?: 0 110 | null 111 | }, 112 | StableRef.create(threadData).asCPointer(), 113 | ) 114 | 115 | pthread_join(thread.value, null) 116 | pthread_attr_destroy(attr.ptr) 117 | } 118 | 119 | assertEquals(mutableSetOf(1), threadData.result) 120 | assertEquals(0, leftRight.readEpoch.value()) // first threads epoch remains 121 | assertEquals(2, threadData.epoch) // spawned threads epoch increments 122 | writeMutex.unlock() 123 | } 124 | 125 | @Test 126 | fun `ensure reads increment separate counters`() { 127 | val writeMutex = reentrantLock() 128 | 129 | val leftRight = LeftRight( 130 | constructor = { mutableSetOf(1) }, 131 | writeMutex = writeMutex, 132 | ) 133 | 134 | memScoped { 135 | val thread = alloc() 136 | val attr = alloc() 137 | pthread_attr_init(attr.ptr) 138 | pthread_attr_setdetachstate(attr.ptr, PTHREAD_CREATE_JOINABLE) 139 | 140 | pthread_create( 141 | thread.ptr, 142 | attr.ptr, 143 | staticCFunction { lp -> 144 | val lr = lp?.asStableRef>>()?.get() 145 | lr?.read { 146 | it.first() 147 | } 148 | null 149 | }, 150 | StableRef.create(leftRight).asCPointer(), 151 | ) 152 | pthread_join(thread.value, null) 153 | pthread_attr_destroy(attr.ptr) 154 | } 155 | 156 | memScoped { 157 | val thread = alloc() 158 | val attr = alloc() 159 | pthread_attr_init(attr.ptr) 160 | pthread_attr_setdetachstate(attr.ptr, PTHREAD_CREATE_JOINABLE) 161 | 162 | pthread_create( 163 | thread.ptr, 164 | attr.ptr, 165 | staticCFunction { lp -> 166 | val lr = lp?.asStableRef>>()?.get() 167 | lr?.read { 168 | it.first() 169 | } 170 | null 171 | }, 172 | StableRef.create(leftRight).asCPointer(), 173 | ) 174 | pthread_join(thread.value, null) 175 | pthread_attr_destroy(attr.ptr) 176 | } 177 | 178 | assertEquals(2, leftRight.allEpochs[0].value()) 179 | assertEquals(2, leftRight.allEpochs[1].value()) 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | google() 5 | mavenCentral() 6 | } 7 | 8 | includeBuild("gradle/plugins/kmp-conventions") 9 | includeBuild("gradle/plugins/linting-conventions") 10 | includeBuild("gradle/plugins/publishing-conventions") 11 | includeBuild("gradle/plugins/versions-conventions") 12 | } 13 | 14 | plugins { 15 | id("com.gradle.enterprise") version ("3.15.1") 16 | id("org.gradle.toolchains.foojay-resolver-convention") version("0.7.0") 17 | } 18 | 19 | gradleEnterprise { 20 | buildScan { 21 | termsOfServiceUrl = "https://gradle.com/terms-of-service" 22 | termsOfServiceAgree = "yes" 23 | 24 | publishAlwaysIf(!System.getenv("GITHUB_ACTIONS").isNullOrEmpty()) 25 | } 26 | } 27 | 28 | dependencyResolutionManagement { 29 | repositories { 30 | google() 31 | mavenCentral() 32 | mavenLocal() 33 | maven(url = "https://jitpack.io" ) 34 | 35 | } 36 | } 37 | 38 | include(":benchmark") 39 | include(":cachemap") 40 | include(":cachemap-suspend") 41 | include(":leftright") 42 | include(":leftright-shared") 43 | include(":leftright-suspend") 44 | 45 | rootProject.name = "cachemap-multiplatform" 46 | 47 | enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") 48 | --------------------------------------------------------------------------------