Java concurrency questions threads vs executorservice

I have been trolling the net the whole day. Without a real answer. I'm hoping that someone can give me some advice.

What I am trying to do build is an auto buyer type application that will need to to poll auctions and check if items I want to purchase become available.

So conceptually I'm thinking that I should be able to start a thread that runs all the time (until I tell it to stop)

And when it finds an item it should start another thread that either bids or buys the item.

I have the code all done that does the mechanics its just the threading I am stuck with.

The first issue is i have been able to start threads using thread /runnable and also using execution services

But in all instances I don't know how to get the thread to continue processing..... And then allow me to issue some sort of command that will stop the thread when I want to stop the program...

Some guidance would be much appreciated

Upvotes: 2

Views: 1392

Answers (1)

Petro Semeniuk
Petro Semeniuk

Reputation: 7038

As I understand you have next in mind:

  1. Have thread which polls from time to time some service in order to find bargains
  2. If found then another thread should be spawned for this concrete item for doing bidding, buying and pissing off other other buyers who don't have such a great tool.
  3. Stopping particular thread if you don't want to buy item anymore.

All of these could be implemented by your own thread framework using JVM thread primitives(and it would be a lot of fun to do so!). However I'd recommend to use Spring Framework for that. Task Execution and Scheduling explains in detail how you can do that. In essence:

  • Want to have some method executed periodically? Just put @Scheduled on it! (Addresses #1)
  • Want to have some method executed in asynchronous manner? Put @Async!(Addresses #1)
  • Regarding #3 - cancelling/stopping threads is problem by its own. Take a look into this question/answer. The best(and recommended) way I found so far is to use a shared variable in memory or some value in database (if application runs in distributed environment) as a flag which asks the background thread to stop.

As simple as it sounds you still need to understand what's going on under-hood and learn a bit about spring. Also @Sheculed/@Async tasks are executed in two different thread pools and you might want to update default size values for them - lesson I've learned only after production deployment :-)

Upvotes: 1

Related Questions