org.mentaqueue.wait.ParkWaitStrategy 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.
/*
* 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;
/**
* A wait strategy that uses the LockSupport.parkNanos method with some optional backing-off functionality. If backing-off is turned on, the sleepTime will gradually increase
* by one nanosecond until the strategy is reset.
*
* @author Sergio Oliveira Jr.
*/
public class ParkWaitStrategy implements WaitStrategy {
private final static boolean DEFAULT_BACK_OFF = false;
private final boolean parkBackOff;
private int sleepTime = 0;
public ParkWaitStrategy(boolean parkBackOff) {
this.parkBackOff = parkBackOff;
}
public ParkWaitStrategy() {
this(DEFAULT_BACK_OFF);
}
@Override
public final void waitForOtherThread() {
if (parkBackOff) {
LockSupport.parkNanos(++sleepTime);
} else {
LockSupport.parkNanos(1);
}
}
@Override
public final void reset() {
sleepTime = 0;
}
}