1 25 26 29 package net.killingar.forum.internal.caches; 30 31 import it.unimi.dsi.fastutil.longs.Long2ObjectAVLTreeMap; 32 import net.killingar.forum.internal.IDItem; 33 import net.killingar.forum.internal.managers.AbstractManager; 34 35 import java.sql.*; 36 37 public abstract class AbstractIDItemCache 38 { 39 protected Timestamp latestUpdate = new Timestamp(0); 40 protected Long2ObjectAVLTreeMap objects = new Long2ObjectAVLTreeMap(); 41 42 public synchronized IDItem get(long id) throws SQLException 43 { 44 update(); 45 46 if (!(objects.get(id) instanceof IDItem) && objects.get(id) != null) 47 throw new ClassCastException ("cast failed from "+objects.get(id).getClass()+" to IDItem"); 48 49 return (IDItem)objects.get(id); 50 } 51 52 protected abstract PreparedStatement createStatement(Connection c) throws SQLException; 53 protected abstract IDItem getObjectFromRow(ResultSet result) throws SQLException; 54 55 public synchronized void add(IDItem inO) 56 { 57 objects.put(inO.getId(), inO); 58 } 59 60 protected long getUpdateTimeout() 61 { 62 return 1500; 63 } 64 65 protected synchronized void update() throws SQLException 66 { 67 if (System.currentTimeMillis()-latestUpdate.getTime() < getUpdateTimeout()) 68 return; 69 75 76 Timestamp now = new Timestamp(System.currentTimeMillis()-1001); 78 Connection c = null; 79 PreparedStatement statement = null; 80 ResultSet result = null; 81 82 try 83 { 84 c = AbstractManager.getNewConnection(); 85 statement = createStatement(c); 86 87 result = statement.executeQuery(); 88 while (result.next()) 89 add(getObjectFromRow(result)); 90 } 91 finally { AbstractManager.closeAll(c, statement, result); } 92 93 latestUpdate = now; 94 } 95 } 96 | Popular Tags |