pool

package module
Version: v2.0.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2018 License: Apache-2.0 Imports: 8 Imported by: 30

README

Go Commons Pool

Build Status CodeCov Go Report Card GoDoc

The Go Commons Pool is a generic object pool for Golang, direct rewrite from Apache Commons Pool.

Features

  1. Support custom PooledObjectFactory.
  2. Rich pool configuration option, can precise control pooled object lifecycle. See ObjectPoolConfig.
    • Pool LIFO (last in, first out) or FIFO (first in, first out)
    • Pool cap config
    • Pool object validate config
    • Pool object borrow block and max waiting time config
    • Pool object eviction config
    • Pool object abandon config

Pool Configuration Option

Configuration option table, more detail description see ObjectPoolConfig

Option Default Description
LIFO true If pool is LIFO (last in, first out)
MaxTotal 8 The cap of pool
MaxIdle 8 Max "idle" instances in the pool
MinIdle 0 Min "idle" instances in the pool
TestOnCreate false Validate when object is created
TestOnBorrow false Validate when object is borrowed
TestOnReturn false Validate when object is returned
TestWhileIdle false Validate when object is idle, see TimeBetweenEvictionRuns
BlockWhenExhausted true Whether to block when the pool is exhausted
MinEvictableIdleTime 30m Eviction configuration,see DefaultEvictionPolicy
SoftMinEvictableIdleTime math.MaxInt64 Eviction configuration,see DefaultEvictionPolicy
NumTestsPerEvictionRun 3 The maximum number of objects to examine during each run evictor goroutine
TimeBetweenEvictionRuns 0 The number of milliseconds to sleep between runs of the evictor goroutine, less than 1 mean not run

Usage

import "github.com/jolestar/go-commons-pool"

//use create func
p := pool.NewObjectPoolWithDefaultConfig(pool.NewPooledObjectFactorySimple(
        func() (interface{}, error) {
            return &MyPoolObject{}, nil
        }))
obj, _ := p.BorrowObject()
p.ReturnObject(obj)

//use custom Object factory

type MyObjectFactory struct {
}

func (f *MyObjectFactory) MakeObject() (*pool.PooledObject, error) {
    return pool.NewPooledObject(&MyPoolObject{}), nil
}

func (f *MyObjectFactory) DestroyObject(object *PooledObject) error {
    //do destroy
    return nil
}

func (f *MyObjectFactory) ValidateObject(object *pool.PooledObject) bool {
    //do validate
    return true
}

func (f *MyObjectFactory) ActivateObject(object *pool.PooledObject) error {
    //do activate
    return nil
}

func (f *MyObjectFactory) PassivateObject(object *pool.PooledObject) error {
    //do passivate
    return nil
}

p := pool.NewObjectPoolWithDefaultConfig(new(MyObjectFactory))
p.Config.MaxTotal = 100
obj, _ := p.BorrowObject()
p.ReturnObject(obj)

For more examples please see pool_test.go and example_test.go.

Note

PooledObjectFactory.MakeObject must return a pointer, not value. The following code will complain error.

p := pool.NewObjectPoolWithDefaultConfig(pool.NewPooledObjectFactorySimple(
    func() (interface{}, error) {
        return "hello", nil
    }))
obj, _ := p.BorrowObject()
p.ReturnObject(obj)

The right way is:

p := pool.NewObjectPoolWithDefaultConfig(pool.NewPooledObjectFactorySimple(
    func() (interface{}, error) {
        s := "hello"
        return &s, nil
    }))

For more examples please see example_test.go.

Dependency

PerformanceTest

The results of running the pool_perf_test is almost equal to the java version PerformanceTest

go test --perf=true

For Apache commons pool user

  • Direct use pool.Config.xxx to change pool config
  • Default config value is same as java version
  • If TimeBetweenEvictionRuns changed after ObjectPool created, should call ObjectPool.StartEvictor to take effect. Java version do this on set method.
  • No KeyedObjectPool (TODO)
  • No ProxiedObjectPool
  • No pool stats (TODO)

