#Does this class cause problems in multithreading?

1 messages · Page 1 of 1 (latest)

flat kayak
#
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?

worn fieldBOT
# flat kayak ```java public abstract class ObjectCache<T> { protected volatile T object; ...

Detected code, here are some useful tools:

Formatted code
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;
  }
}
#

<@&987246399047479336> please have a look, thanks.

worn fieldBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

w ReentrantLock();

public T getObject() {
if (object == null || System.currentTimeMillis() >= expireAt) {
mutex.lock();
try {
if (object == null || System.currentTimeMillis() >= expireAt) {
object = createObject();
expireAt = calculateExpireAt();
}
} finally {
mutex.unlock();
}
}
return object;
}

protected abstract T createObject();

protected abstract int calculateExpireAt();
}