init
This commit is contained in:
30
java/org/apache/tomcat/util/threads/Constants.java
Normal file
30
java/org/apache/tomcat/util/threads/Constants.java
Normal file
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
/**
|
||||
* Static constants for this package.
|
||||
*/
|
||||
public final class Constants {
|
||||
|
||||
public static final long DEFAULT_THREAD_RENEWAL_DELAY = 1000L;
|
||||
|
||||
/**
|
||||
* Has security been turned on?
|
||||
*/
|
||||
public static final boolean IS_SECURITY_ENABLED = (System.getSecurityManager() != null);
|
||||
}
|
||||
169
java/org/apache/tomcat/util/threads/LimitLatch.java
Normal file
169
java/org/apache/tomcat/util/threads/LimitLatch.java
Normal file
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
|
||||
|
||||
import org.apache.juli.logging.Log;
|
||||
import org.apache.juli.logging.LogFactory;
|
||||
|
||||
/**
|
||||
* Shared latch that allows the latch to be acquired a limited number of times
|
||||
* after which all subsequent requests to acquire the latch will be placed in a
|
||||
* FIFO queue until one of the shares is returned.
|
||||
*/
|
||||
public class LimitLatch {
|
||||
|
||||
private static final Log log = LogFactory.getLog(LimitLatch.class);
|
||||
|
||||
private class Sync extends AbstractQueuedSynchronizer {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public Sync() {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int tryAcquireShared(int ignored) {
|
||||
long newCount = count.incrementAndGet();
|
||||
if (!released && newCount > limit) {
|
||||
// Limit exceeded
|
||||
count.decrementAndGet();
|
||||
return -1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean tryReleaseShared(int arg) {
|
||||
count.decrementAndGet();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private final Sync sync;
|
||||
private final AtomicLong count;
|
||||
private volatile long limit;
|
||||
private volatile boolean released = false;
|
||||
|
||||
/**
|
||||
* Instantiates a LimitLatch object with an initial limit.
|
||||
* @param limit - maximum number of concurrent acquisitions of this latch
|
||||
*/
|
||||
public LimitLatch(long limit) {
|
||||
this.limit = limit;
|
||||
this.count = new AtomicLong(0);
|
||||
this.sync = new Sync();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current count for the latch
|
||||
* @return the current count for latch
|
||||
*/
|
||||
public long getCount() {
|
||||
return count.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the current limit.
|
||||
* @return the limit
|
||||
*/
|
||||
public long getLimit() {
|
||||
return limit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sets a new limit. If the limit is decreased there may be a period where
|
||||
* more shares of the latch are acquired than the limit. In this case no
|
||||
* more shares of the latch will be issued until sufficient shares have been
|
||||
* returned to reduce the number of acquired shares of the latch to below
|
||||
* the new limit. If the limit is increased, threads currently in the queue
|
||||
* may not be issued one of the newly available shares until the next
|
||||
* request is made for a latch.
|
||||
*
|
||||
* @param limit The new limit
|
||||
*/
|
||||
public void setLimit(long limit) {
|
||||
this.limit = limit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Acquires a shared latch if one is available or waits for one if no shared
|
||||
* latch is current available.
|
||||
* @throws InterruptedException If the current thread is interrupted
|
||||
*/
|
||||
public void countUpOrAwait() throws InterruptedException {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Counting up["+Thread.currentThread().getName()+"] latch="+getCount());
|
||||
}
|
||||
sync.acquireSharedInterruptibly(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a shared latch, making it available for another thread to use.
|
||||
* @return the previous counter value
|
||||
*/
|
||||
public long countDown() {
|
||||
sync.releaseShared(0);
|
||||
long result = getCount();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Counting down["+Thread.currentThread().getName()+"] latch="+result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases all waiting threads and causes the {@link #limit} to be ignored
|
||||
* until {@link #reset()} is called.
|
||||
* @return <code>true</code> if release was done
|
||||
*/
|
||||
public boolean releaseAll() {
|
||||
released = true;
|
||||
return sync.releaseShared(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the latch and initializes the shared acquisition counter to zero.
|
||||
* @see #releaseAll()
|
||||
*/
|
||||
public void reset() {
|
||||
this.count.set(0);
|
||||
released = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns <code>true</code> if there is at least one thread waiting to
|
||||
* acquire the shared lock, otherwise returns <code>false</code>.
|
||||
* @return <code>true</code> if threads are waiting
|
||||
*/
|
||||
public boolean hasQueuedThreads() {
|
||||
return sync.hasQueuedThreads();
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide access to the list of threads waiting to acquire this limited
|
||||
* shared latch.
|
||||
* @return a collection of threads
|
||||
*/
|
||||
public Collection<Thread> getQueuedThreads() {
|
||||
return sync.getQueuedThreads();
|
||||
}
|
||||
}
|
||||
44
java/org/apache/tomcat/util/threads/ResizableExecutor.java
Normal file
44
java/org/apache/tomcat/util/threads/ResizableExecutor.java
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
public interface ResizableExecutor extends Executor {
|
||||
|
||||
/**
|
||||
* Returns the current number of threads in the pool.
|
||||
*
|
||||
* @return the number of threads
|
||||
*/
|
||||
public int getPoolSize();
|
||||
|
||||
public int getMaxThreads();
|
||||
|
||||
/**
|
||||
* Returns the approximate number of threads that are actively executing
|
||||
* tasks.
|
||||
*
|
||||
* @return the number of threads
|
||||
*/
|
||||
public int getActiveCount();
|
||||
|
||||
public boolean resizePool(int corePoolSize, int maximumPoolSize);
|
||||
|
||||
public boolean resizeQueue(int capacity);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
|
||||
/**
|
||||
* A custom {@link RuntimeException} thrown by the {@link ThreadPoolExecutor}
|
||||
* to signal that the thread should be disposed of.
|
||||
*/
|
||||
public class StopPooledThreadException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public StopPooledThreadException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
122
java/org/apache/tomcat/util/threads/TaskQueue.java
Normal file
122
java/org/apache/tomcat/util/threads/TaskQueue.java
Normal file
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* As task queue specifically designed to run with a thread pool executor. The
|
||||
* task queue is optimised to properly utilize threads within a thread pool
|
||||
* executor. If you use a normal queue, the executor will spawn threads when
|
||||
* there are idle threads and you wont be able to force items onto the queue
|
||||
* itself.
|
||||
*/
|
||||
public class TaskQueue extends LinkedBlockingQueue<Runnable> {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private transient volatile ThreadPoolExecutor parent = null;
|
||||
|
||||
// No need to be volatile. This is written and read in a single thread
|
||||
// (when stopping a context and firing the listeners)
|
||||
private Integer forcedRemainingCapacity = null;
|
||||
|
||||
public TaskQueue() {
|
||||
super();
|
||||
}
|
||||
|
||||
public TaskQueue(int capacity) {
|
||||
super(capacity);
|
||||
}
|
||||
|
||||
public TaskQueue(Collection<? extends Runnable> c) {
|
||||
super(c);
|
||||
}
|
||||
|
||||
public void setParent(ThreadPoolExecutor tp) {
|
||||
parent = tp;
|
||||
}
|
||||
|
||||
public boolean force(Runnable o) {
|
||||
if (parent == null || parent.isShutdown()) throw new RejectedExecutionException("Executor not running, can't force a command into the queue");
|
||||
return super.offer(o); //forces the item onto the queue, to be used if the task is rejected
|
||||
}
|
||||
|
||||
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
|
||||
if (parent == null || parent.isShutdown()) throw new RejectedExecutionException("Executor not running, can't force a command into the queue");
|
||||
return super.offer(o,timeout,unit); //forces the item onto the queue, to be used if the task is rejected
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean offer(Runnable o) {
|
||||
//we can't do any checks
|
||||
if (parent==null) return super.offer(o);
|
||||
//we are maxed out on threads, simply queue the object
|
||||
if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o);
|
||||
//we have idle threads, just add it to the queue
|
||||
if (parent.getSubmittedCount()<=(parent.getPoolSize())) return super.offer(o);
|
||||
//if we have less threads than maximum force creation of a new thread
|
||||
if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false;
|
||||
//if we reached here, we need to add it to the queue
|
||||
return super.offer(o);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Runnable poll(long timeout, TimeUnit unit)
|
||||
throws InterruptedException {
|
||||
Runnable runnable = super.poll(timeout, unit);
|
||||
if (runnable == null && parent != null) {
|
||||
// the poll timed out, it gives an opportunity to stop the current
|
||||
// thread if needed to avoid memory leaks.
|
||||
parent.stopCurrentThreadIfNeeded();
|
||||
}
|
||||
return runnable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Runnable take() throws InterruptedException {
|
||||
if (parent != null && parent.currentThreadShouldBeStopped()) {
|
||||
return poll(parent.getKeepAliveTime(TimeUnit.MILLISECONDS),
|
||||
TimeUnit.MILLISECONDS);
|
||||
// yes, this may return null (in case of timeout) which normally
|
||||
// does not occur with take()
|
||||
// but the ThreadPoolExecutor implementation allows this
|
||||
}
|
||||
return super.take();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int remainingCapacity() {
|
||||
if (forcedRemainingCapacity != null) {
|
||||
// ThreadPoolExecutor.setCorePoolSize checks that
|
||||
// remainingCapacity==0 to allow to interrupt idle threads
|
||||
// I don't see why, but this hack allows to conform to this
|
||||
// "requirement"
|
||||
return forcedRemainingCapacity.intValue();
|
||||
}
|
||||
return super.remainingCapacity();
|
||||
}
|
||||
|
||||
public void setForcedRemainingCapacity(Integer forcedRemainingCapacity) {
|
||||
this.forcedRemainingCapacity = forcedRemainingCapacity;
|
||||
}
|
||||
|
||||
}
|
||||
71
java/org/apache/tomcat/util/threads/TaskThread.java
Normal file
71
java/org/apache/tomcat/util/threads/TaskThread.java
Normal file
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
import org.apache.juli.logging.Log;
|
||||
import org.apache.juli.logging.LogFactory;
|
||||
|
||||
/**
|
||||
* A Thread implementation that records the time at which it was created.
|
||||
*
|
||||
*/
|
||||
public class TaskThread extends Thread {
|
||||
|
||||
private static final Log log = LogFactory.getLog(TaskThread.class);
|
||||
private final long creationTime;
|
||||
|
||||
public TaskThread(ThreadGroup group, Runnable target, String name) {
|
||||
super(group, new WrappingRunnable(target), name);
|
||||
this.creationTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public TaskThread(ThreadGroup group, Runnable target, String name,
|
||||
long stackSize) {
|
||||
super(group, new WrappingRunnable(target), name, stackSize);
|
||||
this.creationTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the time (in ms) at which this thread was created
|
||||
*/
|
||||
public final long getCreationTime() {
|
||||
return creationTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a {@link Runnable} to swallow any {@link StopPooledThreadException}
|
||||
* instead of letting it go and potentially trigger a break in a debugger.
|
||||
*/
|
||||
private static class WrappingRunnable implements Runnable {
|
||||
private Runnable wrappedRunnable;
|
||||
WrappingRunnable(Runnable wrappedRunnable) {
|
||||
this.wrappedRunnable = wrappedRunnable;
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
wrappedRunnable.run();
|
||||
} catch(StopPooledThreadException exc) {
|
||||
//expected : we just swallow the exception to avoid disturbing
|
||||
//debuggers like eclipse's
|
||||
log.debug("Thread exiting on purpose", exc);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
65
java/org/apache/tomcat/util/threads/TaskThreadFactory.java
Normal file
65
java/org/apache/tomcat/util/threads/TaskThreadFactory.java
Normal file
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
import java.security.AccessController;
|
||||
import java.security.PrivilegedAction;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.apache.tomcat.util.security.PrivilegedSetTccl;
|
||||
|
||||
/**
|
||||
* Simple task thread factory to use to create threads for an executor
|
||||
* implementation.
|
||||
*/
|
||||
public class TaskThreadFactory implements ThreadFactory {
|
||||
|
||||
private final ThreadGroup group;
|
||||
private final AtomicInteger threadNumber = new AtomicInteger(1);
|
||||
private final String namePrefix;
|
||||
private final boolean daemon;
|
||||
private final int threadPriority;
|
||||
|
||||
public TaskThreadFactory(String namePrefix, boolean daemon, int priority) {
|
||||
SecurityManager s = System.getSecurityManager();
|
||||
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
|
||||
this.namePrefix = namePrefix;
|
||||
this.daemon = daemon;
|
||||
this.threadPriority = priority;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
TaskThread t = new TaskThread(group, r, namePrefix + threadNumber.getAndIncrement());
|
||||
t.setDaemon(daemon);
|
||||
t.setPriority(threadPriority);
|
||||
|
||||
// Set the context class loader of newly created threads to be the class
|
||||
// loader that loaded this factory. This avoids retaining references to
|
||||
// web application class loaders and similar.
|
||||
if (Constants.IS_SECURITY_ENABLED) {
|
||||
PrivilegedAction<Void> pa = new PrivilegedSetTccl(
|
||||
t, getClass().getClassLoader());
|
||||
AccessController.doPrivileged(pa);
|
||||
} else {
|
||||
t.setContextClassLoader(getClass().getClassLoader());
|
||||
}
|
||||
|
||||
return t;
|
||||
}
|
||||
}
|
||||
227
java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
Normal file
227
java/org/apache/tomcat/util/threads/ThreadPoolExecutor.java
Normal file
@@ -0,0 +1,227 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.apache.tomcat.util.threads;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.apache.tomcat.util.res.StringManager;
|
||||
|
||||
/**
|
||||
* Same as a java.util.concurrent.ThreadPoolExecutor but implements a much more efficient
|
||||
* {@link #getSubmittedCount()} method, to be used to properly handle the work queue.
|
||||
* If a RejectedExecutionHandler is not specified a default one will be configured
|
||||
* and that one will always throw a RejectedExecutionException
|
||||
*
|
||||
*/
|
||||
public class ThreadPoolExecutor extends java.util.concurrent.ThreadPoolExecutor {
|
||||
/**
|
||||
* The string manager for this package.
|
||||
*/
|
||||
protected static final StringManager sm = StringManager
|
||||
.getManager("org.apache.tomcat.util.threads.res");
|
||||
|
||||
/**
|
||||
* The number of tasks submitted but not yet finished. This includes tasks
|
||||
* in the queue and tasks that have been handed to a worker thread but the
|
||||
* latter did not start executing the task yet.
|
||||
* This number is always greater or equal to {@link #getActiveCount()}.
|
||||
*/
|
||||
private final AtomicInteger submittedCount = new AtomicInteger(0);
|
||||
private final AtomicLong lastContextStoppedTime = new AtomicLong(0L);
|
||||
|
||||
/**
|
||||
* Most recent time in ms when a thread decided to kill itself to avoid
|
||||
* potential memory leaks. Useful to throttle the rate of renewals of
|
||||
* threads.
|
||||
*/
|
||||
private final AtomicLong lastTimeThreadKilledItself = new AtomicLong(0L);
|
||||
|
||||
/**
|
||||
* Delay in ms between 2 threads being renewed. If negative, do not renew threads.
|
||||
*/
|
||||
private long threadRenewalDelay = Constants.DEFAULT_THREAD_RENEWAL_DELAY;
|
||||
|
||||
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
|
||||
prestartAllCoreThreads();
|
||||
}
|
||||
|
||||
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
|
||||
RejectedExecutionHandler handler) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
|
||||
prestartAllCoreThreads();
|
||||
}
|
||||
|
||||
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, new RejectHandler());
|
||||
prestartAllCoreThreads();
|
||||
}
|
||||
|
||||
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new RejectHandler());
|
||||
prestartAllCoreThreads();
|
||||
}
|
||||
|
||||
public long getThreadRenewalDelay() {
|
||||
return threadRenewalDelay;
|
||||
}
|
||||
|
||||
public void setThreadRenewalDelay(long threadRenewalDelay) {
|
||||
this.threadRenewalDelay = threadRenewalDelay;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void afterExecute(Runnable r, Throwable t) {
|
||||
submittedCount.decrementAndGet();
|
||||
|
||||
if (t == null) {
|
||||
stopCurrentThreadIfNeeded();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If the current thread was started before the last time when a context was
|
||||
* stopped, an exception is thrown so that the current thread is stopped.
|
||||
*/
|
||||
protected void stopCurrentThreadIfNeeded() {
|
||||
if (currentThreadShouldBeStopped()) {
|
||||
long lastTime = lastTimeThreadKilledItself.longValue();
|
||||
if (lastTime + threadRenewalDelay < System.currentTimeMillis()) {
|
||||
if (lastTimeThreadKilledItself.compareAndSet(lastTime,
|
||||
System.currentTimeMillis() + 1)) {
|
||||
// OK, it's really time to dispose of this thread
|
||||
|
||||
final String msg = sm.getString(
|
||||
"threadPoolExecutor.threadStoppedToAvoidPotentialLeak",
|
||||
Thread.currentThread().getName());
|
||||
|
||||
throw new StopPooledThreadException(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean currentThreadShouldBeStopped() {
|
||||
if (threadRenewalDelay >= 0
|
||||
&& Thread.currentThread() instanceof TaskThread) {
|
||||
TaskThread currentTaskThread = (TaskThread) Thread.currentThread();
|
||||
if (currentTaskThread.getCreationTime() <
|
||||
this.lastContextStoppedTime.longValue()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int getSubmittedCount() {
|
||||
return submittedCount.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public void execute(Runnable command) {
|
||||
execute(command,0,TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the given command at some time in the future. The command
|
||||
* may execute in a new thread, in a pooled thread, or in the calling
|
||||
* thread, at the discretion of the <code>Executor</code> implementation.
|
||||
* If no threads are available, it will be added to the work queue.
|
||||
* If the work queue is full, the system will wait for the specified
|
||||
* time and it throw a RejectedExecutionException if the queue is still
|
||||
* full after that.
|
||||
*
|
||||
* @param command the runnable task
|
||||
* @param timeout A timeout for the completion of the task
|
||||
* @param unit The timeout time unit
|
||||
* @throws RejectedExecutionException if this task cannot be
|
||||
* accepted for execution - the queue is full
|
||||
* @throws NullPointerException if command or unit is null
|
||||
*/
|
||||
public void execute(Runnable command, long timeout, TimeUnit unit) {
|
||||
submittedCount.incrementAndGet();
|
||||
try {
|
||||
super.execute(command);
|
||||
} catch (RejectedExecutionException rx) {
|
||||
if (super.getQueue() instanceof TaskQueue) {
|
||||
final TaskQueue queue = (TaskQueue)super.getQueue();
|
||||
try {
|
||||
if (!queue.force(command, timeout, unit)) {
|
||||
submittedCount.decrementAndGet();
|
||||
throw new RejectedExecutionException("Queue capacity is full.");
|
||||
}
|
||||
} catch (InterruptedException x) {
|
||||
submittedCount.decrementAndGet();
|
||||
throw new RejectedExecutionException(x);
|
||||
}
|
||||
} else {
|
||||
submittedCount.decrementAndGet();
|
||||
throw rx;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void contextStopping() {
|
||||
this.lastContextStoppedTime.set(System.currentTimeMillis());
|
||||
|
||||
// save the current pool parameters to restore them later
|
||||
int savedCorePoolSize = this.getCorePoolSize();
|
||||
TaskQueue taskQueue =
|
||||
getQueue() instanceof TaskQueue ? (TaskQueue) getQueue() : null;
|
||||
if (taskQueue != null) {
|
||||
// note by slaurent : quite oddly threadPoolExecutor.setCorePoolSize
|
||||
// checks that queue.remainingCapacity()==0. I did not understand
|
||||
// why, but to get the intended effect of waking up idle threads, I
|
||||
// temporarily fake this condition.
|
||||
taskQueue.setForcedRemainingCapacity(Integer.valueOf(0));
|
||||
}
|
||||
|
||||
// setCorePoolSize(0) wakes idle threads
|
||||
this.setCorePoolSize(0);
|
||||
|
||||
// TaskQueue.take() takes care of timing out, so that we are sure that
|
||||
// all threads of the pool are renewed in a limited time, something like
|
||||
// (threadKeepAlive + longest request time)
|
||||
|
||||
if (taskQueue != null) {
|
||||
// ok, restore the state of the queue and pool
|
||||
taskQueue.setForcedRemainingCapacity(null);
|
||||
}
|
||||
this.setCorePoolSize(savedCorePoolSize);
|
||||
}
|
||||
|
||||
private static class RejectHandler implements RejectedExecutionHandler {
|
||||
@Override
|
||||
public void rejectedExecution(Runnable r,
|
||||
java.util.concurrent.ThreadPoolExecutor executor) {
|
||||
throw new RejectedExecutionException();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
# contributor license agreements. See the NOTICE file distributed with
|
||||
# this work for additional information regarding copyright ownership.
|
||||
# The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
# (the "License"); you may not use this file except in compliance with
|
||||
# the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
threadPoolExecutor.threadStoppedToAvoidPotentialLeak=Stopping thread [{0}] to avoid potential memory leaks after a context was stopped.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
# contributor license agreements. See the NOTICE file distributed with
|
||||
# this work for additional information regarding copyright ownership.
|
||||
# The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
# (the "License"); you may not use this file except in compliance with
|
||||
# the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
threadPoolExecutor.threadStoppedToAvoidPotentialLeak=Parando hilo [{0}] para evita fallos potenciales de memoria tras haberse parado un contexto.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
# contributor license agreements. See the NOTICE file distributed with
|
||||
# this work for additional information regarding copyright ownership.
|
||||
# The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
# (the "License"); you may not use this file except in compliance with
|
||||
# the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
threadPoolExecutor.threadStoppedToAvoidPotentialLeak=Arrêt du thread [{0}] pour éviter de potentielles fuites de mémoire après l''arrêt d''un contexte
|
||||
@@ -0,0 +1,16 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
# contributor license agreements. See the NOTICE file distributed with
|
||||
# this work for additional information regarding copyright ownership.
|
||||
# The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
# (the "License"); you may not use this file except in compliance with
|
||||
# the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
threadPoolExecutor.threadStoppedToAvoidPotentialLeak=コンテキストが停止した後の潜在的なメモリリークを防ぐため、スレッド[{0}]を停止しています。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
# contributor license agreements. See the NOTICE file distributed with
|
||||
# this work for additional information regarding copyright ownership.
|
||||
# The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
# (the "License"); you may not use this file except in compliance with
|
||||
# the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
threadPoolExecutor.threadStoppedToAvoidPotentialLeak=컨텍스트가 중지된 후에 발생할 수 있는 잠재적 메모리 누수를 피하기 위하여, 쓰레드 [{0}]을(를) 중지시킵니다.
|
||||
Reference in New Issue
Block a user