5

I'm writing a simple Swing GUI which includes a text field which prints debug messages and exceptions. I currently have it set up where I write to a PipedOutputStream, and I have a daemon thread which reads from the connected PipedInputStream and writes to the text area.

While I was trying to figure out how to close the stream in my daemon thread, I came across another answer which says that daemon threads should not hold any resources. Do piped streams count? Do they need to be closed?

Dimpl
  • 935
  • 1
  • 10
  • 24
  • You should close anything that is closeable. – user207421 May 28 '17 at 05:42
  • @EJP The reason I asked the question is because I don't know how to do this. I don't believe daemon threads have defined shutdown behaviour? I think you can add shutdown hooks, but if this was important, I feel like it would be baked in. – Dimpl Jun 01 '17 at 09:26

1 Answers1

4

A PipedInputStream / PipedOutputStream do not hold any operating system resources. So any advice that says that daemon threads should not hold resources does not apply here. (But see below!)

However, this doesn't mean that you don't ever need to close() (at least) the PipedOutputStream. Depending on your application, the corresponding PipedInputStream may need the pipeline to be closed to complete its work.


Regarding the other answer:

After looking at the Answer and the comments, I think that his argument is an over-generalization:

  • He is correct that anything (daemon thread or whatever) that has lots (he says "hundreds") of resources open at the same time is a bad idea.

  • He is also correct in saying that doing critical file updates in a daemon thread is risky. But doing critical file updates in any thread in Java has the same risk1. Or in C. You just need to design the update sequence to be fail-safe ... or rely on something like DB transactions for fail-safety.

However, it is not logically sound (or pragmatically sensible) to generalise this to saying that daemon threads shouldn't hold resources. Clearly there are use-cases where the above concerns do not apply.


1 - The application may get a "kill -9" which will cause it to exit immediately without running the shutdown hooks. The application may get a "file system full" in the middle of the critical update. The power may go off. And so on ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216