繁体   English   中英

具有Runnable接口的Java Future对象

[英]Java Future object with Runnable interface

我必须完成一项工作,即必须为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;

}

}

您的记录器线程已启动, 将立即退出

@Override
public void run() {
    // TODO Auto-generated method stub
    System.out.println("This is the logger thread! " + Thread.currentThread());
}

取而代之的是,您需要循环使用此方法,在日志记录进入时将其写入。我可能建议您从BlockingQueue中读取,方法logRequest()应该将日志记录添加到此队列中。 这样,您的run()方法将仅在队列上等待(使用队列提供的take()方法),并在将每条记录从队列中取出时将其写出。

您将需要能够停止此操作,也许在这里中断线程是一种解决方案。

以上所有只是一个实现选择。 您遇到的根本问题是线程几乎立即启动/停止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM