烹饪是什么意思| 翳是什么意思| 看脊椎挂什么科| 为什么会连续两天遗精| 女人吃什么提高性激素| 乙肝抗体阴性什么意思| 孔子名叫什么| 早上5点是什么时辰| 初衷是什么意思| 四月二十六是什么星座| 县纪委副书记什么级别| 2002年是什么年| 什么叫点映| 女人更年期有什么症状| 下面痛是什么原因| 蛐蛐吃什么食物| 女装大佬什么意思| 头疼喝什么饮料| 六月初一有什么讲究| 氯雷他定片主治什么| 炒菜勾芡用什么淀粉| 怀孕血糖高有什么症状| 狡黠什么意思| 胎盘下缘达宫颈内口是什么意思| 隽字五行属什么| 球菌是什么意思| 四菜一汤是什么意思| mhc是什么意思| 胰腺炎吃什么药好| cdfi是什么意思| 肉是什么结构| 聊天是什么意思| 阑珊处是什么意思| 墨菲定律什么意思| 绿壳鸡蛋是什么鸡生的| 巨蟹女喜欢什么样的男生| 出球小动脉流什么血| 非萎缩性胃炎吃什么药效果好| 湿疹什么原因引起的| 人为什么会长痔疮| 男性尿很黄是什么原因| 日照香炉生紫烟是什么意思| 攻心翻是什么病| 卫校学什么专业最好| 腰疼是什么原因引起的| 甲状腺素低吃什么能补| 1月22日什么星座| 什么样的西瓜甜| 黄山毛峰属于什么茶| 厮守是什么意思| 蚕屎做枕头有什么好处| 手上为什么长湿疹| 备孕男性吃什么精子强| 中筋面粉适合做什么| 宝宝拉肚子能吃什么| 噫气是什么意思| 9月30日是什么纪念日| 注音是什么| 甲状腺结节有什么感觉| 红色的补色是什么颜色| psa是什么意思| 梦见拖地是什么意思| 三无产品指的是什么| 梦见前婆婆是什么意思| 是什么就是什么| 梦见自己头发长长了是什么意思| 息风止痉是什么意思| uc是什么| 乳腺增生是什么原因引起的| 阳刃是什么意思| 紫米和小米什么关系| 什么颜色显黑| gg是什么牌子的包包| 血热是什么意思| 孕妇脚抽筋是什么原因| 炖牛肉放什么| 舒张压偏高是什么原因造成的| 鼻头发红是什么原因| 不生孩子的叫什么族| 气胸吃什么药| 为什么会长口腔溃疡| 手痒是什么原因| 肾结石去医院挂什么科| 红花跟藏红花有什么区别| 米酒发酸是什么原因| 紫苏有什么作用与功效| 角弓反张是什么意思| 气川读什么| 鬼节会开什么生肖| 麸质是什么意思| 方得始终什么意思| 血糖高早饭吃什么最好| 儿童包皮过长挂什么科| 什么样的女人招人嫉妒| 飞刀是什么意思| 农历八月初五是什么星座| 尿有泡泡是什么病| 鸡男配什么属相最好| 明哲保身是什么生肖| 女性私处长什么样| 欧盟是什么| 99什么意思| 总爱放屁是什么原因| 走仕途是什么意思| 肾积水有什么症状表现| 灰指甲有什么症状| 印模是什么意思| 尼龙属于什么材料| 抱恙是什么意思| 诏安是什么意思| 为什么经常放屁| 老鼠最怕什么东西| ba是什么| 胆结石吃什么药可以化掉结石| 查甲功是什么意思| 电波是什么意思| 荷尔蒙是什么意思| 今天的日子适合做什么| 五月掉床有什么说法| 手癣是什么原因引起的| 寻找什么| 世家是什么意思| 孩子说话晚是什么原因是什么情况| 败血症吃什么药| 脑供血不足用什么药好| 什么是抄底| 过敏性鼻炎用什么药效果好| 泛性恋什么意思| 口苦吃什么药最有效| 狐臭去医院挂什么科| 培土什么意思| 哈密瓜为什么会苦| 喝什么牛奶好| 神什么活什么| 小腹坠胀是什么原因| 癔病是一种什么病| 精子长什么样| 淋巴肿瘤吃什么食物好| 奠是什么意思| 做梦剪头发是什么意思| 怀孕可以喝什么饮料| 梦到公鸡是什么意思| 松香是什么| 阁老相当于现在什么官| 鹦鹉能吃什么水果| 骨折喝酒有什么影响吗| 寄生是什么意思| 突然心慌是什么原因| 吃西兰花有什么好处| ecg医学上什么意思| 手抖挂什么科室| eap是什么| 尿液黄绿色是什么原因| 孙策和孙权什么关系| 长智齿意味着什么| 吃洋葱对身体有什么好处| 球代表什么生肖| 什么原因引起尿酸高| 男的为什么喜欢男的| 缺钾吃什么补| 生精补精吃什么药最快| 什么是直辖市| 为什么月经期有性冲动| 辐射对称是什么意思| 2019属什么| 百字五行属什么| 男人太瘦吃什么可以长胖| 左下腹疼痛挂什么科| 景深是什么意思| 蜡烛燃烧会产生什么| 白内障是什么| pd1是什么意思| gl小说是什么意思| 为什么要当兵| 两面派是什么意思| 蝙蝠粪便是什么中药| 金相是什么意思| 护发素什么牌子好| abo溶血是什么意思| 飞沙走石是什么意思| 检查乳房挂什么科| 大米发霉是什么样子| 竹外桃花三两枝的下一句是什么| 感性的人是什么意思| 腹胀便溏是什么意思| 小马是什么牌子| 圣是什么生肖| 曹洪是曹操的什么人| 肉包子打狗的歇后语是什么| 做生意的人最忌讳什么| 为什么精液是黄色的| 黑木耳是什么意思| 梦见女鬼是什么意思| 什么人容易得白塞氏病| 紧急避孕药有什么危害| 万圣节为什么要送糖果| 一什么叮咛| 榴莲跟什么不能一起吃| 喷昔洛韦乳膏治什么| 降血压吃什么| 健身吃什么| 功成名就是什么意思| 内秀是什么意思| 运气是什么意思| 米乳是什么| 减脂吃什么蔬菜| innisfree是什么牌子的化妆品| 过奖是什么意思| 属相鸡与什么属相相合| 生命线分叉代表什么| 十万个为什么作者是谁| 吃猪心有什么好处和坏处| 三轮体空什么意思| 白带什么颜色| pt950是什么材质| ss是什么意思| 合伙人是什么意思| 和南圣众是什么意思| 手麻是什么情况| 锦鲤可以和什么鱼混养| 风声鹤唳是什么意思| 扁桃体结石是什么原因引起的| 麝牛是什么动物| 骨质疏松是什么症状| 去医院洗纹身挂什么科| 宫寒是什么| 1949年是什么年| 肝肾不足是什么意思| 吃什么菜对眼睛好| 梦见很多小孩是什么意思| 登徒子什么意思| 胡萝卜什么时候种| 大嘴猴属于什么档次| 按摩有什么好处和坏处| 什么样的伤口需要缝针| 枸杞有什么作用| 优思悦是什么药| 绌是什么意思| 清明有什么习俗| 青梅什么季节成熟| 抗体是什么意思| 梦见野猪是什么预兆| 二甲医院是什么级别| 为什么肠道总是咕咕的响| 长期失眠挂什么科| 什么是冠心病| 仓鼠和老鼠有什么区别| 全血粘度低切偏高是什么意思| 疯狗病症状都有什么| 寡情是什么意思| 脓毒血症是什么病| 什么零食热量低有利于减肥| 区委副书记是什么级别| 缩阳什么意思| 木槿是什么意思| 绰号是什么意思| 为什么突然就细菌感染了| 戴银镯子变黑是什么原因| 孕妇梦见老鼠是什么意思| 故什么意思| 9.3号是什么星座| 2022年属虎的是什么命| 念珠菌性阴道炎用什么药| 眼睑红是什么原因| 百度Jump to content

