1 /*
2 * Copyright 2017-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
5 package kotlinx.atomicfu
6
7 import java.util.concurrent.locks.ReentrantLock
8
9 internal var interceptor: AtomicOperationInterceptor = DefaultInterceptor
10 private set
11 private val interceptorLock = ReentrantLock()
12
lockAndSetInterceptornull13 internal fun lockAndSetInterceptor(impl: AtomicOperationInterceptor) {
14 if (!interceptorLock.tryLock() || interceptor !== DefaultInterceptor) {
15 error("Interceptor is locked by another test: $interceptor")
16 }
17 interceptor = impl
18 }
19
unlockAndResetInterceptornull20 internal fun unlockAndResetInterceptor(impl: AtomicOperationInterceptor) {
21 check(interceptor === impl) { "Unexpected interceptor found: $interceptor" }
22 interceptor = DefaultInterceptor
23 interceptorLock.unlock()
24 }
25
26 /**
27 * Interceptor for modifications of atomic variables.
28 */
29 internal open class AtomicOperationInterceptor {
beforeUpdatenull30 open fun <T> beforeUpdate(ref: AtomicRef<T>) {}
beforeUpdatenull31 open fun beforeUpdate(ref: AtomicInt) {}
beforeUpdatenull32 open fun beforeUpdate(ref: AtomicLong) {}
beforeUpdatenull33 open fun beforeUpdate(ref: AtomicBoolean){}
afterSetnull34 open fun <T> afterSet(ref: AtomicRef<T>, newValue: T) {}
afterSetnull35 open fun afterSet(ref: AtomicInt, newValue: Int) {}
afterSetnull36 open fun afterSet(ref: AtomicLong, newValue: Long) {}
afterSetnull37 open fun afterSet(ref: AtomicBoolean, newValue: Boolean) {}
afterRMWnull38 open fun <T> afterRMW(ref: AtomicRef<T>, oldValue: T, newValue: T) {}
afterRMWnull39 open fun afterRMW(ref: AtomicInt, oldValue: Int, newValue: Int) {}
afterRMWnull40 open fun afterRMW(ref: AtomicLong, oldValue: Long, newValue: Long) {}
afterRMWnull41 open fun afterRMW(ref: AtomicBoolean, oldValue: Boolean, newValue: Boolean) {}
42 }
43
44 private object DefaultInterceptor : AtomicOperationInterceptor() {
toStringnull45 override fun toString(): String = "DefaultInterceptor"
46 }
47