Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright (c) 2012 Jan Kotek
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *    http://www.apache.org/licenses/LICENSE-2.0
   *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 
 package org.mapdb;
 
 import java.util.*;
A database with easy access to named maps and other collections.

Author(s):
Jan Kotek
 
 @SuppressWarnings("unchecked")
 public class DB {

    
Engine which provides persistence for this D
 
     protected Engine engine;
    
already loaded named collections. It is important to keep collections as singletons, because of 'in-memory' lockin
 
     protected Map<StringWeakReference<?>> collections = new HashMap<StringWeakReference<?>>();

    
view over named records
 
     protected Map<StringLongnameDir;

    
default serializer used for persistence. Handles POJO and other stuff which requires write-able access to Engine
 
     protected Serializer<?> defaultSerializer;

    
Construct new DB. It is just thin layer over Engine which does the real work.

Parameters:
engine
 
     public DB(final Engine engine){
         this. = engine;
         // load serializer
         this. = new SerializerPojo(classInfos){
             @Override
             protected void saveClassInfo() {
                 //hook to save classes if they are updated
                 //I did not want to create direct dependency between SerialierPojo and Engine
                 engine.update(..);
             }
         };
 
         //open name dir
          = HTreeMap.preinitNamedDir(engine);
 
     }

    
Opens existing or creates new Hash Tree Map. This collection perform well under concurrent access. Is best for large keys and large values.

Parameters:
name of map
<K> key
<V> value
Returns:
map
 
     synchronized public <K,V> HTreeMap<K,V> getHashMap(String name){
         checkNotClosed();
         HTreeMap<K,V> ret = (HTreeMap<K, V>) getFromWeakCollection(name);
         if(ret!=nullreturn ret;
         Long recid = .get(name);
         if(recid!=null){
             //open existing map
             ret = new HTreeMap<K,V>(recid,);
             if(!ret.hasValuesthrow new ClassCastException("Collection is Set, not Map");
         }else{
             //create new map
             ret = new HTreeMap<K,V>(,true,false,..nextInt(), ,nullnull);
             .put(nameret.rootRecid);
         }
         .put(namenew WeakReference<Object>(ret));
         return ret;
     }


    
Creates new HashMap with more specific arguments

Parameters:
name of map to create
keepCounter if counter should be kept, without counter updates are faster, but entire collection needs to be traversed to count items.
keySerializer used to convert keys into/from binary form. Use null for default value.
valueSerializer used to convert values into/from binary form. Use null for default value.
<K> key type
<V> value type
Returns:
newly created map
Throws:
java.lang.IllegalArgumentException if name is already used
    synchronized public <K,V> HTreeMap<K,V> createHashMap(
            String nameboolean keepCounterSerializer<K> keySerializerSerializer<V> valueSerializer){
        checkNameNotExists(name);
        HTreeMap<K,V> ret = new HTreeMap<K,V>(true,keepCounter,..nextInt(), keySerializervalueSerializer);
        .put(nameret.rootRecid);
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }

    
Opens existing or creates new Hash Tree Set.

Parameters:
name of Set
<K> values in set
Returns:
set
    synchronized public <K> Set<K> getHashSet(String name){
        checkNotClosed();
        Set<K> ret = (Set<K>) getFromWeakCollection(name);
        if(ret!=nullreturn ret;
        Long recid = .get(name);
        if(recid!=null){
            //open existing map
            HTreeMap<K,Objectm = new HTreeMap<K,Object>(recid);
            if(m.hasValuesthrow new ClassCastException("Collection is Map, not Set");
            ret = m.keySet();
        }else{
            //create new map
            HTreeMap<K,Objectm = new HTreeMap<K,Object>(false,false..nextInt(), nullnull);
            ret = m.keySet();
            .put(namem.rootRecid);
        }
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }


    
Creates new HashSet

Parameters:
name of set to create
keepCounter if counter should be kept, without counter updates are faster, but entire collection needs to be traversed to count items.
serializer used to convert keys into/from binary form. Use null for default value.
<K> item type
Throws:
java.lang.IllegalArgumentException if name is already used
    
    synchronized public <K> Set<K> createHashSet(String nameboolean keepCounterSerializer<K> serializer){
        checkNameNotExists(name);
        HTreeMap<K,Objectret = new HTreeMap<K,Object>(false,keepCounter,..nextInt(), serializernull);
        .put(nameret.rootRecid);
        Set<K> ret2 = ret.keySet();
        .put(namenew WeakReference<Object>(ret2));
        return ret2;
    }

    
Opens existing or creates new B-linked-tree Map. This collection performs well under concurrent access. Only trade-off are deletes, which causes tree fragmentation. It is ordered and best suited for small keys and values.

Parameters:
name of map
<K> key
<V> value
Returns:
map
    
    synchronized public <K,V> BTreeMap<K,V> getTreeMap(String name){
        checkNotClosed();
        BTreeMap<K,V> ret = (BTreeMap<K,V>) getFromWeakCollection(name);
        if(ret!=nullreturn ret;
        Long recid = .get(name);
        if(recid!=null){
            //open existing map
            ret = new BTreeMap<K,V>(recid,);
            if(!ret.hasValuesthrow new ClassCastException("Collection is Set, not Map");
        }else{
            //create new map
            ret = new BTreeMap<K,V>(,.truefalse,falsenullnullnull);
            .put(nameret.treeRecid);
        }
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }

    
Creates new TreeMap

Parameters:
name of map to create
nodeSize maximal size of node, larger node causes overflow and creation of new BTree node. Use large number for small keys, use small number for large keys.
valuesStoredOutsideNodes if true, values are stored outside of BTree nodes. Use 'true' if your values are large.
keepCounter if counter should be kept, without counter updates are faster, but entire collection needs to be traversed to count items.
keySerializer used to convert keys into/from binary form. Use null for default value.
valueSerializer used to convert values into/from binary form. Use null for default value.
comparator used to sort keys. Use null for default value. TODO delta packing
<K> key type
<V> value type
Returns:
newly created map
Throws:
java.lang.IllegalArgumentException if name is already used
    synchronized public <K,V> BTreeMap<K,V> createTreeMap(
            String nameint nodeSizeboolean valuesStoredOutsideNodesboolean keepCounter,
            BTreeKeySerializer<K> keySerializerSerializer<V> valueSerializerComparator<K> comparator){
        checkNameNotExists(name);
        BTreeMap<K,V> ret = new BTreeMap<K,V>(nodeSizetrue,valuesStoredOutsideNodeskeepCounter,keySerializervalueSerializercomparator);
        .put(nameret.treeRecid);
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }


    
Get Named directory. Key is name, value is recid under which named record is stored

Returns:
    public Map<StringLonggetNameDir(){
        return ;
    }


    
Opens existing or creates new B-linked-tree Set.

Parameters:
name of set
<K> values in set
Returns:
set
    synchronized public <K> NavigableSet<K> getTreeSet(String name){
        checkNotClosed();
        NavigableSet<K> ret = (NavigableSet<K>) getFromWeakCollection(name);
        if(ret!=nullreturn ret;
        Long recid = .get(name);
        if(recid!=null){
            //open existing map
            BTreeMap<K,Objectm = new BTreeMap<K,Object>(,  recid);
            if(m.hasValuesthrow new ClassCastException("Collection is Map, not Set");
            ret = m.keySet();
        }else{
            //create new map
            BTreeMap<K,Objectm =  new BTreeMap<K,Object>(,.,
                    falsefalse,falsenullnullnull);
            .put(namem.treeRecid);
            ret = m.keySet();
        }
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }

    
Creates new TreeSet.

Parameters:
name of set to create
nodeSize maximal size of node, larger node causes overflow and creation of new BTree node. Use large number for small keys, use small number for large keys.
keepCounter if counter should be kept, without counter updates are faster, but entire collection needs to be traversed to count items.
serializer used to convert keys into/from binary form. Use null for default value.
comparator used to sort keys. Use null for default value. TODO delta packing
<K>
Returns:
Throws:
java.lang.IllegalArgumentException if name is already used
    synchronized public <K> NavigableSet<K> createTreeSet(String name,int nodeSizeboolean keepCounterBTreeKeySerializer<K> serializerComparator<K> comparator){
        checkNameNotExists(name);
        BTreeMap<K,Objectret = new BTreeMap<K,Object>(nodeSizefalsefalsekeepCounterserializernullcomparator);
        .put(nameret.treeRecid);
        NavigableSet<K> ret2 = ret.keySet();
        .put(namenew WeakReference<Object>(ret2));
        return ret2;
    }
//    synchronized public <E> Queue<E> getQueue(String name){
//        Long recid = nameDir.get(name);
//        if(recid==null){
//
//        }else{
//            return new Queues.Lifo<E>(engine, getDefaultSerializer(),  recid, true);
//        }
//    }
    synchronized public <E> Queue<E> getQueue(String name) {
        Long recid = .get(name);
        if(recid == null){
            recid = Queues.createQueue(getDefaultSerializer(), getDefaultSerializer());
            .put(name,recid);
        }
        Queue<E> ret = Queues.getQueue(,getDefaultSerializer(),recid);
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }
    synchronized public <E> Queue<E> getStack(String name) {
        Long recid = .get(name);
        if(recid == null){
            recid = Queues.createStack(getDefaultSerializer(), getDefaultSerializer(), true);
            .put(name,recid);
        }
        Queue<E> ret = Queues.getStack(getDefaultSerializer(),recid);
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }
    synchronized public <E> Queue<E> getCircularQueue(String name) {
        Long recid = .get(name);
        if(recid == null){
            recid = Queues.createCircularQueue(getDefaultSerializer(), getDefaultSerializer(), 1000000);
            .put(name,recid);
        }
        Queues.CircularQueue<E> ret = Queues.getCircularQueue(,getDefaultSerializer(),recid);
        .put(namenew WeakReference<Object>(ret));
        return ret;
    }
    synchronized public <E> Queue<E> createQueue(String nameSerializer<E> serializer) {
        checkNameNotExists(name);
        if(serializer==nullserializer=getDefaultSerializer();
        Long recid = Queues.createQueue(getDefaultSerializer(), serializer);
        .put(name,recid);
        return getQueue(name);
    }
    synchronized public <E> Queue<E> createStack(String nameSerializer<E> serializerboolean useLocks) {
        checkNameNotExists(name);
        if(serializer==nullserializer=getDefaultSerializer();
        Long recid = Queues.createStack(getDefaultSerializer(), serializeruseLocks);
        .put(name,recid);
        return getStack(name);
    }
    synchronized public <E> Queue<E> createCircularQueue(String nameSerializer<E> serializerlong size) {
        checkNameNotExists(name);
        if(serializer==nullserializer=getDefaultSerializer();
        Long recid = Queues.createCircularQueue(getDefaultSerializer(), serializersize);
        .put(name,recid);
        return getCircularQueue(name);
    }


    
Checks that object with given name does not exist yet.

Parameters:
name to check
Throws:
java.lang.IllegalArgumentException if name is already used
    protected void checkNameNotExists(String name) {
        if(.get(name)!=null)
            throw new IllegalArgumentException("Name already used: "+name);
    }


    
Closes database. All other methods will throw 'IllegalAccessError' after this method was called.

!! it is necessary to call this method before JVM exits!!

    synchronized public void close(){
        if( == nullreturn;
        .close();
        //dereference db to prevent memory leaks
         = null;
         = null;
         = null;
    }

    
All collections are weakly referenced to prevent two instances of the same collection in memory. This is mainly for locking, two instances of the same lock would not simply work.
    protected Object getFromWeakCollection(String name){
        WeakReference<?> r = .get(name);
        if(r==nullreturn null;
        Object o = r.get();
        if(o==null.remove(name);
        return o;
    }
    protected void checkNotClosed() {
        if( == nullthrow new IllegalAccessError("DB was already closed");
    }

    

Returns:
true if DB is closed and can no longer be used
    public synchronized  boolean isClosed(){
        return  == null;
    }

    
Commit changes made on collections loaded by this DB

See also:
Engine.commit()
    synchronized public void commit() {
        checkNotClosed();
        .commit();
    }

    
Rollback changes made on collections loaded by this DB

    synchronized public void rollback() {
        checkNotClosed();
        .rollback();
    }

    
Perform storage maintenance. Typically compact underlying storage and reclaim unused space.

NOTE: MapDB does not have smart defragmentation algorithms. So compaction usually recreates entire store from scratch. This may require additional disk space.

    synchronized public void compact(){
        .compact();
    }


    
Make readonly snapshot view of DB and all of its collection Collections loaded by this instance are not affected (are still mutable). You have to load new collections from DB returned by this method

Returns:
readonly snapshot view
    synchronized public DB snapshot(){
        Engine snapshot = SnapshotEngine.createSnapshotFor();
        return new DB (snapshot);
    }

    

Returns:
default serializer used in this DB, it handles POJO and other stuff.
    public  Serializer getDefaultSerializer() {
        return ;
    }

    

Returns:
underlying engine which takes care of persistence for this DB.
    public Engine getEngine() {
        return ;
    }
New to GrepCode? Check out our FAQ X