All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mentaqueue.wait.SpinParkWaitStrategy Maven / Gradle / Ivy

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-spins then parks with backing off if enabled.
 * 
 * @author Sergio Oliveira Jr.
 */
public class SpinParkWaitStrategy implements WaitStrategy {

	private final static int DEFAULT_SPIN_COUNT = 10000;
	private final static boolean DEFAULT_BACK_OFF = false;

	private final int spinCount;
	private final boolean parkBackOff;

	private int count = 0;
	private int sleepTime = 0;

	public SpinParkWaitStrategy(final int spinCount, final boolean parkBackOff) {
		this.spinCount = spinCount;
		this.parkBackOff = parkBackOff;
	}

	public SpinParkWaitStrategy(final boolean parkBackOff) {
		this(DEFAULT_SPIN_COUNT, parkBackOff);
	}

	public SpinParkWaitStrategy(final int spinCount) {
		this(spinCount, DEFAULT_BACK_OFF);
	}

	public SpinParkWaitStrategy() {
		this(DEFAULT_SPIN_COUNT, DEFAULT_BACK_OFF);
	}

	@Override
	public final void waitForOtherThread() {

		if (count < spinCount) {

			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