FAQ

FAQ

How to contribute

  • Choose one open issue you want to solve, if not create one and describe what you want to change.
  • Fork the repository on GitHub.
  • Write code to solve the issue.
  • Create PR and link to the issue.
  • Make sure test and coverage pass.
  • Wait maintainers to merge.

中文文档

License

Go Commons Pool is available under the Apache License, Version 2.0.

Documentation

Overview

Example (Multiple_borrowers)
type myPoolObject struct {
	s string
}

var v uint64
factory := NewPooledObjectFactorySimple(
	func(context.Context) (interface{}, error) {
		return &myPoolObject{
				s: strconv.FormatUint(atomic.AddUint64(&v, 1), 10),
			},
			nil
	})

ctx := context.Background()
p := NewObjectPoolWithDefaultConfig(ctx, factory)

// Borrows #1
obj1, err := p.BorrowObject(ctx)
if err != nil {
	panic(err)
}

o := obj1.(*myPoolObject)
fmt.Println(o.s)

// Borrowing again while the first object is borrowed will cause a new object to be made, if
// the pool configuration allows it. If the pull is full, this will block until the context
// is cancelled or an object is returned to the pool.
//
// Borrows #2
obj2, err := p.BorrowObject(ctx)
if err != nil {
	panic(err)
}

// Returning the object to the pool makes it available to another borrower.
err = p.ReturnObject(ctx, obj1)
if err != nil {
	panic(err)
}

// Since there's an object available in the pool, this gets that rather than creating a new one.
//
// Borrows #1 again (since it was returned earlier)
obj3, err := p.BorrowObject(ctx)
if err != nil {
	panic(err)
}

o = obj2.(*myPoolObject)
fmt.Println(o.s)

err = p.ReturnObject(ctx, obj2)
if err != nil {
	panic(err)
}

o = obj3.(*myPoolObject)
fmt.Println(o.s)

err = p.ReturnObject(ctx, obj3)
if err != nil {
	panic(err)
}
Output:

1
2
1

Index

Examples

Constants

View Source
const (
	// DefaultMaxTotal is the default value of ObjectPoolConfig.MaxTotal
	DefaultMaxTotal = 8
	// DefaultMaxIdle is the default value of ObjectPoolConfig.MaxIdle
	DefaultMaxIdle = 8
	// DefaultMinIdle is the default value of ObjectPoolConfig.MinIdle
	DefaultMinIdle = 0
	// DefaultLIFO is the default value of ObjectPoolConfig.LIFO
	DefaultLIFO = true

	// DefaultMinEvictableIdleTime is the default value of ObjectPoolConfig.MinEvictableIdleTime
	DefaultMinEvictableIdleTime = 30 * time.Minute
	// DefaultSoftMinEvictableIdleTime is the default value of ObjectPoolConfig.SoftMinEvictableIdleTime
	DefaultSoftMinEvictableIdleTime = time.Duration(math.MaxInt64)
	// DefaultNumTestsPerEvictionRun is the default value of ObjectPoolConfig.NumTestsPerEvictionRun
	DefaultNumTestsPerEvictionRun = 3
	// DefaultTestOnCreate is the default value of ObjectPoolConfig.TestOnCreate
	DefaultTestOnCreate = false
	// DefaultTestOnBorrow is the default value of ObjectPoolConfig.TestOnBorrow
	DefaultTestOnBorrow = false
	// DefaultTestOnReturn is the default value of ObjectPoolConfig.TestOnReturn
	DefaultTestOnReturn = false
	// DefaultTestWhileIdle is the default value of ObjectPoolConfig.TestWhileIdle
	DefaultTestWhileIdle = false
	// DefaultTimeBetweenEvictionRuns is the default value of ObjectPoolConfig.TimeBetweenEvictionRuns
	DefaultTimeBetweenEvictionRuns = time.Duration(0)
	// DefaultBlockWhenExhausted is the default value of ObjectPoolConfig.BlockWhenExhausted
	DefaultBlockWhenExhausted = true
	// DefaultEvictionPolicyName is the default value of ObjectPoolConfig.EvictionPolicyName
	DefaultEvictionPolicyName = "github.com/jolestar/go-commons-pool/DefaultEvictionPolicy"
)

