I am trying to code a BitTorrent client in Java just for practice. For tracker connections, I am using the URLs in announce-list
field of torrent file. To actually communicate with trackers, I used java nio (DatagramChannel and selectors) rather than threads and it is working. However, as per torrent specifications, requests are re-transmitted every 15 * 2^n
seconds if corresponding responses are not received. When I searched for solutions to this through NIO
, I was unable to find any. However, I found many references to Timer
and TimerTask
classes. So my question is: Should I use NIO
or use TimerTask
for scheduling tracker request sending? If the answer is NIO
, how to achieve the re-transmission thing using NIO
?

- 185
- 2
- 9
2 Answers
perhaps use a ScheduledExecutorService
to trigger the delayed tasks and perform the actions using NIO? This has some advantages over TimerTask
. You can keep using NIO to avoid blocking on the network I/O portion of your app.

- 50,847
- 7
- 72
- 76
Blocking (thread per connection) vs. non-blocking (selectors + channels in non-blocking mode) and task scheduling are orthogonal.
The blocking mode of IO is about how your threads interact with sockets once they have been set up, about throughput, latency, parallelism and also code complexity. Blocking IO is relatively simple and can easily provide high throughput. Non-blocking IO (at least java.nio
without supporting abstracts that simplify it) can be fairly complex but can handle more connections in parallel without exploding the thread count of your process.
Task scheduling on the other hand is for designing application logic before the IO happens, e.g. deciding to defer a task for an hour before opening the next connection, without having to dedicate an entire thread to just sleeping for an hour.
Since you're probably only going to handle a handful of HTTP connections at a time blocking IO, i.e. a simple HTTP client such as HttpURLConnection
may be entirely sufficient. But if you're using Java 11 or later you may as well use the java.net.http.HttpClient
API which does use NIO under the hood while handling most of the complexity for you.
In either case deferring the next announce can be done through either Timer
or a ScheduledExecutorService
.

- 40,999
- 5
- 70
- 122