3

The consensus, when it comes to multi-threading & concurrency in Java-land, is to isolate the code you want multi-threaded as a "task" and to submit that task to some kind of executor service or thread pool.

What I'm wondering is:

  • Can a task be any method of any object, or does it have to be something special (if so, what)?
  • How do you determine whether this task is CPU-, IO-bound or other? What are some "dead giveaways" or other deciding factors?

Thanks in advance for any clarity here!

3
  • 2
    the way you determine whether your code is io or cpu bound is to run it in a profiler. anything else is just guessing and, usually, wrong. Commented May 2, 2012 at 0:45
  • @jtahlborn - well, if the task contains a DNS lookup and then a download from a web site, that does give a clue that it's going to be I/O bound. That's not a guess ;) Commented May 2, 2012 at 12:29
  • @MartinJames - still a guess. could be a download from another computer on the same lan (or a really small file), and then some crazy computation on the result. Commented May 2, 2012 at 14:25

3 Answers 3

2

Take a look at ExecutorService:

  • submit(Callable)
  • submit(Runnable)

Your task should probably be one of the two interfaces (which can always call other methods).

Your task is probably IO bound if you perform any input/output operations within it: IE, reading to a file, writing to a file, reading from a socket, writing to a socket, etc.

Sign up to request clarification or add additional context in comments.

2 Comments

So, an ExecutorService just calls the task's run() or call() method (whichever is applicable) and then whatever the definition of that method is determines what the task is bound by? Is that a fair generalization?
@AdamTannon That just about sums it up. Take a look at jtahlborn's comment on your original question too.
0

Threads usually execute the code they find in a class that implements Runnable.

Comments

0

Can a task be any method of any object, or does it have to be something special (if so, what)?

It can be anything. The big problem is that your task will probably include some objects which are shared with other threads. You must make sure that access to those objects is thread-safe. That is a complex topic; "Java Concurrency in Practice" by Goetz et al is a very good book.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.