Variables

This section is empty.

Functions

func Prefill

func Prefill(ctx context.Context, pool *ObjectPool, count int)

Prefill is util func for pre fill pool object

func RegistryEvictionPolicy

func RegistryEvictionPolicy(name string, policy EvictionPolicy)

RegistryEvictionPolicy registry a custom EvictionPolicy with gaven name.

Types

type AbandonedConfig

type AbandonedConfig struct {
	RemoveAbandonedOnBorrow      bool
	RemoveAbandonedOnMaintenance bool
	// Timeout before an abandoned object can be removed.
	RemoveAbandonedTimeout time.Duration
}

AbandonedConfig ObjectPool abandoned strategy config

func NewDefaultAbandonedConfig

func NewDefaultAbandonedConfig() *AbandonedConfig

NewDefaultAbandonedConfig return a new AbandonedConfig instance init with default.

type DefaultEvictionPolicy

type DefaultEvictionPolicy struct {
}

DefaultEvictionPolicy is a default EvictionPolicy impl

func (*DefaultEvictionPolicy) Evict

func (p *DefaultEvictionPolicy) Evict(config *EvictionConfig, underTest *PooledObject, idleCount int) bool

Evict do evict by config

type DefaultPooledObjectFactory

type DefaultPooledObjectFactory struct {
	// contains filtered or unexported fields
}

DefaultPooledObjectFactory is a default PooledObjectFactory impl, support init by func

func (*DefaultPooledObjectFactory) ActivateObject

func (f *DefaultPooledObjectFactory) ActivateObject(ctx context.Context, object *PooledObject) error

ActivateObject see PooledObjectFactory.ActivateObject

func (*DefaultPooledObjectFactory) DestroyObject

func (f *DefaultPooledObjectFactory) DestroyObject(ctx context.Context, object *PooledObject) error

DestroyObject see PooledObjectFactory.DestroyObject

func (*DefaultPooledObjectFactory) MakeObject

MakeObject see PooledObjectFactory.MakeObject

func (*DefaultPooledObjectFactory) PassivateObject

func (f *DefaultPooledObjectFactory) PassivateObject(ctx context.Context, object *PooledObject) error

PassivateObject see PooledObjectFactory.PassivateObject

func (*DefaultPooledObjectFactory) ValidateObject

func (f *DefaultPooledObjectFactory) ValidateObject(ctx context.Context, object *PooledObject) bool

ValidateObject see PooledObjectFactory.ValidateObject

type EvictionConfig

type EvictionConfig struct {
	IdleEvictTime     time.Duration
	IdleSoftEvictTime time.Duration
	MinIdle           int
	Context           context.Context
}

EvictionConfig is config for ObjectPool EvictionPolicy

type EvictionPolicy

type EvictionPolicy interface {
	// Evict do evict by config
	Evict(config *EvictionConfig, underTest *PooledObject, idleCount int) bool
}

EvictionPolicy is a interface support custom EvictionPolicy

func GetEvictionPolicy

func GetEvictionPolicy(name string) EvictionPolicy

GetEvictionPolicy return a EvictionPolicy by gaven name

type IllegalStateErr

type IllegalStateErr struct {
	// contains filtered or unexported fields
}

IllegalStateErr when use pool in a illegal way, return this err

func NewIllegalStateErr

func NewIllegalStateErr(msg string) *IllegalStateErr

NewIllegalStateErr return new IllegalStateErr

func (*IllegalStateErr) Error

func (err *IllegalStateErr) Error() string

type NoSuchElementErr

type NoSuchElementErr struct {
	// contains filtered or unexported fields
}

NoSuchElementErr when no available object in pool, return this err

func NewNoSuchElementErr

