UsagesCounter implementation on java

This commit is contained in:
Andrew Golovashevich 2025-08-24 00:43:25 +03:00
parent ed06e6c2a0
commit c30c585f76
5 changed files with 82 additions and 2 deletions

View File

@ -38,6 +38,7 @@ xomrk {
compilations.configureEach { compilations.configureEach {
compileJavaTaskProvider?.configure { compileJavaTaskProvider?.configure {
targetCompatibility = "1.8" targetCompatibility = "1.8"
sourceCompatibility = "1.8"
} }
compileTaskProvider.configure { compileTaskProvider.configure {
compilerOptions { compilerOptions {

View File

@ -1,10 +1,10 @@
package ru.landgrafhomyak.utility.closeable_state_1 package ru.landgrafhomyak.utility.closeable_state_1
public interface CloseableState { public interface CloseableState {
public fun assertNotClosed()
public val isClosed: Boolean public val isClosed: Boolean
public fun assertNotClosed()
@ManualStateManipulation @ManualStateManipulation
public fun startUsage() public fun startUsage()

View File

@ -0,0 +1,66 @@
package ru.landgrafhomyak.utility.closeable_state_1;
import ru.landgrafhomyak.utility.closeable_state_1.internal.Misc;
import java.util.concurrent.atomic.AtomicLong;
public class jUsagesCounter extends jUsagesCounter$Errors implements CloseableState.AllowsConcurrency {
private final AtomicLong _referencesCounter;
public jUsagesCounter() {
this._referencesCounter = new AtomicLong(0);
}
@Override
public boolean isClosed() {
return this._referencesCounter.get() < 0;
}
@Override
public void assertNotClosed() {
if (this._referencesCounter.get() < 0)
this.throwClosed();
}
@Override
public void startUsage() {
while (true) {
final long cur = this._referencesCounter.get();
if (cur < 0) {
this.throwClosed();
return;
}
if (this._referencesCounter.compareAndSet(cur, cur + 1))
return;
}
}
@Override
public void finishUsage() {
while (true) {
final long cur = this._referencesCounter.get();
if (cur < 0) {
this.throwClosed();
return;
}
if (this._referencesCounter.compareAndSet(cur, cur - 1))
return;
}
}
@Override
public void close() {
long currentReferencesCount;
while (true) {
currentReferencesCount = this._referencesCounter.get();
if (currentReferencesCount != 0) break;
if (this._referencesCounter.compareAndSet(currentReferencesCount, Misc.CLOSED_STATE_VALUE))
break;
}
if (currentReferencesCount > 0) this.throwInUse();
if (currentReferencesCount < 0) this.throwClosed();
}
}

View File

@ -0,0 +1,13 @@
package ru.landgrafhomyak.utility.closeable_state_1
import kotlin.IllegalStateException
internal abstract class `jUsagesCounter$Errors` {
protected open fun throwClosed(): Nothing {
throw IllegalStateException("Object is closed")
}
protected open fun throwInUse(): Nothing {
throw IllegalStateException("Failed close object because it is in use")
}
}