2019-01-11 12:07:56 +00:00
|
|
|
/*
|
|
|
|
* This file is part of ComputerCraft - http://www.computercraft.info
|
2021-01-06 17:13:40 +00:00
|
|
|
* Copyright Daniel Ratcliffe, 2011-2021. Do not distribute without permission.
|
2019-01-11 12:07:56 +00:00
|
|
|
* Send enquiries to dratcliffe@gmail.com
|
|
|
|
*/
|
|
|
|
package dan200.computercraft.core.apis.http;
|
|
|
|
|
|
|
|
import java.util.Collections;
|
|
|
|
import java.util.Set;
|
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
import java.util.function.IntSupplier;
|
|
|
|
import java.util.function.Supplier;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A collection of {@link Resource}s, with an upper bound on capacity.
|
2019-10-27 15:16:47 +00:00
|
|
|
*
|
|
|
|
* @param <T> The type of the resource this group manages.
|
2019-01-11 12:07:56 +00:00
|
|
|
*/
|
|
|
|
public class ResourceGroup<T extends Resource<T>>
|
|
|
|
{
|
|
|
|
private static final IntSupplier ZERO = () -> 0;
|
|
|
|
|
|
|
|
final IntSupplier limit;
|
|
|
|
|
|
|
|
boolean active = false;
|
|
|
|
|
|
|
|
final Set<T> resources = Collections.newSetFromMap( new ConcurrentHashMap<>() );
|
|
|
|
|
|
|
|
public ResourceGroup( IntSupplier limit )
|
|
|
|
{
|
|
|
|
this.limit = limit;
|
|
|
|
}
|
|
|
|
|
|
|
|
public ResourceGroup()
|
|
|
|
{
|
2019-03-29 21:21:39 +00:00
|
|
|
limit = ZERO;
|
2019-01-11 12:07:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public void startup()
|
|
|
|
{
|
|
|
|
active = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public synchronized void shutdown()
|
|
|
|
{
|
|
|
|
active = false;
|
|
|
|
|
|
|
|
for( T resource : resources ) resource.close();
|
|
|
|
resources.clear();
|
|
|
|
|
|
|
|
Resource.cleanup();
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public final boolean queue( T resource, Runnable setup )
|
|
|
|
{
|
|
|
|
return queue( () -> {
|
|
|
|
setup.run();
|
|
|
|
return resource;
|
|
|
|
} );
|
|
|
|
}
|
|
|
|
|
|
|
|
public synchronized boolean queue( Supplier<T> resource )
|
|
|
|
{
|
|
|
|
Resource.cleanup();
|
|
|
|
if( !active ) return false;
|
|
|
|
|
|
|
|
int limit = this.limit.getAsInt();
|
|
|
|
if( limit <= 0 || resources.size() < limit )
|
|
|
|
{
|
|
|
|
resources.add( resource.get() );
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
public synchronized void release( T resource )
|
|
|
|
{
|
|
|
|
resources.remove( resource );
|
|
|
|
}
|
|
|
|
}
|