1

I have a infinite loop where I create an object. At the end of the loop, after creating the object I run it. When running the object the program will block because I have another infinite loop in my TcpClient-object. But sometimes this infinite loop will break because of an handled error, and will call a specific method in my mTcpClient-Object called "reconnect". There I would like to delete the mTcpClient object, so that the first infinite loop will go on and create a new mTcpClient-object.

How can I do this?

while(true) {

    //we create a TCPClient object and
    mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
        @Override
        public void reconnect() {
            // HERE I want to delete this object
        }
    ....
   });

    if (mTcpClient != null)
        mTcpClient.run();
}
5
  • You can't manually delete an object in Java. Can you clarify what you mean by deleting the object? Commented May 17, 2015 at 13:22
  • It would be helpful if you show your full program, but as much I understand your question, you can't delete objects when you want. It is done automatically when the garbage collector will check for unused objects. If you want to do something while TcpClient's garbage collection, you can override protected void finalize() method of Object. Commented May 17, 2015 at 13:22
  • 1
    @Ved Recommending finalizers is nearly always bad advice. Commented May 17, 2015 at 13:23
  • 1
    @texNewbie Its very likely that your overal design is flawed. Post more code. Commented May 17, 2015 at 13:33
  • @chrylis, True, using protected void finalize() is not good, and it does not promise that the object would be garbage collected. But to free any resources loaded through native methods, using finalize() is one way. Commented May 19, 2015 at 9:37

1 Answer 1

1

mTcpClient = null; Setting an object to null will cause the garbage collector to delete the object for you.

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

2 Comments

What you are suggesting is not possible. mTcpClient won't be accessible within the anonymous inner class. Try it out.
I tried, I think this could work. But I have to check a few things until I know if this is the solution for my problem.

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.