简体   繁体   中英

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. Then Use an mdb to process the queue.

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?

Edit: forgot to mention I don't really need the features of jms (reliability etc).

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

Based on conversation in comment, i came to know you have to use this in Java-EE environment. As you said you have to use ManagedExecutorService . How ever you dont need to use singleton Ejb and ConcurrentLinkedQueue.

You can implement you Jobs as Callable and you can block further processing using Future.get()

String name = managedService.submit(iterator.next()).get();

From API

    If you would like to immediately block waiting for a task, 
you can use constructions of the form result = exec.submit(aCallable).get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM