use of java.util.concurrent.CopyOnWriteArrayList in project tomee by apache.
the class PoolTest method testIdleTimeout.
/**
* Tests the idle timeout as well as the Thread pool
* used to invoke the discard/create jobs.
*
* @throws Exception exception
*/
public void testIdleTimeout() throws Exception {
System.out.println("PoolTest.testIdleTimeout");
final int min = 4;
final int max = 9;
final int idleTimeout = 1000;
final int sweepInterval = idleTimeout / 4;
final List<Bean> discarded = new CopyOnWriteArrayList<Bean>();
final CountDownLatch discard = new CountDownLatch(max - min);
final CountDownLatch hold = new CountDownLatch(1);
final Pool.Builder<Bean> builder = new Pool.Builder<Bean>();
builder.setMinSize(min);
builder.setMaxSize(max);
builder.setExecutor(Executors.newFixedThreadPool(5));
builder.setIdleTimeout(new Duration(idleTimeout, TimeUnit.MILLISECONDS));
builder.setSweepInterval(new Duration(sweepInterval, TimeUnit.MILLISECONDS));
builder.setSupplier(new Pool.Supplier<Bean>() {
public void discard(final Bean bean, final Pool.Event reason) {
bean.discard();
discarded.add(bean);
discard.countDown();
try {
// Executor should have enough threads
// to execute removes on all the
// timed out objects.
hold.await();
} catch (final InterruptedException e) {
Thread.interrupted();
}
}
public Bean create() {
// Should never be called
return new Bean();
}
});
final Pool pool = this.pool = builder.build().start();
// Fill pool to max
Bean.instances.set(0);
for (int i = 0; i < max; i++) {
assertTrue(pool.add(new Bean()));
}
{
// Should have a full, non-null pool
final List entries = drain(pool, 100);
checkMin(min, entries);
checkEntries(max, entries);
// Wait for the timeout -- items should not expire while in use
Thread.sleep((long) (idleTimeout * 1.2));
push(pool, entries);
}
await(discard, 20, TimeUnit.SECONDS);
// All non-min instances should have been removed
// no more, no less
assertEquals(max - min, discarded.size());
for (final Bean bean : discarded) {
final long inactive = bean.discarded - bean.accessed;
// Actual idle time should not be less than our setting
assertTrue("timed out too soon: timeout=" + idleTimeout + ", idle=" + inactive, inactive >= idleTimeout);
// It shouldn't be too much more either
assertTrue("timed out too long", inactive < idleTimeout + (sweepInterval * 2));
}
{
// Pool should only have min number of non-null entries
final List entries = drain(pool, 100);
checkMin(min, entries);
checkEntries(min, entries);
push(pool, entries);
}
// -- DONE --
assertEquals(max, Bean.instances.get());
}
use of java.util.concurrent.CopyOnWriteArrayList in project tomee by apache.
the class PoolTest method testClose.
public void testClose() throws Exception {
System.out.println("PoolTest.testClose");
final int min = 4;
final int max = 9;
final int sweepInterval = 200;
final int pause = 1000;
final List<Bean> discarded = new CopyOnWriteArrayList<Bean>();
final CountDownLatch discard = new CountDownLatch(max);
final Pool.Builder builder = new Pool.Builder();
builder.setMinSize(min);
builder.setMaxSize(max);
builder.setSweepInterval(new Duration(sweepInterval, TimeUnit.MILLISECONDS));
builder.setSupplier(new Pool.Supplier<Bean>() {
public void discard(final Bean bean, final Pool.Event reason) {
try {
Thread.sleep(pause);
} catch (final InterruptedException e) {
Thread.interrupted();
}
bean.discard();
discarded.add(bean);
discard.countDown();
}
public Bean create() {
return new Bean();
}
});
final Pool pool = this.pool = builder.build().start();
// Fill pool to max
Bean.instances.set(0);
for (int i = 0; i < max; i++) {
assertTrue(pool.add(new Bean()));
}
{
// Should have a full, non-null pool
final List entries = drain(pool, 100);
checkMin(min, entries);
checkEntries(max, entries);
push(pool, entries);
}
final long start = System.currentTimeMillis();
assertTrue(pool.close(10, TimeUnit.SECONDS));
final long time = System.currentTimeMillis() - start;
// All instances should have been removed
assertEquals(max, discarded.size());
// Should have taken at least three seconds
assertTrue(time >= pause);
}
use of java.util.concurrent.CopyOnWriteArrayList in project tomee by apache.
the class PoolTest method testMaxAge.
public void testMaxAge() throws Exception {
System.out.println("PoolTest.testMaxAge");
final int min = 4;
final int max = 9;
final int maxAge = 1000;
final int sweepInterval = maxAge / 4;
final List<Bean> discarded = new CopyOnWriteArrayList<Bean>();
final CountDownLatch discard = new CountDownLatch(max);
final CountDownLatch created = new CountDownLatch(min);
final CountDownLatch createInstances = new CountDownLatch(1);
final Pool.Builder builder = new Pool.Builder();
builder.setMinSize(min);
builder.setMaxSize(max);
builder.setMaxAge(new Duration(maxAge, MILLISECONDS));
builder.setSweepInterval(new Duration(sweepInterval, MILLISECONDS));
builder.setSupplier(new Pool.Supplier<Bean>() {
public void discard(final Bean bean, final Pool.Event reason) {
bean.discard();
discarded.add(bean);
countDown(discard, bean, "discarded");
}
public Bean create() {
try {
createInstances.await();
} catch (final InterruptedException e) {
Thread.interrupted();
}
try {
return new Bean();
} finally {
created.countDown();
}
}
});
final Pool pool = this.pool = builder.build().start();
// Fill pool to max
Bean.instances.set(0);
for (int i = 0; i < max; i++) {
assertTrue(pool.add(new Bean()));
}
{
// Should have a full, non-null pool
final List entries = drain(pool, 100);
checkMin(min, entries);
checkEntries(max, entries);
push(pool, entries);
}
// Now wait for the instances in the pool to expire
await(discard, 10, TimeUnit.SECONDS);
// All instances should have been removed
assertEquals(max, discarded.size());
for (final Bean bean : discarded) {
final long age = bean.discarded - bean.created;
// Actual idle time should not be less than our setting
assertTrue("died too soon", age >= maxAge);
// It shouldn't be too much more either
assertTrue("lived too long", age < maxAge + (sweepInterval * 2));
}
// Minimum instances are still being created
// The rest of the pool should be empty (null)
{
final List entries = drain(pool, 100);
// Nothing should be a "min" item as those
// are still being created
checkMin(0, entries);
// And as the pool was just drained all the
// entries we get should be null
checkNull(entries);
// Should have "non-min" number of entries
checkMax(max - min, entries);
push(pool, entries);
}
Bean.instances.set(0);
// Try and trick the pool into adding more "min" items
// Fill the pool as much as we can -- should only let us
// fill to the max factoring in the "min" instances that
// are currently being created
{
final List entries = drain(pool, 100);
// Should reject the instance we try to add
assertFalse(pool.add(new Bean()));
// Empty the pool
discard(pool, entries);
// Now count how many instances it lets us add
Bean.instances.set(0);
while (pool.add(new Bean())) ;
// As the "min" instances are still being created
// it should only let us fill max - min, then + 1
// to account for the instance that gets rejected
// and terminates the while loop
final int expected = max - min + 1;
assertEquals(expected, Bean.instances.getAndSet(0));
}
// Ok, let the "min" instance creation threads continue
createInstances.countDown();
// Wait for the "min" instance creation to complete
await(created, 10, TimeUnit.SECONDS);
{
// Pool should be full again
final List entries = drain(pool, 100);
checkMin(min, entries);
checkEntries(max, entries);
push(pool, entries);
}
// -- DONE --
}
use of java.util.concurrent.CopyOnWriteArrayList in project tomee by apache.
the class MultiThreadedManagedDataSourceTest method insertsWithRollback.
@Test
public void insertsWithRollback() throws SQLException {
final int count = count("");
final AtomicInteger errors = new AtomicInteger(0);
final AtomicInteger fail = new AtomicInteger(0);
final AtomicInteger ok = new AtomicInteger(0);
final List<Exception> ex = new CopyOnWriteArrayList<Exception>();
run(new Runnable() {
@Override
public void run() {
final boolean rollback = Math.random() > 0.5;
if (!rollback) {
ok.incrementAndGet();
}
int id = -1;
try {
id = persistManager.saveRollback(!rollback);
} catch (final SQLException e) {
errors.incrementAndGet();
ex.add(e);
}
if (!rollback) {
try {
if (!exists(id)) {
fail.incrementAndGet();
}
} catch (final SQLException e) {
errors.incrementAndGet();
ex.add(e);
}
}
}
});
for (final Exception e : ex) {
e.printStackTrace(System.err);
}
assertEquals(0, errors.get());
assertEquals(0, fail.get());
assertEquals(ok.get(), count("") - count);
}
use of java.util.concurrent.CopyOnWriteArrayList in project tomee by apache.
the class SingletonContainer method invokeWebService.
private Object invokeWebService(final Object[] args, final BeanContext beanContext, final Method runMethod, final Instance instance) throws Exception {
if (args.length < 2) {
throw new IllegalArgumentException("WebService calls must follow format {messageContext, interceptor, [arg...]}.");
}
final Object messageContext = args[0];
if (messageContext == null) {
throw new IllegalArgumentException("MessageContext is null.");
}
// This object will be used as an interceptor in the stack and will be responsible
// for unmarshalling the soap message parts into an argument list that will be
// used for the actual method invocation.
//
// We just need to make it an interceptor in the OpenEJB sense and tack it on the end
// of our stack.
final Object interceptor = args[1];
if (interceptor == null) {
throw new IllegalArgumentException("Interceptor instance is null.");
}
final Class<?> interceptorClass = interceptor.getClass();
// Add the webservice interceptor to the list of interceptor instances
final Map<String, Object> interceptors = new HashMap<String, Object>(instance.interceptors);
{
interceptors.put(interceptorClass.getName(), interceptor);
}
// Create an InterceptorData for the webservice interceptor to the list of interceptorDatas for this method
final List<InterceptorData> interceptorDatas = new ArrayList<InterceptorData>();
{
final InterceptorData providerData = new InterceptorData(interceptorClass);
List<Method> aroundInvokes = interceptorCache.get(interceptorClass);
if (aroundInvokes == null) {
aroundInvokes = new ClassFinder(interceptorClass).findAnnotatedMethods(AroundInvoke.class);
if (SingletonContainer.class.getClassLoader() == interceptorClass.getClassLoader()) {
// use cache only for server classes
final List<Method> value = new CopyOnWriteArrayList<Method>(aroundInvokes);
// ensure it to be thread safe
aroundInvokes = interceptorCache.putIfAbsent(interceptorClass, value);
if (aroundInvokes == null) {
aroundInvokes = value;
}
}
}
providerData.getAroundInvoke().addAll(aroundInvokes);
interceptorDatas.add(0, providerData);
interceptorDatas.addAll(beanContext.getMethodInterceptors(runMethod));
}
final InterceptorStack interceptorStack = new InterceptorStack(instance.bean, runMethod, Operation.BUSINESS_WS, interceptorDatas, interceptors);
final Object[] params = new Object[runMethod.getParameterTypes().length];
if (messageContext instanceof javax.xml.rpc.handler.MessageContext) {
ThreadContext.getThreadContext().set(javax.xml.rpc.handler.MessageContext.class, (javax.xml.rpc.handler.MessageContext) messageContext);
return interceptorStack.invoke((javax.xml.rpc.handler.MessageContext) messageContext, params);
} else if (messageContext instanceof javax.xml.ws.handler.MessageContext) {
AddressingSupport wsaSupport = NoAddressingSupport.INSTANCE;
for (int i = 2; i < args.length; i++) {
if (args[i] instanceof AddressingSupport) {
wsaSupport = (AddressingSupport) args[i];
}
}
ThreadContext.getThreadContext().set(AddressingSupport.class, wsaSupport);
ThreadContext.getThreadContext().set(javax.xml.ws.handler.MessageContext.class, (javax.xml.ws.handler.MessageContext) messageContext);
return interceptorStack.invoke((javax.xml.ws.handler.MessageContext) messageContext, params);
}
throw new IllegalArgumentException("Uknown MessageContext type: " + messageContext.getClass().getName());
}
Aggregations