This is an automated email from the ASF dual-hosted git repository. rombert pushed a commit to annotated tag org.apache.sling.commons.threads-2.0.2-incubator in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-commons-threads.git
commit 0061bf1f84f23556cc2a22c128e5db53d753e890 Author: Felix Meschberger <[email protected]> AuthorDate: Thu Jun 18 09:21:02 2009 +0000 Move Sling to new TLP location git-svn-id: https://svn.eu.apache.org/repos/asf/sling/tags/org.apache.sling.commons.threads-2.0.2-incubator@785979 13f79535-47bb-0310-9956-ffa450edef68 --- LICENSE | 202 +++++++++++++++++++++ NOTICE | 8 + README.txt | 36 ++++ pom.xml | 91 ++++++++++ .../apache/sling/commons/threads/ThreadPool.java | 44 +++++ .../sling/commons/threads/ThreadPoolConfig.java | 202 +++++++++++++++++++++ .../sling/commons/threads/ThreadPoolManager.java | 56 ++++++ .../commons/threads/impl/DefaultThreadPool.java | 194 ++++++++++++++++++++ .../threads/impl/DefaultThreadPoolManager.java | 133 ++++++++++++++ .../threads/impl/ExtendedThreadFactory.java | 79 ++++++++ src/main/resources/META-INF/DISCLAIMER | 7 + src/main/resources/META-INF/LICENSE | 202 +++++++++++++++++++++ src/main/resources/META-INF/NOTICE | 8 + 13 files changed, 1262 insertions(+) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..3a4d87e --- /dev/null +++ b/NOTICE @@ -0,0 +1,8 @@ +Apache Sling Threads +Copyright 2008 The Apache Software Foundation + +Apache Sling is based on source code originally developed +by Day Software (http://www.day.com/). + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..37ca813 --- /dev/null +++ b/README.txt @@ -0,0 +1,36 @@ +Apache Sling Threads + +Support for thread handling like pooling. + +Disclaimer +========== +Apache Sling is an effort undergoing incubation at The Apache Software Foundation (ASF), +sponsored by the Apache Jackrabbit PMC. Incubation is required of all newly accepted +projects until a further review indicates that the infrastructure, communications, +and decision making process have stabilized in a manner consistent with other +successful ASF projects. While incubation status is not necessarily a reflection of +the completeness or stability of the code, it does indicate that the project has yet +to be fully endorsed by the ASF. + +Getting Started +=============== + +This component uses a Maven 2 (http://maven.apache.org/) build +environment. It requires a Java 5 JDK (or higher) and Maven (http://maven.apache.org/) +2.0.7 or later. We recommend to use the latest Maven version. + +If you have Maven 2 installed, you can compile and +package the jar using the following command: + + mvn package + +See the Maven 2 documentation for other build features. + +The latest source code for this component is available in the +Subversion (http://subversion.tigris.org/) source repository of +the Apache Software Foundation. If you have Subversion installed, +you can checkout the latest source using the following command: + + svn checkout http://svn.apache.org/repos/asf/incubator/sling/trunk/commons/threads + +See the Subversion documentation for other source control features. diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..324059e --- /dev/null +++ b/pom.xml @@ -0,0 +1,91 @@ +<?xml version="1.0" encoding="ISO-8859-1"?> +<!-- + 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. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.sling</groupId> + <artifactId>sling</artifactId> + <version>3-incubator</version> + <relativePath>../../parent/pom.xml</relativePath> + </parent> + + <artifactId>org.apache.sling.commons.threads</artifactId> + <packaging>bundle</packaging> + <version>2.0.2-incubator</version> + + <name>Sling - Thread Support</name> + <description> + Support for thread handling like pooling. + </description> + + <scm> + <connection>scm:svn:http://svn.apache.org/repos/asf/incubator/sling/tags/org.apache.sling.commons.threads-2.0.2-incubator</connection> + <developerConnection>scm:svn:https://svn.apache.org/repos/asf/incubator/sling/tags/org.apache.sling.commons.threads-2.0.2-incubator</developerConnection> + <url>http://svn.apache.org/viewvc/incubator/sling/tags/org.apache.sling.commons.threads-2.0.2-incubator</url> + </scm> + + <build> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-scr-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + <extensions>true</extensions> + <configuration> + <instructions> + <Export-Package> + org.apache.sling.commons.threads;version=${pom.version} + </Export-Package> + <Private-Package> + org.apache.sling.commons.threads.impl + </Private-Package> + </instructions> + </configuration> + </plugin> + </plugins> + </build> + <reporting> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <configuration> + <excludePackageNames> + org.apache.sling.commons.threads.impl + </excludePackageNames> + </configuration> + </plugin> + </plugins> + </reporting> + <dependencies> + <dependency> + <groupId>org.apache.felix</groupId> + <artifactId>org.osgi.compendium</artifactId> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </dependency> + </dependencies> +</project> diff --git a/src/main/java/org/apache/sling/commons/threads/ThreadPool.java b/src/main/java/org/apache/sling/commons/threads/ThreadPool.java new file mode 100644 index 0000000..e99c13e --- /dev/null +++ b/src/main/java/org/apache/sling/commons/threads/ThreadPool.java @@ -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.sling.commons.threads; + +/** + * The ThreadPool interface allows to start runnables by + * getting threads from a managed pool. + * + * @version $Id$ + */ +public interface ThreadPool { + + /** + * Execute a runnable + * @param runnable The {@link Runnable} to execute + */ + void execute(Runnable runnable); + + /** + * The name of the thread pool. + */ + String getName(); + + /** + * Shut down the thread pool. + */ + void shutdown(); + + ThreadPoolConfig getConfiguration(); +} diff --git a/src/main/java/org/apache/sling/commons/threads/ThreadPoolConfig.java b/src/main/java/org/apache/sling/commons/threads/ThreadPoolConfig.java new file mode 100644 index 0000000..1274aaa --- /dev/null +++ b/src/main/java/org/apache/sling/commons/threads/ThreadPoolConfig.java @@ -0,0 +1,202 @@ +/* + * 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.sling.commons.threads; + +import java.util.concurrent.ThreadFactory; + +/** + * The ThreadPool configuration. + * + * @version $Id$ + */ +public final class ThreadPoolConfig { + + /** The thread pool policies. */ + public enum ThreadPoolPolicy { + ABORT, + DISCARD, + DISCARDOLDEST, + RUN + }; + + public enum ThreadPriority { + NORM, + MIN, + MAX + }; + + /** The min pool size. */ + private int minPoolSize = 5; + + /** The max pool size. */ + private int maxPoolSize = 5; + + /** The queue size */ + private int queueSize = -1; + + /** The keep alive time. */ + private long keepAliveTime = 60000L; + + /** The thread pool policy. Default is RUN. */ + private ThreadPoolPolicy blockPolicy = ThreadPoolPolicy.RUN; + + private boolean shutdownGraceful = false; + + private int shutdownWaitTimeMs = -1; + + private ThreadFactory factory; + + private ThreadPriority priority = ThreadPriority.NORM; + + private boolean isDaemon = false; + + /** Can this configuration still be changed? */ + private boolean isWritable = true; + + /** + * Create a new default configuration. + */ + public ThreadPoolConfig() { + // nothing to do + } + + /** + * Clone an existing configuration + * @param copy The config to clone + */ + public ThreadPoolConfig(ThreadPoolConfig copy) { + this.minPoolSize = copy.minPoolSize; + this.maxPoolSize = copy.maxPoolSize; + this.queueSize = copy.queueSize; + this.keepAliveTime = copy.keepAliveTime; + this.blockPolicy = copy.blockPolicy; + this.shutdownGraceful = copy.shutdownGraceful; + this.shutdownWaitTimeMs = copy.shutdownWaitTimeMs; + this.factory = copy.factory; + this.priority = copy.priority; + this.isDaemon = copy.isDaemon; + } + + protected void checkWritable() { + if ( !isWritable ) { + throw new IllegalStateException("ThreadPoolConfig is read-only."); + } + } + + /** + * Make the configuration read-only. + */ + public void makeReadOnly() { + this.isWritable = false; + } + + public int getMinPoolSize() { + return minPoolSize; + } + + public void setMinPoolSize(int minPoolSize) { + this.checkWritable(); + this.minPoolSize = minPoolSize; + } + + public int getMaxPoolSize() { + return maxPoolSize; + } + + public void setMaxPoolSize(int maxPoolSize) { + this.checkWritable(); + this.maxPoolSize = maxPoolSize; + } + + public int getQueueSize() { + return queueSize; + } + + public void setQueueSize(int queueSize) { + this.checkWritable(); + this.queueSize = queueSize; + } + + public long getKeepAliveTime() { + return keepAliveTime; + } + + public void setKeepAliveTime(long keepAliveTime) { + this.checkWritable(); + this.keepAliveTime = keepAliveTime; + } + + public ThreadPoolPolicy getBlockPolicy() { + return blockPolicy; + } + + public void setBlockPolicy(ThreadPoolPolicy blockPolicy) { + this.checkWritable(); + this.blockPolicy = blockPolicy; + if ( blockPolicy == null ) { + throw new IllegalArgumentException("Policy must not be null."); + } + } + + public boolean isShutdownGraceful() { + return shutdownGraceful; + } + + public void setShutdownGraceful(boolean shutdownGraceful) { + this.checkWritable(); + this.shutdownGraceful = shutdownGraceful; + } + + public int getShutdownWaitTimeMs() { + return shutdownWaitTimeMs; + } + + public void setShutdownWaitTimeMs(int shutdownWaitTimeMs) { + this.checkWritable(); + this.shutdownWaitTimeMs = shutdownWaitTimeMs; + } + + public ThreadFactory getFactory() { + return factory; + } + + public void setFactory(ThreadFactory factory) { + this.checkWritable(); + this.factory = factory; + } + + public ThreadPriority getPriority() { + return priority; + } + + public void setPriority(ThreadPriority priority) { + this.checkWritable(); + if ( priority == null ) { + throw new IllegalArgumentException("Priority must not be null."); + } + this.priority = priority; + } + + public boolean isDaemon() { + return isDaemon; + } + + public void setDaemon(boolean isDaemon) { + this.checkWritable(); + this.isDaemon = isDaemon; + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/sling/commons/threads/ThreadPoolManager.java b/src/main/java/org/apache/sling/commons/threads/ThreadPoolManager.java new file mode 100644 index 0000000..fc9c060 --- /dev/null +++ b/src/main/java/org/apache/sling/commons/threads/ThreadPoolManager.java @@ -0,0 +1,56 @@ +/* + * 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.sling.commons.threads; + + +/** + * The <cod>ThreadPoolManager</code> manages thread pools. + * + * @version $Id$ + */ +public interface ThreadPoolManager { + + /** The default thread pool name */ + String DEFAULT_THREADPOOL_NAME = "default"; + + /** + * Add a new pool. + * If a pool with the same name already exists, the new pool is not added + * and false is returned. + * @param pool The pool. + * @return True if the pool could be added, false otherwise. + */ + boolean add(ThreadPool pool); + + /** + * Get a thread pool. + * If there is no thread pool with the given name, the default thread + * pool is returned. + * @param name The name of the thread pool or null for the default pool. + */ + ThreadPool get(String name); + + /** + * Create a new thread pool. + * If a pool with the same name already exists, no new pool is created + * and <code>null</code> is returned. + * @param name Name must not be null. + * @param config The thread pool configuration. + */ + ThreadPool create(String name, + ThreadPoolConfig config); +} diff --git a/src/main/java/org/apache/sling/commons/threads/impl/DefaultThreadPool.java b/src/main/java/org/apache/sling/commons/threads/impl/DefaultThreadPool.java new file mode 100644 index 0000000..7c19c75 --- /dev/null +++ b/src/main/java/org/apache/sling/commons/threads/impl/DefaultThreadPool.java @@ -0,0 +1,194 @@ +/* + * 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.sling.commons.threads.impl; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.apache.sling.commons.threads.ThreadPool; +import org.apache.sling.commons.threads.ThreadPoolConfig; +import org.apache.sling.commons.threads.ThreadPoolManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * The DefaultThreadPool class implements the {@link ThreadPool} interface. + * Instances of this class are managed by the {@link ThreadPoolManager}. + * + * @version $Id$ + */ +public class DefaultThreadPool + implements ThreadPool { + + /** By default we use the logger for this class. */ + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + /** The name of this thread pool */ + protected final String name; + + /** The executor. */ + protected ThreadPoolExecutor executor; + + protected final ThreadPoolConfig configuration; + + /** + * Create a new thread pool. + * @param name - The name of the thread pool. If null {@link DefaultThreadPoolManager#DEFAULT_THREADPOOL_NAME} + * is used + */ + public DefaultThreadPool(final String name, + ThreadPoolConfig origConfig) { + this.logger.info("ThreadPool [{}] initializing ...", name); + + // name + if ( name != null ) { + this.name = name; + } else { + this.name = DefaultThreadPoolManager.DEFAULT_THREADPOOL_NAME; + } + + this.configuration = new ThreadPoolConfig(origConfig); + + // factory + final ThreadFactory delegateThreadFactory; + if (this.configuration.getFactory() == null) { + logger.warn("No ThreadFactory is configured. Will use JVM default thread factory." + + ExtendedThreadFactory.class.getName()); + delegateThreadFactory = Executors.defaultThreadFactory(); + } else { + delegateThreadFactory = this.configuration.getFactory(); + } + // Min pool size + if (this.configuration.getMinPoolSize() < 1) { + this.configuration.setMinPoolSize(1); + this.logger.warn("min-pool-size < 1 for pool \"" + name + "\". Set to 1"); + } + // Max pool size + if ( this.configuration.getMaxPoolSize() < 0 ) { + this.configuration.setMaxPoolSize(Integer.MAX_VALUE); + } + + // Set priority and daemon flag + final ExtendedThreadFactory threadFactory = new ExtendedThreadFactory(delegateThreadFactory, this.configuration.getPriority(), this.configuration.isDaemon()); + + // Keep alive time + if (this.configuration.getKeepAliveTime() < 0) { + this.configuration.setKeepAliveTime(1000); + this.logger.warn("keep-alive-time-ms < 0 for pool \"" + name + "\". Set to 1000"); + } + + // Queue + final BlockingQueue<Runnable> queue; + if (this.configuration.getQueueSize() != 0) { + if (this.configuration.getQueueSize() > 0) { + queue = new java.util.concurrent.ArrayBlockingQueue<Runnable>(this.configuration.getQueueSize()); + } else { + queue = new LinkedBlockingQueue<Runnable>(); + } + } else { + queue = new SynchronousQueue<Runnable>(); + } + + RejectedExecutionHandler handler = null; + switch (this.configuration.getBlockPolicy()) { + case ABORT : + handler = new ThreadPoolExecutor.AbortPolicy(); + break; + case DISCARD : + handler = new ThreadPoolExecutor.AbortPolicy(); + break; + case DISCARDOLDEST : + handler = new ThreadPoolExecutor.AbortPolicy(); + break; + case RUN : + handler = new ThreadPoolExecutor.AbortPolicy(); + break; + } + this.executor = new ThreadPoolExecutor(this.configuration.getMinPoolSize(), + this.configuration.getMaxPoolSize(), + this.configuration.getKeepAliveTime(), + TimeUnit.MILLISECONDS, + queue, + threadFactory, + handler); + this.configuration.makeReadOnly(); + this.logger.info("ThreadPool [{}] initialized.", name); + } + + /** + * @see org.apache.sling.commons.threads.ThreadPool#getName() + */ + public String getName() { + return name; + } + + + /** + * @see org.apache.sling.commons.threads.ThreadPool#getConfiguration() + */ + public ThreadPoolConfig getConfiguration() { + return this.configuration; + } + + /** + * @see org.apache.sling.commons.threads.ThreadPool#execute(java.lang.Runnable) + */ + public void execute(Runnable runnable) { + if ( this.executor == null ) { + throw new IllegalStateException("Thread pool " + this.name + " is already shutdown."); + } + if ( runnable != null ) { + this.logger.debug("Executing runnable: {},pool={}", runnable, this.name); + + this.executor.execute(runnable); + } + } + + /** + * @see org.apache.sling.commons.threads.ThreadPool#shutdown() + */ + public void shutdown() { + if ( this.executor != null ) { + if (this.configuration.isShutdownGraceful()) { + this.executor.shutdown(); + } else { + this.executor.shutdownNow(); + } + + try { + if (this.configuration.getShutdownWaitTimeMs() > 0) { + if (!this.executor.awaitTermination(this.configuration.getShutdownWaitTimeMs(), TimeUnit.MILLISECONDS)) { + logger.warn("running commands have not terminated within " + + this.configuration.getShutdownWaitTimeMs() + + "ms. Will shut them down by interruption"); + this.executor.shutdownNow(); + } + } + } catch (final InterruptedException ie) { + this.logger.error("Cannot shutdown ThreadPool", ie); + } + this.executor = null; + } + } +} diff --git a/src/main/java/org/apache/sling/commons/threads/impl/DefaultThreadPoolManager.java b/src/main/java/org/apache/sling/commons/threads/impl/DefaultThreadPoolManager.java new file mode 100644 index 0000000..4ed4811 --- /dev/null +++ b/src/main/java/org/apache/sling/commons/threads/impl/DefaultThreadPoolManager.java @@ -0,0 +1,133 @@ +/* + * 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.sling.commons.threads.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.sling.commons.threads.ThreadPool; +import org.apache.sling.commons.threads.ThreadPoolConfig; +import org.apache.sling.commons.threads.ThreadPoolManager; +import org.osgi.service.component.ComponentContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The DefaultThreadPoolManager implements the {@link ThreadPoolManager} interface + * and is responsible to manage {@link ThreadPool}s. + * + * @scr.component metatype="no" + * @scr.service interface="org.apache.sling.commons.threads.ThreadPoolManager" + * + * @version $Id$ + */ +public class DefaultThreadPoolManager implements ThreadPoolManager { + + /** By default we use the logger for this class. */ + protected Logger logger = LoggerFactory.getLogger(getClass()); + + /** The managed thread pools */ + protected final Map<String, ThreadPool> pools = new HashMap<String, ThreadPool>(); + + /** + * Activate this component. + */ + protected void activate(ComponentContext context) throws Exception { + this.logger.info("Starting thread pool manager."); + final ThreadPool defaultPool = new DefaultThreadPool( + DEFAULT_THREADPOOL_NAME, + new ThreadPoolConfig()); + synchronized ( this.pools ) { + this.pools.put(defaultPool.getName(), defaultPool); + } + this.logger.info("Thread pool manager startet with default pool."); + } + + /** + * Deactivate this component. + */ + protected void deactivate(ComponentContext context) throws Exception { + this.logger.info("Stopping thread pool manager."); + this.logger.debug("Disposing all thread pools"); + + synchronized ( this.pools ) { + for (ThreadPool pool : this.pools.values()) { + this.logger.debug("Shutting down thread pool {}", pool.getName()); + + pool.shutdown(); + + this.logger.debug("Thread pool " + pool.getName() + " is shut down."); + } + this.pools.clear(); + } + this.logger.info("Thread pool manager stopped."); + } + + /** + * @see org.apache.sling.commons.threads.ThreadPoolManager#add(org.apache.sling.commons.threads.ThreadPool) + */ + public boolean add(ThreadPool pool) { + synchronized ( this.pools ) { + if (null != pools.get(pool.getName())) { + return false; + } + pools.put(pool.getName(), pool); + } + return true; + } + + /** + * @see org.apache.sling.commons.threads.ThreadPoolManager#get(java.lang.String) + */ + public ThreadPool get(String name) { + if ( name == null ) { + name = DEFAULT_THREADPOOL_NAME; + } + synchronized (this.pools) { + ThreadPool pool = this.pools.get(name); + if ( pool == null && !(name.equals(DEFAULT_THREADPOOL_NAME))) { + this.logger.info("Requested pool {} is not available, returning default pool.", name); + pool = this.pools.get(DEFAULT_THREADPOOL_NAME); + } + return pool; + } + } + + /** + * @see org.apache.sling.commons.threads.ThreadPoolManager#create(java.lang.String, org.apache.sling.commons.threads.ThreadPoolConfig) + */ + public ThreadPool create(String name, + ThreadPoolConfig config) { + if ( name == null ) { + throw new IllegalArgumentException("Name must not be null."); + } + if ( config == null ) { + throw new IllegalArgumentException("Config must not be null."); + } + synchronized ( this.pools ) { + ThreadPool pool = this.pools.get(name); + if ( pool != null ) { + // pool already exists + return null; + } + pool = new DefaultThreadPool(name, config); + this.pools.put(name, pool); + return pool; + } + } + +} diff --git a/src/main/java/org/apache/sling/commons/threads/impl/ExtendedThreadFactory.java b/src/main/java/org/apache/sling/commons/threads/impl/ExtendedThreadFactory.java new file mode 100644 index 0000000..b213fd8 --- /dev/null +++ b/src/main/java/org/apache/sling/commons/threads/impl/ExtendedThreadFactory.java @@ -0,0 +1,79 @@ +/* + * 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.sling.commons.threads.impl; + +import java.util.concurrent.ThreadFactory; + +import org.apache.sling.commons.threads.ThreadPoolConfig; + + +/** + * This class is responsible to create new Thread instances. + * It's a very basic implementation. + * + * @version $Id$ + */ +public final class ExtendedThreadFactory implements ThreadFactory { + + /** The daemon mode */ + private final boolean isDaemon; + + /** The priority of newly created Threads */ + private final int priority; + + /** The real factory. */ + private final ThreadFactory factory; + + /** + * Create a new wrapper for a thread factory handling the + * + * @param priority A non null value. + * @param isDaemon Whether new {@link Thread}s should run as daemons. + */ + public ExtendedThreadFactory(final ThreadFactory factory, + final ThreadPoolConfig.ThreadPriority priority, + final boolean isDaemon) { + this.isDaemon = isDaemon; + if ( priority == null ) { + throw new IllegalStateException("Prioriy must not be null."); + } + switch ( priority ) { + case NORM : this.priority = Thread.NORM_PRIORITY; + break; + case MIN : this.priority = Thread.MIN_PRIORITY; + break; + case MAX : this.priority = Thread.MAX_PRIORITY; + break; + default: // this can never happen + this.priority = Thread.NORM_PRIORITY; + break; + } + this.factory = factory; + } + + /** + * Invoke the thread factory and set the daemon flag and priority. + * @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) + */ + public Thread newThread( final Runnable command ) { + final Thread thread = this.factory.newThread(command); + thread.setPriority( this.priority ); + thread.setDaemon( this.isDaemon ); + + return thread; + } +} diff --git a/src/main/resources/META-INF/DISCLAIMER b/src/main/resources/META-INF/DISCLAIMER new file mode 100644 index 0000000..90850c2 --- /dev/null +++ b/src/main/resources/META-INF/DISCLAIMER @@ -0,0 +1,7 @@ +Apache Sling is an effort undergoing incubation at The Apache Software Foundation (ASF), +sponsored by the Apache Jackrabbit PMC. Incubation is required of all newly accepted +projects until a further review indicates that the infrastructure, communications, +and decision making process have stabilized in a manner consistent with other +successful ASF projects. While incubation status is not necessarily a reflection of +the completeness or stability of the code, it does indicate that the project has yet +to be fully endorsed by the ASF. \ No newline at end of file diff --git a/src/main/resources/META-INF/LICENSE b/src/main/resources/META-INF/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/src/main/resources/META-INF/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. diff --git a/src/main/resources/META-INF/NOTICE b/src/main/resources/META-INF/NOTICE new file mode 100644 index 0000000..3a4d87e --- /dev/null +++ b/src/main/resources/META-INF/NOTICE @@ -0,0 +1,8 @@ +Apache Sling Threads +Copyright 2008 The Apache Software Foundation + +Apache Sling is based on source code originally developed +by Day Software (http://www.day.com/). + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). -- To stop receiving notification emails like this one, please contact "[email protected]" <[email protected]>.
