Take the 2-minute tour ×

I'm writing a java GUI that performs certain operations through the serial port. Since I don't want it to block while waiting for a response I figured having a thread do it was a better way, but now I'm faced with two options and I don't know which would be more efficient:

  • Case 1: Create a single thread for each asynchronous task.
  • Case 2: Keep a single thread sleeping and have it perform different tasks by changing an atomic integer's value and then interrupting it.

None of these operations will be processor intensive, but I still wonder if it's wise to keep a thread in memory permanently.

share|improve this question
There is a Case 3: have a third thread waiting, not sleeping. You need to use wait()/notify(). The best solution depends on the number of simultaneous tasks than eventually can be processed at the same time. But assuming you serial port is not really fast, with 2 threads is enough. –  logoff Oct 9 '12 at 10:10
'I still wonder if its wise to keep a thread on memory permanently' - if there were no threads in memory, you could not do anything at all in your app because there would be no execution. –  Martin James Oct 9 '12 at 10:15
In theory there will be no simultaneous tasks since the communication is established for a very short period of time. Still, I want to know if there's a best practice or if these are just different yet valid options. @Martin James what I meant by that, was a thread other than the main one. –  rodkarom Oct 9 '12 at 10:16
What kind of operations? Synchronous request/response or something more complex? –  Martin James Oct 9 '12 at 10:16
@rodkarom - you cannot just keep the serial port open, then? –  Martin James Oct 9 '12 at 10:17
show 2 more comments

2 Answers

up vote 2 down vote accepted

I would use a single threaded ExecutorService like

private final ExecutorService service = Executors.newSingleThreadExecutor();

service.submit(new Runnable() {
   public void run() {
       // task to perform here.

You may want a different thread for reading and writing to the serial device.

share|improve this answer
+1 for Correction. –  AmitD Oct 9 '12 at 10:19
Are tasks queued or something like that? –  rodkarom Oct 9 '12 at 10:25
Yes tasks will be queued.And will be executed in the order you have submitted them if you use SingleThreadedPool. –  AmitD Oct 9 '12 at 10:27
add comment

Have a look at ExecutorService, I guess this is all what you need.

As suggested by Peter you can create ExecutorService using newSingleThreadExecutor and use it to process your tasks.

share|improve this answer
There is a risk that the serial device is access by more than one thread or in an unexpected order than one thread at a time if you create multiple threads. –  Peter Lawrey Oct 9 '12 at 10:15
@PeterLawrey Yes. corrected. –  AmitD Oct 9 '12 at 10:19
add comment

Your Answer


