簡體   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