Skip to content

Commit

Permalink
enhance: TaskGroup await
Browse files Browse the repository at this point in the history
add: TaskEngine shutdown/shutdownNow methods
format: format codes
add: document
  • Loading branch information
JonZhang3 committed Jun 26, 2023
1 parent 5cc1963 commit 7518f72
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 50 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Maven
<dependency>
<groupId>com.github.jonzhang3</groupId>
<artifactId>aTask</artifactId>
<version>1.1.0</version>
<version>1.2.0</version>
</dependency>
```
#### 示例
Expand Down
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.github.jonzhang3</groupId>
<artifactId>aTask</artifactId>
<version>1.1.1</version>
<version>1.2.0</version>

<name>ATask</name>
<description>A simple multi-purpose asynchronous task execution framework.</description>
Expand Down Expand Up @@ -48,7 +48,7 @@
<dependency>
<groupId>com.github.jonzhang3</groupId>
<artifactId>tuples</artifactId>
<version>1.0.0</version>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
Expand All @@ -60,7 +60,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/atask/AbstractTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public final boolean setState(State expect, State update) {
}

private void setStateToCancel() {
this.state.set(State.CANCLE);
this.state.set(State.CANCEL);
}

@Override
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/com/atask/DefaultThreadPoolExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ThreadFactory;
Expand Down Expand Up @@ -62,7 +61,7 @@ public void submit(Task task) {
}

public void submit(TaskGroup.Item item, TaskGroup group) {
TaskGroup.ItemExecutor executor = new TaskGroup.ItemExecutor(item, group);
TaskGroup.GroupItemExecutor executor = new TaskGroup.GroupItemExecutor(item, group);
RunnableFuture<Object> future = newTaskFor(item, executor);
item.setFuture(future);
item.setState(State.INIT, State.QUEUED);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/atask/Json.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public JsonObject put(String name, Object value) {
}

public JsonObject end() {
if(builder.charAt(builder.length() - 1) == ',') {
if (builder.charAt(builder.length() - 1) == ',') {
builder.deleteCharAt(builder.length() - 1);
}
builder.append("}");
Expand Down Expand Up @@ -64,7 +64,7 @@ public JsonArray add(Object value) {
}

public JsonArray end() {
if(builder.charAt(builder.length() - 1) == ',') {
if (builder.charAt(builder.length() - 1) == ',') {
builder.deleteCharAt(builder.length() - 1);
}
builder.append("]");
Expand Down
33 changes: 15 additions & 18 deletions src/main/java/com/atask/StatViewServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import com.atask.util.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
Expand All @@ -24,15 +22,14 @@ public class StatViewServlet extends HttpServlet {
private String password;



@Override
public void init() throws ServletException {
this.username = getInitParameter(PARAM_NAME_USERNAME);
this.password = getInitParameter(PARAM_NAME_PASSWORD);
if(username == null) {
if (username == null) {
username = "";
}
if(password == null) {
if (password == null) {
password = "";
}
}
Expand All @@ -43,17 +40,17 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) throws
String servletPath = req.getServletPath();
String requestURI = req.getRequestURI();
resp.setCharacterEncoding("UTF-8");
if(contextPath == null) {
if (contextPath == null) {
contextPath = "";
}
String uri = contextPath + servletPath;
String path = requestURI.substring(contextPath.length() + servletPath.length());
// 登录接口,不需要验证
if("/toLogin".equals(path)) {
if ("/toLogin".equals(path)) {
String reqUsername = req.getParameter(PARAM_NAME_USERNAME);
String reqPassword = req.getParameter(PARAM_NAME_PASSWORD);
if(this.username.equals(reqUsername) && this.password.equals(reqPassword)) {
if(requireAuth()) {
if (this.username.equals(reqUsername) && this.password.equals(reqPassword)) {
if (requireAuth()) {
Cookie cookie = new Cookie(USER_KEY, encodeCookieValue());
cookie.setMaxAge(12 * 60 * 60);
resp.addCookie(cookie);
Expand Down Expand Up @@ -93,7 +90,7 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) throws
resp.sendRedirect("index.html");
return;
}
if(path.contains(".json")) {
if (path.contains(".json")) {
String fullUrl = path;
if (req.getQueryString() != null && req.getQueryString().length() > 0) {
fullUrl += "?" + req.getQueryString();
Expand All @@ -110,11 +107,11 @@ private boolean requireAuth() {

private boolean checkUser(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if(cookies != null) {
if (cookies != null) {
for (Cookie cookie : cookies) {
if(USER_KEY.equals(cookie.getName())) {
if (USER_KEY.equals(cookie.getName())) {
String value = cookie.getValue();
if(Utils.isNotEmpty(value)) {
if (Utils.isNotEmpty(value)) {
try {
byte[] bytes = Utils.aesDecode(Base64.getDecoder().decode(value), password);
value = new String(bytes, StandardCharsets.UTF_8);
Expand All @@ -131,15 +128,15 @@ private boolean checkUser(HttpServletRequest request) {

private void returnFile(String fileName, String uri, HttpServletResponse response) throws IOException {
String filePath = RESOURCE_PATH + fileName;
if(fileName.endsWith(".html")) {
if (fileName.endsWith(".html")) {
response.setContentType("text/html; charset=utf-8");
} else if(fileName.endsWith(".css")) {
} else if (fileName.endsWith(".css")) {
response.setContentType("text/css;charset=utf-8");
} else if(fileName.endsWith(".js")) {
} else if (fileName.endsWith(".js")) {
response.setContentType("text/javascript;charset=utf-8");
}
String text = Utils.readFromResource(filePath);
if(text == null) {
if (text == null) {
response.sendRedirect(uri + "/index.html");
return;
}
Expand All @@ -155,7 +152,7 @@ private String process(String url) {
if (url.equals("/basic.json")) {
return TaskStatService.INSTANCE.getBasicInfo();
}
if(url.equals("/tasks.json")) {
if (url.equals("/tasks.json")) {
return TaskStatService.INSTANCE.getTaskInfo();
}
return "";
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/atask/State.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

public enum State {

UNKNOW("未知", -1),
UNKNOWN("未知", -1),
INIT("初始化", 0),
QUEUED("等待队列中", 1),
RUNNING("执行中", 2),
CANCLE("取消", 3),
CANCEL("取消", 3),
SUCCESS("执行成功", 4),
ERROR("执行失败", 5),
TIMEOUT("超时", 6);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/atask/Task.java
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public Builder progress(Progress progress) {
}

/**
* 设置任务完成时的回调,可以很实用 {@link Context#onSuccess(Object...)}、{@link Context#onError(String, Object)} 或
* 设置任务完成时的回调,可以使用 {@link Context#onSuccess(Object...)}、{@link Context#onError(String, Object)} 或
* {@link Context#onError(Exception)} 触发该回调。
* <p>
* 如果调用 {@link Context#onSuccess(Object...)} 触发回调,任务状态为成功 {@link State#SUCCESS},并且回调函数的第二个参数
Expand Down
38 changes: 37 additions & 1 deletion src/main/java/com/atask/TaskEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public final class TaskEngine {
private static final int DEFAULT_CORE_SIZE = Runtime.getRuntime().availableProcessors();
private static final int DEFAULT_MAX_POOL_SIZE = Integer.MAX_VALUE;
private static final int DEFAULT_QUEUE_CAPACITY = Integer.MAX_VALUE;
private static final int DEFAULT_KEEP_ALIVE_SECONDS = 60;//S
private static final int DEFAULT_KEEP_ALIVE_SECONDS = 60;// S
private static final String DEFAULT_TASK_GROUP_NAME_PREFIX = "atask-group-";

private final AtomicLong taskGroupNumber = new AtomicLong(0);
Expand Down Expand Up @@ -53,10 +53,21 @@ public Task.Builder buildTask(Executor executor) {
return new Task.Builder(executor);
}

/**
* 使用默认的任务组名称初始化一个任务组
*
* @return {@link TaskGroup}
*/
public TaskGroup prepareGroup() {
return this.prepareGroup(DEFAULT_TASK_GROUP_NAME_PREFIX + taskGroupNumber.incrementAndGet());
}

/**
* 初始化一个任务组,可自定义任务组名称
*
* @param name 任务组的名称
* @return {@link TaskGroup}
*/
public TaskGroup prepareGroup(String name) {
TaskGroup taskGroup = new TaskGroup(name, executor);
executor.addTaskGroup(taskGroup);
Expand Down Expand Up @@ -119,6 +130,31 @@ public void shutdown() {
this.executor.shutdown();
}

/**
* 试图关闭线程池,同时阻塞等待线程池关闭
*
* @param timeout 超时时间
* @param unit 超时时间的时间单位
* @return {@code true} 线程池正常关闭;如果到达超时时间后,线程池仍未关闭,返回 {@code false}
* @see ThreadPoolExecutor#shutdown()
* @see ThreadPoolExecutor#awaitTermination(long, TimeUnit)
* @since 1.2.0
*/
public boolean shutdown(long timeout, TimeUnit unit) throws InterruptedException {
this.executor.shutdown();
return this.executor.awaitTermination(timeout, unit);
}

/**
* 立即关闭线程池
*
* @see ThreadPoolExecutor#shutdownNow()
* @since 1.2.0
*/
public void shutdownNow() {
this.executor.shutdownNow();
}

public List<Task> getRunningTasks() {
return executor.getRunningTasks();
}
Expand Down
Loading

0 comments on commit 7518f72

Please sign in to comment.