Concurrency Utilities for Java EE sample:
/**
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://java.net/projects/javaeetutorial/pages/BerkeleyLicense
*/
package javaeetutorial.concurrency.jobs.service;import java.util.UUID;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;/**
* @author ito
*/
@Stateless
@Path("/JobService")
public class JobService { private final static Logger logger = Logger.getLogger(JobService.class.getCanonicalName());
// http header to check for valid tokens
private final static String API_TOKEN_HEADER = "X-REST-API-Key";
@Resource(lookup = "MES_High")
private ManagedExecutorService highPrioExecutor;
@Resource(lookup = "MES_Low")
private ManagedExecutorService lowPrioExecutor; @EJB
private TokenStore tokenStore; @GET
@Path("/token")
public Response getToken() {
// static token + dynamic token
final String token = "123X5-" + UUID.randomUUID().toString();
tokenStore.put(token);
return Response.status(200).entity(token).build();
} @POST
@Path("/process")
public Response process(final @HeaderParam(API_TOKEN_HEADER) String token,
final @QueryParam("jobID") int jobID) { try {
if (token != null && tokenStore.isValid(token)) {
logger.info("Token accepted. Execution with high priority.");
highPrioExecutor.submit(new JobTask("HIGH-" + jobID));
} else {
logger.log(Level.INFO, "Invalid or missing token! {0}", token);
// requests without token, will be executed but without priority
lowPrioExecutor.submit(new JobTask("LOW-" + jobID));
}
} catch (RejectedExecutionException ree) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Job " + jobID + " NOT submitted. " + ree.getMessage()).build();
} return Response.status(Response.Status.OK).entity("Job " + jobID + " successfully submitted.").build();
} static class JobTask implements Runnable { private final String jobID;
private final int JOB_EXECUTION_TIME= 10000; public JobTask(String id) {
this.jobID = id;
} @Override
public void run() {
try {
logger.log(Level.INFO, "Task started {0}", jobID);
Thread.sleep(JOB_EXECUTION_TIME); // 5 seconds per job
logger.log(Level.INFO, "Task finished {0}", jobID);
} catch (InterruptedException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
}
/**
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://java.net/projects/javaeetutorial/pages/BerkeleyLicense
*/
package javaeetutorial.concurrency.jobs.service;import java.util.UUID;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;/**
* @author ito
*/
@Stateless
@Path("/JobService")
public class JobService { private final static Logger logger = Logger.getLogger(JobService.class.getCanonicalName());
// http header to check for valid tokens
private final static String API_TOKEN_HEADER = "X-REST-API-Key";
@Resource(lookup = "MES_High")
private ManagedExecutorService highPrioExecutor;
@Resource(lookup = "MES_Low")
private ManagedExecutorService lowPrioExecutor; @EJB
private TokenStore tokenStore; @GET
@Path("/token")
public Response getToken() {
// static token + dynamic token
final String token = "123X5-" + UUID.randomUUID().toString();
tokenStore.put(token);
return Response.status(200).entity(token).build();
} @POST
@Path("/process")
public Response process(final @HeaderParam(API_TOKEN_HEADER) String token,
final @QueryParam("jobID") int jobID) { try {
if (token != null && tokenStore.isValid(token)) {
logger.info("Token accepted. Execution with high priority.");
highPrioExecutor.submit(new JobTask("HIGH-" + jobID));
} else {
logger.log(Level.INFO, "Invalid or missing token! {0}", token);
// requests without token, will be executed but without priority
lowPrioExecutor.submit(new JobTask("LOW-" + jobID));
}
} catch (RejectedExecutionException ree) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Job " + jobID + " NOT submitted. " + ree.getMessage()).build();
} return Response.status(Response.Status.OK).entity("Job " + jobID + " successfully submitted.").build();
} static class JobTask implements Runnable { private final String jobID;
private final int JOB_EXECUTION_TIME= 10000; public JobTask(String id) {
this.jobID = id;
} @Override
public void run() {
try {
logger.log(Level.INFO, "Task started {0}", jobID);
Thread.sleep(JOB_EXECUTION_TIME); // 5 seconds per job
logger.log(Level.INFO, "Task finished {0}", jobID);
} catch (InterruptedException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
}
}
解决方案 »
- 使用Hibernate注解自动创建表报错
- 在增删改方法中如果没有返回值,如何给用户友好的提示?
- javascript 打印问题
- urlrewrite如何重写struts1
- JAVA中数组越界有哪几种情况?请大侠帮忙!!
- 我用java调用java写的webservice时出现错误,急。。。。。。
- 大家有好的j2ee源码网址么
- JSP群招兵买马,群号:11588934
- 在apache soap作的web service中如何调用第三方的类包?比如ojdbc.jar
- Spring MVC jquery upload控件跳转问题
- 关于Spring定时器配置时间的问题!!!
- android手机数据线连接电脑,手机里相片看不到,必须在重启之后才能看到
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://java.net/projects/javaeetutorial/pages/BerkeleyLicense
*/
package javaeetutorial.concurrency.jobs.service;import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;/**
* @author ito
*/
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@Singleton
public class TokenStore implements Serializable { private final List<String> store; public TokenStore() {
this.store = new ArrayList<>();
} @Lock(LockType.WRITE)
public void put(String key) {
store.add(key);
} @Lock(LockType.READ)
public boolean isValid(String key) {
return store.contains(key);
}
}
你说的线程池指的是什么?怎么实现?
怕说的不详细,百度了下,这个比较详细 http://www.cnblogs.com/riskyer/p/3263032.html
如果对线程比较了解,只想看线程池部分,可以直接看“Java线程:新特征-线程池”章节