Code example for Semaphore

Methods: release, tryAcquire

0
	private Semaphore sem = new Semaphore(MAX_NUMBER_OF_PERMITS, true);
 
	public Resource getMyResource(long maxWaitMillis) throws InterruptedException, ResourceCreateException {
 
		// try acquiring a permission to take or create MyResource 
		sem.tryAcquire(maxWaitMillis, TimeUnit.MILLISECONDS);
 
		// take MyResource if available... 
		Resource MyResource = resources.poll();
		if (MyResource != null) {
			return MyResource;
		} 
 
		// ... or create one if no available 
		try { 
			return createResource(); 
		} catch (Exception exc) {
			sem.release();
			throw new ResourceCreateException(); 
		} 
	} 
 
	private Resource createResource() {