2013-02-26 96 views
0

我運行這個測試:性LevelDB的Java:刪除在迭代

public class LeveldbTest { 

@Test 
public void test() throws IOException, InterruptedException { 
    DBFactory factory = new Iq80DBFactory(); 

    Options opts = new Options(); 
    opts.cacheSize(4096); 
    opts.compressionType(CompressionType.SNAPPY); 
    opts.createIfMissing(true).writeBufferSize(4096); 
    final DB db = factory.open(new File("target/leveldb"), opts); 
    final AtomicLong counter = new AtomicLong(); 

    long start = System.currentTimeMillis(); 
    new Thread() { 
     @Override 
     public void run() { 
      WriteOptions wo = new WriteOptions(); 
      wo.sync(true); 
      while (true) { 
       String key = UUID.randomUUID().toString(); 
       byte[] bytes = key.getBytes(); 
       System.out.println("putting: " + key); 
       db.put(bytes, bytes, wo); 
       counter.incrementAndGet(); 
      } 
     } 
    }.start(); 

    new Thread() { 
     @Override 
     public void run() { 
      WriteOptions wo = new WriteOptions(); 
      ReadOptions ro = new ReadOptions(); 
      wo.sync(true); 
      while (true) { 
       DBIterator iterator = db.iterator(ro); 
       if (iterator.hasNext()) { 
        Entry<byte[], byte[]> next = iterator.next(); 
        byte[] key = next.getKey(); 
        System.out.println("deleting: " + new String(key)); 
        db.delete(key, wo); 
        counter.incrementAndGet(); 
        try { 
         iterator.close(); 
        } catch (IOException e) { 
        } 
       } 
      } 
     } 
    }.start(); 

    Thread.sleep(3000); 
    System.out.println((double) counter.longValue()/(System.currentTimeMillis() - start)); 
} 
} 

我期待那個鍵會從隊列中,但在控制檯中只有一個相同的鍵刪除似乎被刪除:

putting: a1ad4662-18c3-4085-af9d-a451dc3279c0 
deleting: 004ef0c2-b278-42c6-9c85-4769d93d5b30 <- 
putting: 6c4ee31d-2910-4870-acc5-962f9c40a573 
deleting: 004ef0c2-b278-42c6-9c85-4769d93d5b30 <- 
deleting: 004ef0c2-b278-42c6-9c85-4769d93d5b30 <- 
putting: 63e2e438-3849-46e3-9ea0-1165f9356efb 
deleting: 004ef0c2-b278-42c6-9c85-4769d93d5b30 <- 

我錯誤地使用了API嗎?

回答

0

事實證明,如果我在調用deleter線程中的next()之前調用iterator.seekToFirst(),它的行爲與我所期望的相同。 接下來的問題是如果我不尋求位置,迭代器指向何處。

0

正如您在使用迭代器時所觀察到的,您必須在迭代之前將迭代器指向seekToFirst或seekToLast的有效行。

我之前發現過這種困難,它並沒有如你所期望的那樣拋出ISE,你只是得到了不一致的讀取。