java – Why can't streams be reused?

Question:

The question may be stupid, but still … Why can't you reuse streams?

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Answer:

There would be no tangible benefit to reusing streams. On the contrary, restarting threads would be inconvenient for programmers:

  1. If a thread can be run twice, then it can be run twice from multiple threads. However, it is unclear whether client threads need to be notified of the "dual" state of the subject thread.

  2. Tracking the state of a thread is meaningless. The stream will never truly terminate because can restart itself or be restarted by another thread.

Accessing shared resources is a major problem in multithreaded programming. One-shot streams in Java are easier to understand because they are allow the virtual machine to take over the synchronization of the state changes of threads.

Probably, technical arguments can also be made: the virtual machine uses operating system threads, for which restart can be limited. But simplifying the client code is a strong enough argument in and of itself.

PS You can reuse Runnable objects. It is enough to implement the interface and create threads as needed:

Runnable myRunnable = new MyRunnableObject();
new Thread(myRunnable).start();
//синхронизация внутреннего состояния MyRunnableObject по вкусу
new Thread(myRunnable).start();
...
Scroll to Top