我必须做一个任务,我必须为 Web 服务实现一个后台线程记录器,对于记录器,我们有一些骨架代码,其中我们有一个运行方法和一个返回未来对象的方法。对于我们必须实现预写日志记录的活动日志记录,我设法为记录器启动了一个新线程,并在我在 Web 服务中执行插入/更新命令时向它发送了记录某些内容的命令(Web 服务实现了一个键到值映射),但我无法让主线程等待日志线程完成日志记录。有人有什么建议吗?也许我做错了什么?
public class IndexImpl implements Index<KeyImpl,ValueListImpl>
{
private Thread log_thread;
private MyLogger log;
/*
* in out pair, the long refers to the initial memory address that our data
* has been saved too, and the integer refers to the length of the data in the file
*/
private HashMap<KeyImpl,Pair<Long,Integer>> m;
private long endAddr;
public IndexImpl()
{
valSer = new ValueSerializerImpl();
endAddr = 0;
m = new HashMap<KeyImpl,Pair<Long,Integer>>();
this.log= new MyLogger();
this.log_thread= new Thread(log);
log_thread.start();
}
public void insert(KeyImpl k, ValueListImpl v) throws KeyAlreadyPresentException, IOException {
locker.WriteLock(k);
try {
if (m.containsKey(k)) {
throw new KeyAlreadyPresentException(k);
}
else {
//LOGGING
Object[] array = new Object[3]; // Key, Old Value List, New Value List
array[0]= k.toString(); //Key
array[1]= null; // Old value list
array[2]= v; // New value list
LogRecord l = new LogRecord(MyKeyValueBaseLog.class, "insert", array);
FutureLog<LogRecord> future = (FutureLog<LogRecord>) log.logRequest(l);
System.out.println("Inserting a new key " + k.getKey());
future.get();
long tempEndAddr;
byte[] temp = valSer.toByteArray(v);
//we are using the ReentrantReadWriteLock implementation found in java
write.lock();
try{
tempEndAddr = endAddr;
endAddr += temp.length;
}
finally{
write.unlock();
}
store.write(tempEndAddr, temp);
m.put(k, new Pair<Long, Integer>(tempEndAddr,temp.length));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
locker.WriteUnlock(k);
}
}
记录器的代码是:
public class MyLogger implements Logger {
private ArrayList<LogRecord> log = new ArrayList<LogRecord>(100);
public MyLogger()
{
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("This is the logger thread! " + Thread.currentThread());
}
@Override
public Future<?> logRequest(LogRecord record) {
// TODO Auto-generated method stub
this.log.add(record);
System.out.println("Record added to log! operation: " + record.getMethodName() );
FutureLog<LogRecord> future = new FutureLog();
return future;
}
}