我必须完成一项任务,我必须为Web服务实现后台线程记录器,对于记录器,我们得到一些框架代码,其中有一个run方法和一个返回未来对象的方法。为了记录我们必须实现预写日志记录的活动,我设法为记录器启动一个新线程,并且当我在Web服务中执行insert / update命令时,我发送命令来记录某些内容(Web服务实现了一个键to values map),但是我无法让主线程等待日志记录线程完成日志记录。有人有什么建议吗?也许我做错了什么?
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;
}
}
答案 0 :(得分:1)
您的记录器线程已启动,将立即退出
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("This is the logger thread! " + Thread.currentThread());
}
相反,您需要循环使用此方法,在它们进入时写入日志记录。我建议您从BlockingQueue读取,并且方法logRequest()应该将日志记录添加到此队列。这样,您的run()
方法将只等待队列(使用队列提供的take()方法),并在将每个记录从队列中取出时写出。
你需要能够阻止这一点,也许interrupting线程是一个解决方案。
以上所有内容只是一种实现选择。你遇到的根本问题是你的线程几乎是瞬间启动/停止。