Is there any better alternative to busy waiting in this case?

1.5k Views Asked by At

I have a Manager class that encapsulates a (rather) low-level facility (e.g. database) and serves as a factory for Worker instances, which

  • use Manager's underlying facility (database)
  • reference Manager from each instance
  • are used concurrently
  • can launch asynchronous tasks which refer to the database (in some detached thread).

The Manager also has a shutdown() method that closes the database connection. To ensure that the connection will stay alive if there are any running threads launched by any worker (i.e. not to close database connection until there are still workers using it), I currently have something like this:

Manager mgr   = new Manager(database);
Worker worker = mgr.newWorker(arg0, arg1, arg2);

worker.runHeavyComputation();

where runHeavyComputation is defined like this:

void runHeavyComputation() {
    executor.execute(() -> {
        myManager.tellTaskLaunched();
        doSomethingWithDatabase();
        myManager.tellTaskFinished();
    });
}

where Manager#tellTaskLaunched() and Manager#tellTaskLaunched() are defined like this:

void tellTaskLaunched() {
    taskCounter.incrementAndGet();
}

void tellTaskFinished() {
    taskCounter.decrementAndGet();
}

and Manager#shutdown() looks like this:

void shutdown() {
    while (taskCounter.get() > 0) {}
    databaseConnection.close();
    database.shutdown()
}

I understand that this is a kinda lengthy introduction for such a simple question, but since I have encountered anti-busy-waiting statements almost in every book or post I've read, it occurs to me that there might be some alternatives to the simple solution I provide here, so I'd like to hear your opinions.

Note that since the shutdown() is likely to be called once per application lifecycle (or whatever it is they call a single long run), it isn't really a performance issue. However, I still would change it if something better comes up.

P.S. Note as well that although I said "your opinions", it's not really an opinion-based question :)

1

There are 1 best solutions below

1
On

There is ALWAYS a better alternative to busy-waiting, at anything above the OS level.

See, for example, the wait and notify operations on Thread.