Skip to content

Commit

Permalink
Merge pull request #128 from rauljordan/database-mutex
Browse files Browse the repository at this point in the history
Making In-Memory DB Concurrency Safe
  • Loading branch information
rauljordan committed May 22, 2018
2 parents fcae1d9 + 58d10d2 commit bb77d16
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion sharding/database/inmemory.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ package database

import (
"fmt"
"sync"

"github.com/ethereum/go-ethereum/common"
)

// ShardKV is an in-memory mapping of hashes to RLP encoded values.
type ShardKV struct {
kv map[common.Hash]*[]byte
kv map[common.Hash]*[]byte
lock sync.RWMutex
}

// NewShardKV initializes a keyval store in memory.
Expand All @@ -21,6 +23,8 @@ func NewShardKV() *ShardKV {

// Get fetches a val from the mappping by key.
func (sb *ShardKV) Get(k common.Hash) (*[]byte, error) {
sb.lock.RLock()
defer sb.lock.RUnlock()
v, ok := sb.kv[k]
if !ok {
return nil, fmt.Errorf("key not found: %v", k)
Expand All @@ -30,19 +34,25 @@ func (sb *ShardKV) Get(k common.Hash) (*[]byte, error) {

// Has checks if the key exists in the mapping.
func (sb *ShardKV) Has(k common.Hash) bool {
sb.lock.RLock()
defer sb.lock.RUnlock()
v := sb.kv[k]
return v != nil
}

// Put updates a key's value in the mapping.
func (sb *ShardKV) Put(k common.Hash, v []byte) error {
sb.lock.Lock()
defer sb.lock.Unlock()
// there is no error in a simple setting of a value in a go map.
sb.kv[k] = &v
return nil
}

// Delete removes the key and value from the mapping.
func (sb *ShardKV) Delete(k common.Hash) error {
sb.lock.Lock()
defer sb.lock.Unlock()
// There is no return value for deleting a simple key in a go map.
delete(sb.kv, k)
return nil
Expand Down

0 comments on commit bb77d16

Please sign in to comment.