-
Notifications
You must be signed in to change notification settings - Fork 40
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[util] add RWSpinLock and upgrade ObjectPool
- Loading branch information
Showing
7 changed files
with
315 additions
and
64 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
base/src/main/java/io/vproxy/base/util/lock/ReadWriteSpinLock.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package io.vproxy.base.util.lock; | ||
|
||
import java.util.concurrent.atomic.AtomicInteger; | ||
|
||
public class ReadWriteSpinLock { | ||
private static final int WRITE_LOCKED = 0x80_00_00_00; | ||
// 32 31 ------ 0 | ||
// W RRRR...RRRR | ||
private final AtomicInteger lock = new AtomicInteger(0); | ||
private final AtomicInteger wLockPending = new AtomicInteger(0); | ||
private final int spinTimes; | ||
|
||
public ReadWriteSpinLock() { | ||
this(20); | ||
} | ||
|
||
public ReadWriteSpinLock(int spinTimes) { | ||
this.spinTimes = spinTimes; | ||
} | ||
|
||
public void readLock() { | ||
while (true) { | ||
if (wLockPending.get() != 0) { | ||
spinWait(); | ||
continue; | ||
} | ||
if (lock.incrementAndGet() < 0) { | ||
continue; | ||
} | ||
break; | ||
} | ||
} | ||
|
||
public void readUnlock() { | ||
lock.decrementAndGet(); | ||
} | ||
|
||
public void writeLock() { | ||
wLockPending.incrementAndGet(); | ||
while (!lock.compareAndSet(0, WRITE_LOCKED)) { | ||
spinWait(); | ||
} | ||
} | ||
|
||
public void writeUnlock() { | ||
lock.set(0); | ||
wLockPending.decrementAndGet(); | ||
} | ||
|
||
private void spinWait() { | ||
for (int i = 0; i < spinTimes; ++i) { | ||
Thread.onSpinWait(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.