func NewNoSuchElementErr(msg string) *NoSuchElementErr

NewNoSuchElementErr return new NoSuchElementErr

func (*NoSuchElementErr) Error

func (err *NoSuchElementErr) Error() string

type ObjectPool

type ObjectPool struct {
	AbandonedConfig *AbandonedConfig
	Config          *ObjectPoolConfig
	// contains filtered or unexported fields
}

ObjectPool is a generic object pool

func NewObjectPool

func NewObjectPool(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig) *ObjectPool

NewObjectPool return new ObjectPool, init with PooledObjectFactory and ObjectPoolConfig

func NewObjectPoolWithAbandonedConfig

func NewObjectPoolWithAbandonedConfig(ctx context.Context, factory PooledObjectFactory, config *ObjectPoolConfig, abandonedConfig *AbandonedConfig) *ObjectPool

NewObjectPoolWithAbandonedConfig return new ObjectPool init with PooledObjectFactory, ObjectPoolConfig, and AbandonedConfig

func NewObjectPoolWithDefaultConfig

func NewObjectPoolWithDefaultConfig(ctx context.Context, factory PooledObjectFactory) *ObjectPool

NewObjectPoolWithDefaultConfig return new ObjectPool init with PooledObjectFactory and default config

func (*ObjectPool) AddObject

func (pool *ObjectPool) AddObject(ctx context.Context) error

AddObject create an object using the PooledObjectFactory factory, passivate it, and then place it in the idle object pool. AddObject is useful for "pre-loading" a pool with idle objects. (Optional operation).

func (*ObjectPool) BorrowObject

func (pool *ObjectPool) BorrowObject(ctx context.Context) (interface{}, error)

BorrowObject obtains an instance from pool. Instances returned from pool method will have been either newly created with PooledObjectFactory.MakeObject or will be a previously idle object and have been activated with PooledObjectFactory.ActivateObject and then validated with PooledObjectFactory.ValidateObject. If the pool is full (based on the number of objects in the pool and the value of the MaxTotal configuration field), this method will block until an object is returned to the pool or the context is cancelled.

By contract, clients must return the borrowed instance using ReturnObject, InvalidateObject

func (*ObjectPool) Clear

func (pool *ObjectPool) Clear(ctx context.Context)

Clear clears any objects sitting idle in the pool, releasing any associated resources (optional operation). Idle objects cleared must be PooledObjectFactory.DestroyObject(PooledObject) .

func (*ObjectPool) Close

func (pool *ObjectPool) Close(ctx context.Context)

Close pool, and free any resources associated with it.

func (*ObjectPool) GetDestroyedByBorrowValidationCount

func (pool *ObjectPool) GetDestroyedByBorrowValidationCount() int

GetDestroyedByBorrowValidationCount return destroyed object count when borrow validation

func (*ObjectPool) GetDestroyedCount

func (pool *ObjectPool) GetDestroyedCount() int

GetDestroyedCount return destroyed object count of this pool

func (*ObjectPool) GetNumActive

func (pool *ObjectPool) GetNumActive() int

GetNumActive return the number of instances currently borrowed from pool.

func (*ObjectPool) GetNumIdle

func (pool *ObjectPool) GetNumIdle() int

GetNumIdle return the number of instances currently idle in pool. This may be considered an approximation of the number of objects that can be BorrowObject borrowed without creating any new instances.

func (*ObjectPool) InvalidateObject

func (pool *ObjectPool) InvalidateObject(ctx context.Context, object interface{}) error

InvalidateObject invalidates an object from the pool. By contract, object must have been obtained using BorrowObject. This method should be used when an object that has been borrowed is determined (due to an exception or other problem) to be invalid.

func (*ObjectPool) IsClosed

func (pool *ObjectPool) IsClosed() bool

IsClosed return this pool is closed

func (*ObjectPool) PreparePool

func (pool *ObjectPool) PreparePool(ctx context.Context)

