[英]serial execution in Java-ee
I have some incoming concurrent requests that should be processed in serial. 我有一些传入的并发请求,应该串行处理。 I have attempted to achieve this by converting the requests to messages and post to a jms queue.
我试图通过将请求转换为消息并将其发布到jms队列来实现这一点。 Then Use an mdb to process the queue.
然后,使用mdb处理队列。
Using vendor specific config, I understand I can limit mdb to one instance, but what is the recommended and portable way to solve this problem? 使用供应商特定的配置,我知道可以将mdb限制为一个实例,但是解决此问题的推荐且可移植的方法是什么?
Edit: forgot to mention I don't really need the features of jms (reliability etc). 编辑:忘了提我真的不需要jms的功能(可靠性等)。
Assume you have Job like this. 假设您有这样的工作。
class LogJob implements Runnable{
private final String name;
public LogJob(String name){
this.name = name;
}
@Override
public void run() {
System.out.println(" Starting ."+name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(" End ."+name);
}
}
It is just display starting and ending Job. 它只是显示开始和结束作业。 Placed sleep for demo
放置睡眠进行演示
Create a list of Jobs 创建工作清单
ArrayList<LogJob> jobs = new ArrayList<LogJob>();
for ( int i=0;i<10;i++){
LogJob job = new LogJob("Job"+i);
jobs.add(job);
}
Let see how to process in serial 让我们看看如何串行处理
ExecutorService singleThread = Executors.newSingleThreadExecutor();
for (Iterator<LogJob> iterator = jobs.iterator(); iterator.hasNext();) {
singleThread.execute(iterator.next());
}
singleThread.shutdown();
This will provide an output. 这将提供输出。
Starting .Job0
End .Job0
Starting .Job1
End .Job1
Starting .Job2
End .Job2
Starting .Job3
End .Job3
Starting .Job4
End .Job4
Starting .Job5
End .Job5
Starting .Job6
End .Job6
Starting .Job7
End .Job7
Starting .Job8
End .Job8
Starting .Job9
End .Job9
UPDATE UPDATE
Based on conversation in comment, i came to know you have to use this in Java-EE environment. 基于评论中的对话,我知道您必须在Java-EE环境中使用它。 As you said you have to use
ManagedExecutorService
. 如您所说,您必须使用
ManagedExecutorService
。 How ever you dont need to use singleton Ejb and ConcurrentLinkedQueue. 您无需使用单例Ejb和ConcurrentLinkedQueue。
You can implement you Jobs as Callable and you can block further processing using Future.get() 您可以将Jobs实施为Callable,也可以使用Future.get()阻止进一步处理
String name = managedService.submit(iterator.next()).get();
If you would like to immediately block waiting for a task,
you can use constructions of the form result = exec.submit(aCallable).get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.