Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java techniques for end-of-lifetime of objects

Tags:

java

Experienced programmer new to Java seeking your wisdom:

If there is no way to ensure that some particular chunk code is executed as an object goes out of scope, then what other approaches are there that would offer the same functionality? (it seems finalize is clearly not meant for that)

A classic example is the scoped lock idiom:

void method()
{
    // Thread-unsafe operations {...}

    { // <- New scope
        // Give a mutex to the lock
        ScopedLock lock(m_mutex);

        // thread safe operations {...}

        if (...) return; // Mutex is unlocked automatically on return

        // thread safe operations {...}

    } // <- End of scope, Mutex is unlocked automatically

    // Thread-unsafe operations {...}
}

I can understand that in Java it would be frowned upon to have some code executed if you haven't explicitly called it. But I find being able to enforce some code to be executed at the end of an object's lifetime is a very powerful feature to ensure your classes are being used sensibly by client code. Thanks

like image 460
user1659313 Avatar asked Aug 20 '13 13:08

user1659313


People also ask

What is the last stage in an object life cycle?

Objects are persistent, meaning they exist in memory until you destroy them. We can break the life of an object into three phases: creation and initialization, use, and destruction.

What is the lifetime of an object in Java?

It would live until at least the start() method finished executing, there is no guarantee about object lifetimes in Java since memory is managed by the garbage collecter and not the programmer.

How do you terminate an object in Java?

You can delete an object in Java by removing the reference to it by assigning null. After that, it will be automatically deleted by the Garbage Collector.

How does Java know that an object is no longer needed?

Java uses a technique known as garbage collection to remove objects that are no longer needed. The garbage collector is Java's grim reaper. It lingers in the background, stalking objects and awaiting their demise. It finds and watches them, periodically counting references to them to see when their time has come.


2 Answers

Generally - if you have a need to actually close/dispose of resources then using a try{} finally{} structure is encouraged.

  // The old way - using try/finally
  Statement stmt = con.createStatement();
  try {
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next()) {
      // ...
    }
  } catch (SQLException e) {
    // Whatever ... .
  } finally {
    // Be sure to close the statement.
    if (stmt != null) {
      stmt.close();
    }
  }

More recent incarnations of java have the AutoCloseable interface which you can use with the with mechanism. All Closeable objects are automatically AutoCloseable.

  // Example of what is called try-with
  try (Statement stmt = con.createStatement()) {
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next()) {
      // ...
    }
  } catch (SQLException e) {
    // Whatever ... stmt will be closed.
  }
like image 182
OldCurmudgeon Avatar answered Oct 08 '22 00:10

OldCurmudgeon


As of Java 7 there is the Automatic Resource Management. If your lock is under your control, then make it implement AutoCloseable. Unfortunately, the java.util.concurrent locks do not implement this interface. Here's a good reference to the details of that.

like image 34
Marko Topolnik Avatar answered Oct 07 '22 23:10

Marko Topolnik