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

org.mentaqueue.wait.YieldParkWaitStrategy 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;

/**
 * No busy spinning, just yield and sleep. You can configure how many iteration to yield before sleeping. Supporing backing-off
 * functionality, in other words, if turned on, the sleeping time will increase by one nanosecond gradually until reset is called.
 * 
 * @author Sergio Oliveira Jr.
 */
public class YieldParkWaitStrategy implements WaitStrategy {

	private final static int DEFAULT_YIELD_COUNT = 1000;
	private final static boolean DEFAULT_BACK_OFF = false;

	private final int yieldCount;
	private final boolean parkBackOff;

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

	public YieldParkWaitStrategy(final int yieldCount, final boolean parkBackOff) {
		this.yieldCount = yieldCount;
		this.parkBackOff = parkBackOff;
	}

	public YieldParkWaitStrategy(final int yieldCount) {
		this(yieldCount, DEFAULT_BACK_OFF);
	}

	public YieldParkWaitStrategy(final boolean parkBackOff) {
		this(DEFAULT_YIELD_COUNT, parkBackOff);
	}

	public YieldParkWaitStrategy() {
		this(DEFAULT_YIELD_COUNT, DEFAULT_BACK_OFF);
	}

	@Override
	public final void waitForOtherThread() {

		if (count < yieldCount) {
			Thread.yield();
			count++;
		} else {
			if (parkBackOff) {
				LockSupport.parkNanos(++sleepTime);
			} else {
				LockSupport.parkNanos(1);
			}
		}
	}

	@Override
	public final void reset() {
		count = 0;
		sleepTime = 0;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy