Issue #3361 thread safe addHandler

Added new thread safe methods deployHandler and undeployHandler

Signed-off-by: Greg Wilkins <gregw@webtide.com>
This commit is contained in:
Greg Wilkins 2019-03-20 18:18:55 +11:00
parent 79c1700f62
commit 1accced62f
6 changed files with 233 additions and 30 deletions

View File

@ -40,6 +40,6 @@ public class StandardDeployer implements AppLifeCycle.Binding
{
throw new NullPointerException("No Handler created for App: " + app);
}
app.getDeploymentManager().getContexts().addHandler(handler);
app.getDeploymentManager().getContexts().deployHandler(handler);
}
}

View File

@ -21,10 +21,8 @@ package org.eclipse.jetty.deploy.bindings;
import org.eclipse.jetty.deploy.App;
import org.eclipse.jetty.deploy.AppLifeCycle;
import org.eclipse.jetty.deploy.graph.Node;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -44,31 +42,6 @@ public class StandardUndeployer implements AppLifeCycle.Binding
{
ContextHandler handler = app.getContextHandler();
ContextHandlerCollection chcoll = app.getDeploymentManager().getContexts();
recursiveRemoveContext(chcoll,handler);
}
private void recursiveRemoveContext(HandlerCollection coll, ContextHandler context)
{
Handler children[] = coll.getHandlers();
int originalCount = children.length;
for (int i = 0, n = children.length; i < n; i++)
{
Handler child = children[i];
LOG.debug("Child handler {}",child);
if (child.equals(context))
{
LOG.debug("Removing handler {}",child);
coll.removeHandler(child);
child.destroy();
if (LOG.isDebugEnabled())
LOG.debug("After removal: {} (originally {})",coll.getHandlers().length,originalCount);
}
else if (child instanceof HandlerCollection)
{
recursiveRemoveContext((HandlerCollection)child,context);
}
}
chcoll.undeployHandler(handler);
}
}

View File

@ -40,6 +40,7 @@ import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.SerializedExecutor;
/* ------------------------------------------------------------ */
/** ContextHandlerCollection.
@ -56,6 +57,7 @@ import org.eclipse.jetty.util.log.Logger;
public class ContextHandlerCollection extends HandlerCollection
{
private static final Logger LOG = Log.getLogger(ContextHandlerCollection.class);
private final SerializedExecutor _serializedExecutor = new SerializedExecutor();
private Class<? extends ContextHandler> _contextClass = ContextHandler.class;
@ -233,6 +235,7 @@ public class ContextHandlerCollection extends HandlerCollection
* @param resourceBase the base (root) Resource
* @return the ContextHandler just added
*/
@Deprecated
public ContextHandler addContext(String contextPath,String resourceBase)
{
try
@ -250,7 +253,37 @@ public class ContextHandlerCollection extends HandlerCollection
}
}
/* ------------------------------------------------------------ */
/**
* Thread safe deploy of a Handler.
* <p>
* This method is the equivalent of {@link #addHandler(Handler)},
* but its execution is non-block and mutually excluded from all
* other calls to {@link #deployHandler(Handler)} and
* {@link #undeployHandler(Handler)}
* </p>
* @param handler the handler to deploy
*/
public void deployHandler(Handler handler)
{
_serializedExecutor.execute(()-> addHandler(handler));
}
/* ------------------------------------------------------------ */
public void undeployHandler(Handler handler)
/**
* Thread safe undeploy of a Handler.
* <p>
* This method is the equivalent of {@link #removeHandler(Handler)},
* but its execution is non-block and mutually excluded from all
* other calls to {@link #deployHandler(Handler)} and
* {@link #undeployHandler(Handler)}
* </p>
* @param handler The handler to undeploy
*/
{
_serializedExecutor.execute(()-> removeHandler(handler));
}
/* ------------------------------------------------------------ */
/**

View File

@ -91,7 +91,11 @@ public class HandlerCollection extends AbstractHandlerContainer
if (!_mutableWhenRunning && isStarted())
throw new IllegalStateException(STARTED);
while(!updateHandlers(_handlers.get(),newHandlers(handlers)));
while(true)
{
if(updateHandlers(_handlers.get(),newHandlers(handlers)))
break;
};
}
/* ------------------------------------------------------------ */

View File

@ -0,0 +1,98 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util.thread;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.log.Log;
/**
* An executor than ensurers serial execution of submitted tasks.
* <p>
* Callers of this execute will never block in the executor, but they may
* be required to either execute the task they submit or tasks submitted
* by other threads whilst they are executing tasks.
* </p>
* <p>
* This class was inspired by the public domain class
* <a href="https://github.com/jroper/reactive-streams-servlet/blob/master/reactive-streams-servlet/src/main/java/org/reactivestreams/servlet/NonBlockingMutexExecutor.java">NonBlockingMutexExecutor</a>
* </p>
*/
public class SerializedExecutor implements Executor
{
final AtomicReference<Link> _tail = new AtomicReference<>();
@Override
public void execute(Runnable task)
{
Link link = new Link(task);
Link secondLast = _tail.getAndSet(link);
if (secondLast==null)
run(link);
else
secondLast._next.lazySet(link);
}
protected void onError(Runnable task, Throwable t)
{
Log.getLogger(task.getClass()).warn(t);
}
private void run(Link link)
{
while(true)
{
try
{
link._task.run();
}
catch (Throwable t)
{
onError(link._task, t);
}
finally
{
// Are we the current the last Link?
if (_tail.compareAndSet(link, null))
return;
// not the last task, so its next link will eventually be set
Link next = link._next.get();
while (next == null)
{
Thread.yield(); // Thread.onSpinWait();
next = link._next.get();
}
link = next;
}
}
}
private class Link
{
final Runnable _task;
final AtomicReference<Link> _next = new AtomicReference<>();
public Link(Runnable task)
{
_task = task;
}
}
}

View File

@ -0,0 +1,95 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util.thread;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SerializedExecutorTest
{
@Test
public void test() throws Exception
{
int threads = 64;
int loops = 1000;
int depth = 100;
AtomicInteger ran = new AtomicInteger();
AtomicBoolean running = new AtomicBoolean();
SerializedExecutor executor = new SerializedExecutor();
final CountDownLatch start = new CountDownLatch(1);
final CountDownLatch stop = new CountDownLatch(threads);
final Random random = new Random();
for (int t=threads; t-->0;)
{
new Thread(()->
{
try
{
start.await();
for (int l=loops; l-->0;)
{
final AtomicInteger d = new AtomicInteger(depth);
executor.execute(new Runnable()
{
@Override
public void run()
{
ran.incrementAndGet();
if (!running.compareAndSet(false, true))
throw new IllegalStateException();
if (d.decrementAndGet() > 0)
executor.execute(this);
if (!running.compareAndSet(true, false))
throw new IllegalStateException();
}
});
Thread.sleep(random.nextInt(5));
}
}
catch(Throwable th)
{
th.printStackTrace();
}
finally
{
stop.countDown();
}
}).start();
}
start.countDown();
assertTrue(stop.await(30, TimeUnit.SECONDS));
assertThat(ran.get(), Matchers.is(threads*loops*depth));
}
}