1 package org.apache.maven.surefire.junitcore.pc; 2 3 /* 4 * Licensed to the Apache Software Foundation (ASF) under one 5 * or more contributor license agreements. See the NOTICE file 6 * distributed with this work for additional information 7 * regarding copyright ownership. The ASF licenses this file 8 * to you under the Apache License, Version 2.0 (the 9 * "License"); you may not use this file except in compliance 10 * with the License. You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, 15 * software distributed under the License is distributed on an 16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 * KIND, either express or implied. See the License for the 18 * specific language governing permissions and limitations 19 * under the License. 20 */ 21 22 import java.util.concurrent.Semaphore; 23 24 /** 25 * @author Tibor Digana (tibor17) 26 * @since 2.16 27 * 28 * @see Balancer 29 */ 30 final class ThreadResourcesBalancer implements Balancer 31 { 32 private final Semaphore balancer; 33 private final int numPermits; 34 35 /** 36 * <tt>fair</tt> set to false. 37 * 38 * @param numPermits number of permits to acquire when maintaining concurrency on tests. 39 * Must be >0 and < {@link Integer#MAX_VALUE}. 40 * 41 * @see #ThreadResourcesBalancer(int, boolean) 42 */ 43 ThreadResourcesBalancer( int numPermits ) 44 { 45 this( numPermits, false ); 46 } 47 48 /** 49 * @param numPermits number of permits to acquire when maintaining concurrency on tests. 50 * Must be >0 and < {@link Integer#MAX_VALUE}. 51 * @param fair <tt>true</tt> guarantees the waiting schedulers to wake up in order they acquired a permit 52 */ 53 ThreadResourcesBalancer( int numPermits, boolean fair ) 54 { 55 balancer = new Semaphore( numPermits, fair ); 56 this.numPermits = numPermits; 57 } 58 59 /** 60 * Acquires a permit from this balancer, blocking until one is available. 61 * 62 * @return <code>true</code> if current thread is <em>NOT</em> interrupted 63 * while waiting for a permit. 64 */ 65 public boolean acquirePermit() 66 { 67 try 68 { 69 balancer.acquire(); 70 return true; 71 } 72 catch ( InterruptedException e ) 73 { 74 return false; 75 } 76 } 77 78 /** 79 * Releases a permit, returning it to the balancer. 80 */ 81 public void releasePermit() 82 { 83 balancer.release(); 84 } 85 86 public void releaseAllPermits() 87 { 88 balancer.release( numPermits ); 89 } 90 }