Attempted to make cache system thread compatible.

This commit is contained in:
Harrison Deng 2020-04-24 15:08:03 -05:00
parent 88c645e2a5
commit 8acc653b5b
4 changed files with 23 additions and 7 deletions

View File

@ -14,7 +14,7 @@ public class Cache <CacheValueType> {
this.maxCacheSize = maxCacheSize;
}
public CacheValue<CacheValueType> retrieveCache(Identifier identifier) {
public synchronized CacheValue<CacheValueType> retrieveCache(Identifier identifier) {
if (dataCache.containsKey(identifier)) {
ids.remove(identifier);
dataCache.get(identifier);

View File

@ -1,9 +1,9 @@
package ca.recrown.islandsurvivalcraft.caching;
public class CacheValue <ValueType> {
private ValueType value;
private volatile ValueType value;
protected final Identifier identifier;
private boolean fresh = true;
private volatile boolean fresh = true;
public CacheValue(Identifier identifier) {
this.identifier = identifier;
@ -13,9 +13,10 @@ public class CacheValue <ValueType> {
return fresh;
}
public void setValue(ValueType value) {
public synchronized void setValue(ValueType value) {
this.fresh = false;
this.value = value;
identifier.usage ++;
}
public ValueType getValue() {

View File

@ -5,10 +5,12 @@ import java.util.Objects;
public class CoordinateIdentifier extends Identifier {
private final int x;
private final int y;
private final int hash;
public CoordinateIdentifier(int x, int y) {
this.x = x;
this.y = y;
hash = Objects.hash(x, y);
}
@Override
@ -22,7 +24,20 @@ public class CoordinateIdentifier extends Identifier {
@Override
public int hashCode() {
return Objects.hash(x, y);
return hash;
}
/**
* @return the x
*/
public int getX() {
return x;
}
/**
* @return the y
*/
public int getY() {
return y;
}
}

View File

@ -1,7 +1,7 @@
package ca.recrown.islandsurvivalcraft.caching;
public abstract class Identifier implements Comparable<Identifier> {
protected int usage;
protected volatile int usage;
@Override
public abstract boolean equals(Object obj);
@ -10,7 +10,7 @@ public abstract class Identifier implements Comparable<Identifier> {
public abstract int hashCode();
@Override
public int compareTo(Identifier o) {
public synchronized int compareTo(Identifier o) {
return usage - o.usage;
}
}