ttt
ttt

Reputation: 4004

Java Thread, how to release resource when thread is done

I have a java class which extends from Thread and for example I want to send message to a queue, but want to reuse Producer for each thread. Not close it until Thread is done.

public class Producer extends Thread {
    private final QueueProducer producer;

    public Producer() {
        Properties props = new Properties();
        producer = new QueueProducer(props);
    }

    public void send(String message) {
        producer.send(message);
    }

    // close?
}

For this piece of code how can I call the close method?

Upvotes: 0

Views: 3267

Answers (1)

Awan Biru
Awan Biru

Reputation: 490

If QueueProducer does not implement Closeable and does not provide method to close its resources, then you can't close it explicitly. Best way is by limiting its scope inside run method hence eligible for GC.

However if it does AutoCloseable or Closeable, then wrap QueueProducer with try-with-resources block to automatically close it after its usage.

public void run(){

    try(QueueProducer qp = producer){
        //do operation on qp
    }
}

Or make Producer to implement Closeable. In its overriden close method will close QueueProducer instead. For example:-

class Producer extends Closeable{

   private final QueueProducer qp;

   ....

   @Override
   public void close(){

      if(qp!=null){
         qp.close();
      }
   }
}

This is similar to BufferedReader whom its close method close its internal Reader object. Thus QueueProducer remain usable until client close Producer itself.

Upvotes: 1

Related Questions