PreparePool Tries to ensure that {@link #getMinIdle()} idle instances are available in the pool.

func (*ObjectPool) ReturnObject

func (pool *ObjectPool) ReturnObject(ctx context.Context, object interface{}) error

ReturnObject return an instance to the pool. By contract, object must have been obtained using BorrowObject()

func (*ObjectPool) StartEvictor

func (pool *ObjectPool) StartEvictor()

StartEvictor start background evictor goroutine, pool.Config.TimeBetweenEvictionRuns must a positive number. if ObjectPool.Config.TimeBetweenEvictionRuns change, should call pool method to let it to take effect.

type ObjectPoolConfig

type ObjectPoolConfig struct {
	/**
	 * Whether the pool has LIFO (last in, first out) behaviour with
	 * respect to idle objects - always returning the most recently used object
	 * from the pool, or as a FIFO (first in, first out) queue, where the pool
	 * always returns the oldest object in the idle object pool.
	 */
	LIFO bool

	/**
	 * The cap on the number of objects that can be allocated by the pool
	 * (checked out to clients, or idle awaiting checkout) at a given time. Use
	 * a negative value for no limit.
	 */
	MaxTotal int

	/**
	 * The cap on the number of "idle" instances in the pool. Use a
	 * negative value to indicate an unlimited number of idle instances.
	 * If MaxIdle
	 * is set too low on heavily loaded systems it is possible you will see
	 * objects being destroyed and almost immediately new objects being created.
	 * This is a result of the active goroutines momentarily returning objects
	 * faster than they are requesting them them, causing the number of idle
	 * objects to rise above maxIdle. The best value for maxIdle for heavily
	 * loaded system will vary but the default is a good starting point.
	 */
	MaxIdle int

	/**
	 * The minimum number of idle objects to maintain in
	 * the pool. This setting only has an effect if
	 * TimeBetweenEvictionRuns is greater than zero. If this
	 * is the case, an attempt is made to ensure that the pool has the required
	 * minimum number of instances during idle object eviction runs.
	 *
	 * If the configured value of MinIdle is greater than the configured value
	 * for MaxIdle then the value of MaxIdle will be used instead.
	 *
	 */
	MinIdle int

	/**
	* Whether objects created for the pool will be validated before
	* being returned from the ObjectPool.BorrowObject() method. Validation is
	* performed by the ValidateObject() method of the factory
	* associated with the pool. If the object fails to validate, then
	* ObjectPool.BorrowObject() will fail.
	 */
	TestOnCreate bool

	/**
	 * Whether objects borrowed from the pool will be validated before
	 * being returned from the ObjectPool.BorrowObject() method. Validation is
	 * performed by the ValidateObject() method of the factory
	 * associated with the pool. If the object fails to validate, it will be
	 * removed from the pool and destroyed, and a new attempt will be made to
	 * borrow an object from the pool.
	 */
	TestOnBorrow bool

	/**
	 * Whether objects borrowed from the pool will be validated when
	 * they are returned to the pool via the ObjectPool.ReturnObject() method.
	 * Validation is performed by the ValidateObject() method of
	 * the factory associated with the pool. Returning objects that fail validation
	 * are destroyed rather then being returned the pool.
	 */
	TestOnReturn bool

	/**
	* Whether objects sitting idle in the pool will be validated by the
	* idle object evictor (if any - see
	*  TimeBetweenEvictionRuns ). Validation is performed
	* by the ValidateObject() method of the factory associated
	* with the pool. If the object fails to validate, it will be removed from
	* the pool and destroyed.  Note that setting this property has no effect
	* unless the idle object evictor is enabled by setting
	* TimeBetweenEvictionRuns to a positive value.
	 */
	TestWhileIdle bool

	/**
	* Whether to block when the ObjectPool.BorrowObject() method is
	* invoked when the pool is exhausted (the maximum number of "active"
	* objects has been reached).
	 */
	BlockWhenExhausted bool

	/**
	 * The minimum amount of time an object may sit idle in the pool
	 * before it is eligible for eviction by the idle object evictor (if any -
	 * see TimeBetweenEvictionRuns. When non-positive,
	 * no objects will be evicted from the pool due to idle time alone.
	 */
	MinEvictableIdleTime time.Duration

	/**
	 * The minimum amount of time an object may sit idle in the pool
	 * before it is eligible for eviction by the idle object evictor (if any -
	 * see TimeBetweenEvictionRuns),
	 * with the extra condition that at least MinIdle object
	 * instances remain in the pool. This setting is overridden by
	 *  MinEvictableIdleTime (that is, if
	 *  MinEvictableIdleTime is positive, then
	 *  SoftMinEvictableIdleTime is ignored).
	 */
	SoftMinEvictableIdleTime time.Duration

	/**
	 * The maximum number of objects to examine during each run (if any)
	 * of the idle object evictor goroutine. When positive, the number of tests
	 * performed for a run will be the minimum of the configured value and the
	 * number of idle instances in the pool. When negative, the number of tests
	 * performed will be math.Ceil(ObjectPool.GetNumIdle()/math.
	 * Abs(PoolConfig.NumTestsPerEvictionRun)) which means that when the
	 * value is -n roughly one nth of the idle objects will be
	 * tested per run.
	 */
	NumTestsPerEvictionRun int

	/**
	 * The name of the EvictionPolicy implementation that is
	 * used by this pool. Please register policy by RegistryEvictionPolicy(name, policy)
	 */
	EvictionPolicyName string

	/**
	* The amount of time sleep between runs of the idle
	* object evictor goroutine. When non-positive, no idle object evictor goroutine
	* will be run.
	* if this value changed after ObjectPool created, should call ObjectPool.StartEvictor to take effect.
	 */
	TimeBetweenEvictionRuns time.Duration

	/**
	 * The context.Context to use when the evictor runs in the background.
	 */
	EvitionContext context.Context
}

ObjectPoolConfig is ObjectPool config, include cap, block, valid strategy, evict strategy etc.

func NewDefaultPoolConfig

func NewDefaultPoolConfig() *ObjectPoolConfig

NewDefaultPoolConfig return a ObjectPoolConfig instance init with default value.

type PooledObject

type PooledObject struct {
	// Object must be a pointer
	Object         interface{}
	CreateTime     time.Time
	LastBorrowTime time.Time
	LastReturnTime time.Time
	//init equals CreateTime
	LastUseTime time.Time

	BorrowedCount int32
	// contains filtered or unexported fields
}

PooledObject is the wrapper of origin object that is used to track the additional information, such as state, for the pooled objects.

func NewPooledObject

func NewPooledObject(object interface{}) *PooledObject

NewPooledObject return new init PooledObject

func (*PooledObject) Allocate

func (o *PooledObject) Allocate() bool

Allocate this object

func (*PooledObject) Deallocate

func (o *PooledObject) Deallocate() bool

Deallocate this object

func (*PooledObject) EndEvictionTest

func (o *PooledObject) EndEvictionTest(idleQueue *collections.LinkedBlockingDeque) bool

EndEvictionTest called to inform the object that the eviction test has ended.

func (*PooledObject) GetActiveTime

func (o *PooledObject) GetActiveTime() time.Duration

GetActiveTime return the time that this object last spent in the the active state

func (*PooledObject) GetIdleTime

func (o *PooledObject) GetIdleTime() time.Duration

GetIdleTime the time that this object last spend in the the idle state

func (*PooledObject) GetLastUsedTime

func (o *PooledObject) GetLastUsedTime() time.Time

GetLastUsedTime return an estimate of the last time this object was used.

func (*PooledObject) GetState

func (o *PooledObject) GetState() PooledObjectState

GetState return current state of this object

func (*PooledObject) Invalidate

func (o *PooledObject) Invalidate()

Invalidate this object

func (*PooledObject) MarkAbandoned

func (o *PooledObject) MarkAbandoned()

MarkAbandoned mark this object to Abandoned state

func (*PooledObject) MarkReturning

func (o *PooledObject) MarkReturning()

MarkReturning mark this object to Returning state

func (*PooledObject) StartEvictionTest

func (o *PooledObject) StartEvictionTest() bool

StartEvictionTest attempt to place the pooled object in the EVICTION state

type PooledObjectFactory

type PooledObjectFactory interface {

	/**
	 * Create a pointer to an instance that can be served by the
	 * pool and wrap it in a PooledObject to be managed by the pool.
	 *
	 * return error if there is a problem creating a new instance,
	 *    this will be propagated to the code requesting an object.
	 */
	MakeObject(ctx context.Context) (*PooledObject, error)

	/**
	 * Destroys an instance no longer needed by the pool.
	 */
	DestroyObject(ctx context.Context, object *PooledObject) error

	/**
	 * Ensures that the instance is safe to be returned by the pool.
	 *
	 * return false if object is not valid and should
	 *         be dropped from the pool, true otherwise.
	 */
	ValidateObject(ctx context.Context, object *PooledObject) bool

	/**
	 * Reinitialize an instance to be returned by the pool.
	 *
	 * return error if there is a problem activating object,
	 *    this error may be swallowed by the pool.
	 */
	ActivateObject(ctx context.Context, object *PooledObject) error

	/**
	 * Uninitialize an instance to be returned to the idle object pool.
	 *
	 * return error if there is a problem passivating obj,
	 *    this exception may be swallowed by the pool.
	 */
	PassivateObject(ctx context.Context, object *PooledObject) error
}

PooledObjectFactory is factory interface for ObjectPool

Example
ctx := context.Background()
// MyCustomFactory is a type that implements PooledObjectFactory
// and is defined earlier in this file (example_test.go).
p := NewObjectPoolWithDefaultConfig(ctx, &MyCustomFactory{})

obj1, err := p.BorrowObject(ctx)
if err != nil {
	panic(err)
}

o := obj1.(*MyPoolObject)
fmt.Println(o.s)

err = p.ReturnObject(ctx, obj1)
if err != nil {
	panic(err)
}
Output:

1

func NewPooledObjectFactory

func NewPooledObjectFactory(
	create func(context.Context) (interface{}, error),
	destroy func(ctx context.Context, object *PooledObject) error,
	validate func(ctx context.Context, object *PooledObject) bool,
	activate func(ctx context.Context, object *PooledObject) error,
	passivate func(ctx context.Context, object *PooledObject) error) PooledObjectFactory

NewPooledObjectFactory return a DefaultPooledObjectFactory, init with gaven func.

func NewPooledObjectFactorySimple

func NewPooledObjectFactorySimple(
	create func(context.Context) (interface{}, error)) PooledObjectFactory

NewPooledObjectFactorySimple return a DefaultPooledObjectFactory, only custom MakeObject func

type PooledObjectState

type PooledObjectState int

PooledObjectState is PooledObjectState enum const

const (
	// StateIdle in the queue, not in use. default value.
	StateIdle PooledObjectState = iota
	// StateAllocated in use.
	StateAllocated
	// StateEviction in the queue, currently being tested for possible eviction.
	StateEviction
	// StateEvictionReturnToHead not in the queue, currently being tested for possible eviction. An
	// attempt to borrow the object was made while being tested which removed it
	// from the queue. It should be returned to the head of the queue once
	// eviction testing completes.
	StateEvictionReturnToHead
	// StateInvalid failed maintenance (e.g. eviction test or validation) and will be / has
	// been destroyed
	StateInvalid
	// StateAbandoned Deemed abandoned, to be invalidated.
	StateAbandoned
	// StateReturning Returning to the pool
	StateReturning
)

type TrackedUse

type TrackedUse interface {
	// GetLastUsed Get the last time o object was used in ms.
	GetLastUsed() time.Time
}

TrackedUse allows pooled objects to make information available about when and how they were used available to the object pool. The object pool may, but is not required, to use this information to make more informed decisions when determining the state of a pooled object - for instance whether or not the object has been abandoned.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL