I think I just am not seeing something as I’ve gotten this to work in the past.
My lock isn’t holding an exclusive lock, and when a new instance of the object is created, tryLock returns true and another TimerTask is scheduled.
public class A {
private static Timer timer = new Timer();
private static Lock clean_lock = new ReentrantLock();
private static ConcurrentHashMap<String,B> _b_dict = new ConcurrentHashmap<String,B>();
public A() {
if(clean_lock.tryLock()) {
timer.scheduleAtFixedRate(new TimerTaskThread(), new Date(), 60000);
}
}
//Various NON static methods
// use an iterator at one point so they must be NON static
class TimerTaskThread extends TimerTask {
public void run() {
//delete old stuff in _b_dict
}
}
}
//sample usage
public class Main {
public Main() {
A a = new A();
a.contains(new B());
}
}
Are you creating the other
Ainstance from another thread? Because if you’re creating both instances from the same thread, then, the lock being reentrant,tryLockobviously returns true.If you really want to schedule from the constructor, and not from a static block, you should use a static
AtomicBooleanvariable and only schedule the timer ifcompareAndSet(false, true)returns true.