org.mentaqueue.wait.SpinYieldParkWaitStrategy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of menta-queue Show documentation
Show all versions of menta-queue Show documentation
A super fast inter-thread transfer queue.
The newest version!
/*
* MentaQueue => http://mentaqueue.soliveirajr.com Copyright (C) 2012 Sergio Oliveira Jr. ([email protected])
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.mentaqueue.wait;
import java.util.concurrent.locks.LockSupport;
/**
* This wait strategy first busy spinings, then yields, then sleep. You can configure each component by passing a spinCount and yieldCount.
* It optionally supports backing-off for the LockSupport.parkNanos method, increasing the sleep time by one nanosecond until the reset
* method is called.
*
* @author Sergio Oliveira Jr.
*/
public class SpinYieldParkWaitStrategy implements WaitStrategy {
private final static int DEFAULT_SPIN_COUNT = 10000;
private final static int DEFAULT_YIELD_COUNT = 1000;
private final static boolean DEFAULT_BACK_OFF = false;
private final int spinCount;
private final int yieldCount;
private final boolean parkBackOff;
private int count = 0;
private int sleepTime = 0;
public SpinYieldParkWaitStrategy(final int spinCount, final int yieldCount, final boolean parkBackOff) {
this.spinCount = spinCount;
this.yieldCount = yieldCount + spinCount;
this.parkBackOff = parkBackOff;
}
public SpinYieldParkWaitStrategy(final boolean parkBackOff) {
this(DEFAULT_SPIN_COUNT, DEFAULT_YIELD_COUNT, parkBackOff);
}
public SpinYieldParkWaitStrategy(final int spinCount, final int yieldCount) {
this(spinCount, yieldCount, DEFAULT_BACK_OFF);
}
public SpinYieldParkWaitStrategy() {
this(DEFAULT_SPIN_COUNT, DEFAULT_YIELD_COUNT, DEFAULT_BACK_OFF);
}
@Override
public final void waitForOtherThread() {
if (count < spinCount) {
count++;
} else if (count < yieldCount) {
Thread.yield();
count++;
} else {
if (parkBackOff) {
LockSupport.parkNanos(++sleepTime);
} else {
LockSupport.parkNanos(1L);
}
}
}
@Override
public final void reset() {
count = 0;
sleepTime = 0;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy