Skip to content

Commit

Permalink
use lock defer unlock pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
CaitieM20 committed Jun 16, 2016
1 parent 1afdd8c commit 90385aa
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions saga/inMemorySagaLog.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,41 +27,41 @@ func MakeInMemorySaga() Saga {
}

func (log *inMemorySagaLog) LogMessage(msg sagaMessage) error {
fmt.Println(fmt.Sprintf("Saga %s: %s %s", msg.sagaId, msg.msgType.String(), msg.taskId))

log.mutex.Lock()
defer log.mutex.Unlock()

fmt.Println(fmt.Sprintf("Saga %s: %s %s", msg.sagaId, msg.msgType.String(), msg.taskId))
sagaId := msg.sagaId
var err error

log.mutex.Lock()
msgs, ok := log.sagas[sagaId]
if !ok {
return errors.New(fmt.Sprintf("Saga: %s is not Started yet.", msg.sagaId))
}

log.sagas[sagaId] = append(msgs, msg)
log.mutex.Unlock()
return err
return nil

This comment has been minimized.

Copy link
@dbentley

dbentley Jun 16, 2016

Contributor

Oh great, it looks like this even fixes a possible bug! (not unlocking on invalid sagaID)

}

func (log *inMemorySagaLog) StartSaga(sagaId string, job []byte) error {

log.mutex.Lock()
defer log.mutex.Unlock()

fmt.Println(fmt.Sprintf("Start Saga %s", sagaId))

startMsg := MakeStartSagaMessage(sagaId, job)
log.sagas[sagaId] = []sagaMessage{startMsg}

log.mutex.Unlock()

return nil
}

func (log *inMemorySagaLog) GetMessages(sagaId string) ([]sagaMessage, error) {

log.mutex.RLock()
defer log.mutex.RUnlock()

msgs, ok := log.sagas[sagaId]
log.mutex.RUnlock()

if ok {
return msgs, nil
Expand All @@ -75,13 +75,13 @@ func (log *inMemorySagaLog) GetMessages(sagaId string) ([]sagaMessage, error) {
*/
func (log *inMemorySagaLog) GetActiveSagas() ([]string, error) {
log.mutex.RLock()
defer log.mutex.RUnlock()

keys := make([]string, 0, len(log.sagas))

for key, _ := range log.sagas {
keys = append(keys, key)
}

log.mutex.RUnlock()

return keys, nil
}

0 comments on commit 90385aa

Please sign in to comment.