55岁大爷因爱吃豆腐天天吃 体内取出了420颗结石

From Wikipedia, the free encyclopedia
百度 记者就荣华实业房屋产权问题致电肃北县国土局,该局不动产中心负责人之一刘玉梅表示:他们(荣华实业)的房屋产权证不是办不下来,而是需要有一个前提条件的,在合理合法条件下能提供便利就提供便利。

The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object to the pool rather than destroying it; this can be done manually or automatically.

Object pools are primarily used for performance: in some circumstances, object pools significantly improve performance. Object pools complicate object lifetime, as objects obtained from and returned to a pool are not actually created or destroyed at this time, and thus require care in implementation.

Description

[edit]

When it is necessary to work with numerous objects that are particularly expensive to instantiate and each object is only needed for a short period of time, the performance of an entire application may be adversely affected. An object pool design pattern may be deemed desirable in cases such as these.

The object pool design pattern creates a set of objects that may be reused. When a new object is needed, it is requested from the pool. If a previously prepared object is available, it is returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a new item is created and returned. When the object has been used and is no longer needed, it is returned to the pool, allowing it to be used again in the future without repeating the computationally expensive instantiation process. It is important to note that once an object has been used and returned, existing references will become invalid.

In some object pools the resources are limited, so a maximum number of objects is specified. If this number is reached and a new item is requested, an exception may be thrown, or the thread will be blocked until an object is released back into the pool.

The object pool design pattern is used in several places in the standard classes of the .NET Framework. One example is the .NET Framework Data Provider for SQL Server. As SQL Server database connections can be slow to create, a pool of connections is maintained. Closing a connection does not actually relinquish the link to SQL Server. Instead, the connection is held in a pool, from which it can be retrieved when requesting a new connection. This substantially increases the speed of making connections.

Benefits

[edit]

Object pooling can offer a significant performance boost in situations where the cost of initializing a class instance is high and the rate of instantiation and destruction of a class is high – in this case objects can frequently be reused, and each reuse saves a significant amount of time. Object pooling requires resources – memory and possibly other resources, such as network sockets, and thus it is preferable that the number of instances in use at any one time is low, but this is not required.

The pooled object is obtained in predictable time when creation of the new objects (especially over network) may take variable time. These benefits are mostly true for objects that are expensive with respect to time, such as database connections, socket connections, threads and large graphic objects like fonts or bitmaps.

In other situations, simple object pooling (that hold no external resources, but only occupy memory) may not be efficient and could decrease performance.[1] In case of simple memory pooling, the slab allocation memory management technique is more suited, as the only goal is to minimize the cost of memory allocation and deallocation by reducing fragmentation.

Implementation

[edit]

Object pools can be implemented in an automated fashion in languages like C++ via smart pointers. In the constructor of the smart pointer, an object can be requested from the pool, and in the destructor of the smart pointer, the object can be released back to the pool. In garbage-collected languages, where there are no destructors (which are guaranteed to be called as part of a stack unwind), object pools must be implemented manually, by explicitly requesting an object from the factory and returning the object by calling a dispose method (as in the dispose pattern). Using a finalizer to do this is not a good idea, as there are usually no guarantees on when (or if) the finalizer will be run. Instead, "try ... finally" should be used to ensure that getting and releasing the object is exception-neutral.

Manual object pools are simple to implement, but harder to use, as they require manual memory management of pool objects.

Handling of empty pools

[edit]

Object pools employ one of three strategies to handle a request when there are no spare objects in the pool.

  1. Fail to provide an object (and return an error to the client).
  2. Allocate a new object, thus increasing the size of the pool. Pools that do this usually allow you to set the high water mark (the maximum number of objects ever used).
  3. In a multithreaded environment, a pool may block the client until another thread returns an object to the pool.

Pitfalls

[edit]

Care must be taken to ensure the state of the objects returned to the pool is reset back to a sensible state for the next use of the object, otherwise the object may be in a state unexpected by the client, which may cause it to fail. The pool is responsible for resetting the objects, not the clients. Object pools full of objects with dangerously stale state are sometimes called object cesspools and regarded as an anti-pattern.

Stale state may not always be an issue; it becomes dangerous when it causes the object to behave unexpectedly. For example, an object representing authentication details may fail if the "successfully authenticated" flag is not reset before it is reused, since it indicates that a user is authenticated (possibly as someone else) when they are not. However, failing to reset a value used only for debugging, such as the identity of the last authentication server used, may pose no issues.

Inadequate resetting of objects can cause information leaks. Objects containing confidential data (e.g. a user's credit card numbers) must be cleared before being passed to new clients, otherwise, the data may be disclosed to an unauthorized party.

If the pool is used by multiple threads, it may need the means to prevent parallel threads from trying to reuse the same object in parallel. This is not necessary if the pooled objects are immutable or otherwise thread-safe.

Criticism

[edit]

Some publications do not recommend using object pooling with certain languages, such as Java, especially for objects that only use memory and hold no external resources (such as connections to database). Opponents usually say that object allocation is relatively fast in modern languages with garbage collectors; while the operator new needs only ten instructions, the classic new - delete pair found in pooling designs requires hundreds of them as it does more complex work. Also, most garbage collectors scan "live" object references, and not the memory that these objects use for their content. This means that any number of "dead" objects without references can be discarded with little cost. In contrast, keeping a large number of "live" but unused objects increases the duration of garbage collection.[1]

Examples

[edit]

Go

[edit]

The following Go code initializes a resource pool of a specified size (concurrent initialization) to avoid resource race issues through channels, and in the case of an empty pool, sets timeout processing to prevent clients from waiting too long.

// package pool
package pool

import (
	"errors"
	"log"
	"math/rand"
	"sync"
	"time"
)

const getResMaxTime = 3 * time.Second

var (
	ErrPoolNotExist  = errors.New("pool not exist")
	ErrGetResTimeout = errors.New("get resource time out")
)

//Resource
type Resource struct {
	resId int
}

//NewResource Simulate slow resource initialization creation
// (e.g., TCP connection, SSL symmetric key acquisition, auth authentication are time-consuming)
func NewResource(id int) *Resource {
	time.Sleep(500 * time.Millisecond)
	return &Resource{resId: id}
}

//Do Simulation resources are time consuming and random consumption is 0~400ms
func (r *Resource) Do(workId int) {
	time.Sleep(time.Duration(rand.Intn(5)) * 100 * time.Millisecond)
	log.Printf("using resource #%d finished work %d finish\n", r.resId, workId)
}

//Pool based on Go channel implementation, to avoid resource race state problem
type Pool chan *Resource

//New a resource pool of the specified size
// Resources are created concurrently to save resource initialization time
func New(size int) Pool {
	p := make(Pool, size)
	wg := new(sync.WaitGroup)
	wg.Add(size)
	for i := 0; i < size; i++ {
		go func(resId int) {
			p <- NewResource(resId)
			wg.Done()
		}(i)
	}
	wg.Wait()
	return p
}

//GetResource based on channel, resource race state is avoided and resource acquisition timeout is set for empty pool
func (p Pool) GetResource() (r *Resource, err error) {
	select {
	case r := <-p:
		return r, nil
	case <-time.After(getResMaxTime):
		return nil, ErrGetResTimeout
	}
}

//GiveBackResource returns resources to the resource pool
func (p Pool) GiveBackResource(r *Resource) error {
	if p == nil {
		return ErrPoolNotExist
	}
	p <- r
	return nil
}

// package main
package main

import (
	"github.com/tkstorm/go-design/creational/object-pool/pool"
	"log"
	"sync"
)

func main() {
	// Initialize a pool of five resources,
	// which can be adjusted to 1 or 10 to see the difference
	size := 5
	p := pool.New(size)

	// Invokes a resource to do the id job
	doWork := func(workId int, wg *sync.WaitGroup) {
		defer wg.Done()
		// Get the resource from the resource pool
		res, err := p.GetResource()
		if err != nil {
			log.Println(err)
			return
		}
		// Resources to return
		defer p.GiveBackResource(res)
		// Use resources to handle work
		res.Do(workId)
	}

	// Simulate 100 concurrent processes to get resources from the asset pool
	num := 100
	wg := new(sync.WaitGroup)
	wg.Add(num)
	for i := 0; i < num; i++ {
		go doWork(i, wg)
	}
	wg.Wait()
}

C#

[edit]

In the .NET Base Class Library there are a few objects that implement this pattern. System.Threading.ThreadPool is configured to have a predefined number of threads to allocate. When the threads are returned, they are available for another computation. Thus, one can use threads without paying the cost of creation and disposal of threads.

The following shows the basic code of the object pool design pattern implemented using C#. For brevity the properties of the classes are declared using C# 3.0 automatically implemented property syntax. These could be replaced with full property definitions for earlier versions of the language. Pool is shown as a static class, as it's unusual for multiple pools to be required. However, it's equally acceptable to use instance classes for object pools.

namespace DesignPattern.Objectpool;

// The PooledObject class is the type that is expensive or slow to instantiate,
// or that has limited availability, so is to be held in the object pool.
public class PooledObject
{
    private DateTime _createdAt = DateTime.Now;

    public DateTime CreatedAt => _createdAt;

    public string TempData { get; set; }
}

// The Pool class controls access to the pooled objects. It maintains a list of available objects and a 
// collection of objects that have been obtained from the pool and are in use. The pool ensures that released objects 
// are returned to a suitable state, ready for reuse. 
public static class Pool
{
    private static List<PooledObject> _available = new List<PooledObject>();
    private static List<PooledObject> _inUse = new List<PooledObject>();

    public static PooledObject GetObject()
    {
        lock (_available)
        {
            if (_available.Count != 0)
            {
                PooledObject po = _available[0];
                _inUse.Add(po);
                _available.RemoveAt(0);
                return po;
            }
            else
            {
                PooledObject po = new PooledObject();
                _inUse.Add(po);
                return po;
            }
        }
    }

    public static void ReleaseObject(PooledObject po)
    {
        CleanUp(po);

        lock (_available)
        {
            _available.Add(po);
            _inUse.Remove(po);
        }
    }

    private static void CleanUp(PooledObject po)
    {
        po.TempData = null;
    }
}

In the code above, the PooledObject has properties for the time it was created, and another, that can be modified by the client, that is reset when the PooledObject is released back to the pool. Shown is the clean-up process, on release of an object, ensuring it is in a valid state before it can be requested from the pool again.

Java

[edit]

Java supports thread pooling via java.util.concurrent.ExecutorService and other related classes. The executor service has a certain number of "basic" threads that are never discarded. If all threads are busy, the service allocates the allowed number of extra threads that are later discarded if not used for the certain expiration time. If no more threads are allowed, the tasks can be placed in the queue. Finally, if this queue may get too long, it can be configured to suspend the requesting thread.

public class PooledObject {
	public String temp1;
	public String temp2;
	public String temp3;
	
	public String getTemp1() {
		return temp1;
	}
	public void setTemp1(String temp1) {
		this.temp1 = temp1;
	}
	public String getTemp2() {
		return temp2;
	}
	public void setTemp2(String temp2) {
		this.temp2 = temp2;
	}
	public String getTemp3() {
		return temp3;
	}
	public void setTemp3(String temp3) {
		this.temp3 = temp3;
	}
}
public class PooledObjectPool {
	private static long expTime = 6000;//6 seconds
	public static HashMap<PooledObject, Long> available = new HashMap<PooledObject, Long>();
	public static HashMap<PooledObject, Long> inUse = new HashMap<PooledObject, Long>();
	
	public synchronized static PooledObject getObject() {
		long now = System.currentTimeMillis();
		if (!available.isEmpty()) {
			for (Map.Entry<PooledObject, Long> entry : available.entrySet()) {
				if (now - entry.getValue() > expTime) { //object has expired
					popElement(available);
				} else {
					PooledObject po = popElement(available, entry.getKey());
					push(inUse, po, now); 
					return po;
				}
			}
		}

		// either no PooledObject is available or each has expired, so return a new one
		return createPooledObject(now);
	}	
	
	private synchronized static PooledObject createPooledObject(long now) {
		PooledObject po = new PooledObject();
		push(inUse, po, now);
		return po;
    }

	private synchronized static void push(HashMap<PooledObject, Long> map,
			PooledObject po, long now) {
		map.put(po, now);
	}

	public static void releaseObject(PooledObject po) {
		cleanUp(po);
		available.put(po, System.currentTimeMillis());
		inUse.remove(po);
	}
	
	private static PooledObject popElement(HashMap<PooledObject, Long> map) {
		 Map.Entry<PooledObject, Long> entry = map.entrySet().iterator().next();
		 PooledObject key= entry.getKey();
		 //Long value=entry.getValue();
		 map.remove(entry.getKey());
		 return key;
	}
	
	private static PooledObject popElement(HashMap<PooledObject, Long> map, PooledObject key) {
		map.remove(key);
		return key;
	}
	
	public static void cleanUp(PooledObject po) {
		po.setTemp1(null);
		po.setTemp2(null);
		po.setTemp3(null);
	}
}

See also

[edit]

Notes

[edit]
  1. ^ a b Goetz, Brian (2025-08-05). "Java theory and practice: Urban performance legends, revisited". IBM. IBM developerWorks. Archived from the original on 2025-08-05. Retrieved 2025-08-05.

References

[edit]
[edit]
手心有痣代表什么意思 宬字五行属什么 焦虑症应该挂什么科室 michaelkors是什么牌子 尿胆原弱阳性什么意思
张一山和杨紫是什么关系 白兰地是什么酒 空调开不了机是什么原因 同房什么感觉 转氨酶高说明什么
血小板计数偏低是什么意思 养老保险什么时候开始交 尿发黄是什么原因 男女双修什么意思 高血糖吃什么比较好
玮字五行属什么 轻度贫血有什么症状 6月23号什么星座 体检吃早餐有什么影响 人绒毛膜促性腺激素是什么意思
壁虎在家里是什么征兆hcv7jop6ns1r.cn 郭富城什么星座hcv8jop1ns4r.cn 清朝前面是什么朝代hcv7jop4ns6r.cn 什么是npchcv8jop0ns6r.cn 眼睛浮肿什么原因hcv8jop2ns5r.cn
江西有什么景点hcv9jop4ns1r.cn 沂字五行属什么hcv8jop8ns0r.cn 认知障碍是什么病hcv7jop9ns3r.cn 割包皮看什么科hcv9jop7ns0r.cn 遇上方知有什么意思hcv8jop4ns0r.cn
哮喘是什么症状hcv8jop7ns5r.cn 第四个手指叫什么jinxinzhichuang.com 大腿内侧肌肉叫什么hcv9jop6ns9r.cn 火碱是什么东西hcv8jop7ns4r.cn 4.4是什么星座hcv9jop3ns2r.cn
心肌供血不足吃什么药hcv8jop2ns1r.cn 岁月如梭是什么意思hcv8jop0ns9r.cn 省公安厅副厅长是什么级别hcv8jop0ns8r.cn 寻常疣是什么原因造成的hcv9jop3ns8r.cn 太阳是什么hcv8jop2ns1r.cn
百度