There is no way to do exactly what you said (check whether other threads are inside of a method directly).
However, this sounds like a classic case for synchronization. Make the method invocation synchronize on some object's monitor; make your cleanup code synchronize on the same monitor, and voila! Now, if any thread is running the method(s) that you've made synchronized, your cleanup code can't run, but will wait until all threads have exited the methods and will then proceed.
Here's an example:
public class Foo
{
private final Object LOCK = new Object();
public void importantMethodOne()
{
synchronized(LOCK)
{
// Method body here
}
}
public void importantMethodTwo()
{
synchronized(LOCK)
{
// Method body here
}
}
public void otherMethod()
{
// Method body here
}
public void cleanupMethod()
{
synchronized(LOCK)
{
// Method body here
}
}
}
The LOCK monitor is a mutex - only one thread can hold it at once, so only one thread can be calling any of importantMethodOne, importantMethodTwo or the cleanupMethod at once. Any threads that try to invoke any of these methods while another is within the scope (and thus has the lock) will wait. In this example, otherMethod can be called at any time without interrupting anything else, because it doesn't acquire the lock.
Note that in this case, two threads cannot execute myMethod() at once because they'll block each other. If this is an issue, you can get around this with a ReadWriteLock (which allows many "readers" to hold it at once but one "writer"). If you acquire the read lock for your "normal" methods and the write lock for your "cleanup" methods, this will have the desired semantics.