#Does this class cause problems in multithreading?

23 messages · Page 1 of 1 (latest)

torpid flare
#
public abstract class ObjectCache<T> {
  protected volatile T object;

  protected int expireAt = 0;

  private final ReentrantLock mutex = new ReentrantLock(true);

  public abstract T create();

  protected abstract int getExpireSeconds();

  public T get()
  {
    if(mutex.isLocked() && this.object != null)
    {
      return this.object;
    }

    mutex.lock();
    try
    {
      int unixTimestamp = (int) (System.currentTimeMillis() / 1000L);
      if(expireAt < unixTimestamp)
      {
        this.expireAt = (int) unixTimestamp + getExpireSeconds();
        this.object = create();
      }
    }
    finally
    {
      mutex.unlock();
    }
    return this.object;
  }
}

Does this class cause multithreading problems?

slim cedarBOT
#

This post has been reserved for your question.

Hey @torpid flare! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

median wren
#

Yes

torpid flare
#

and how can i solve it?

median wren
#

Because of if(mutex.isLocked() && this.object != null)

#

add me fl btw

torpid flare
#

worst case will enter the mutex again and get the real value.

#

In other words, I only care about the object being null, as long as it is not null, at most it will enter the mutex again.

#

I have already calculated it and wrote it like this, 1-2 threads entering the mutex will not cause any problems.

median wren
#

Your class is not thread safe

#

whatever you calculated

torpid flare
median wren
#

"Check-then-act. " Part is important for you

upbeat sailBOT
#

if(mutex.isLocked() && this.object != null) { return this.object; } is a mistake

This message has been formatted automatically. You can disable this using /preferences.

torpid flare
median wren
#

volatile not solve your race condition

#

You checked the link I posted?

#

Check-then-act Part of it

#

If you need more explaination write here