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

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

/**
 * 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;
    }
	
	
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy