Exemple #1
0
  public static void main(String[] args) throws IOException {

    // Open db in temp directory
    File f = File.createTempFile("mapdb", "temp");
    DB db = DBMaker.newFileDB(f).make();

    // Open or create table
    Map<String, Person> dbMap = db.getTreeMap("personAndCity");

    // Add data
    Person bilbo = new Person("Bilbo", "The Shire");
    Person sauron = new Person("Sauron", "Mordor");
    Person radagast = new Person("Radagast", "Crazy Farm");

    dbMap.put("west", bilbo);
    dbMap.put("south", sauron);
    dbMap.put("mid", radagast);

    // Commit and close
    db.commit();
    db.close();

    //
    // Second option for using cystom values is to use your own serializer.
    // This usually leads to better performance as MapDB does not have to
    // analyze the class structure.
    //

    class CustomSerializer implements ValueSerializer<Person>, Serializable {

      @Override
      public void serialize(DataOutput out, Person value) throws IOException {
        out.writeUTF(value.getName());
        out.writeUTF(value.getCity());
      }

      @Override
      public Person deserialize(DataInput in, int available) throws IOException {
        return new Person(in.readUTF(), in.readUTF());
      }

      @Override
      public int fixedSize() {
        return -1;
      }
    }

    ValueSerializer<Person> serializer = new CustomSerializer();

    DB db2 = DBMaker.newTempFileDB().make();

    Map<String, Person> map2 = db2.createHashMap("map").valueSerializer(serializer).make();

    map2.put("North", new Person("Yet another dwarf", "Somewhere"));

    db2.commit();
    db2.close();
  }
 @Override
 public ConcurrentMap<String, String> getCacheMap(String namespaceKey) {
   final Lock lock = nsLocks.get(namespaceKey);
   lock.lock();
   try {
     String mapDBKey = currentNamespaceCache.get(namespaceKey);
     if (mapDBKey == null) {
       // Not something created by swapAndClearCache
       mapDBKey = namespaceKey;
     }
     return mmapDB.createHashMap(mapDBKey).makeOrGet();
   } finally {
     lock.unlock();
   }
 }
 @Override
 public ConcurrentMap<String, String> getCacheMap(String namespaceOrCacheKey) {
   final Lock lock = nsLocks.get(namespaceOrCacheKey);
   lock.lock();
   try {
     String realKey = currentNamespaceCache.get(namespaceOrCacheKey);
     if (realKey == null) {
       realKey = namespaceOrCacheKey;
     }
     final Lock nsLock = nsLocks.get(realKey);
     if (lock != nsLock) {
       nsLock.lock();
     }
     try {
       return mmapDB.createHashMap(realKey).makeOrGet();
     } finally {
       if (lock != nsLock) {
         nsLock.unlock();
       }
     }
   } finally {
     lock.unlock();
   }
 }