github.com/tursom/GoCollections@v0.3.10/concurrent/collections/MessageQueue.go (about)

     1  /*
     2   * Copyright (c) 2022 tursom. All rights reserved.
     3   * Use of this source code is governed by a GPL-3
     4   * license that can be found in the LICENSE file.
     5   */
     6  
     7  package collections
     8  
     9  import (
    10  	"sync"
    11  
    12  	"github.com/tursom/GoCollections/exceptions"
    13  	"github.com/tursom/GoCollections/lang"
    14  )
    15  
    16  var (
    17  	// MessageQueueCapacity message capacity of MQ
    18  	// -1 to unlimited
    19  	// this variable can let you discover problems before OOM crash
    20  	MessageQueueCapacity  = 128
    21  	MessageQueueWarnLimit = MessageQueueCapacity / 2
    22  )
    23  
    24  type (
    25  	MessageQueue[T any] interface {
    26  		// Subscribe subscribe this message queue
    27  		Subscribe() lang.ReceiveChannel[T]
    28  		Send(msg T)
    29  	}
    30  	MessageQueueImpl[T lang.Object] struct {
    31  		chLock sync.Mutex
    32  		ch     lang.Channel[T]
    33  	}
    34  )
    35  
    36  func (m *MessageQueueImpl[T]) checkCh() {
    37  	if m.ch != nil {
    38  		return
    39  	}
    40  
    41  	m.chLock.Lock()
    42  	defer m.chLock.Unlock()
    43  
    44  	if m.ch != nil {
    45  		return
    46  	}
    47  
    48  	m.ch = lang.NewChannel[T](MessageQueueCapacity)
    49  }
    50  
    51  func (m *MessageQueueImpl[T]) Subscribe() lang.ReceiveChannel[T] {
    52  	m.checkCh()
    53  	// package ch, remove closer to empty body
    54  	// closer is nil will just close this channel
    55  	return lang.WithReceiveChannel[T](m.ch, func() {})
    56  }
    57  
    58  func (m *MessageQueueImpl[T]) Send(msg T) {
    59  	m.checkCh()
    60  	if !m.ch.TrySend(msg) {
    61  		panic(exceptions.NewIndexOutOfBound("object buffer of this MQ is full", nil))
    62  	}
    63  }