| 18 | // void Close() noexcept |
| 19 | template <class TConn> |
| 20 | class TConnCache { |
| 21 | struct TCounter : TAtomicCounter { |
| 22 | inline void IncCount(const TConn* const&) { |
| 23 | Inc(); |
| 24 | } |
| 25 | |
| 26 | inline void DecCount(const TConn* const&) { |
| 27 | Dec(); |
| 28 | } |
| 29 | }; |
| 30 | |
| 31 | public: |
| 32 | typedef TIntrusivePtr<TConn> TConnRef; |
| 33 | |
| 34 | class TConnList: public TLockFreeQueue<TConn*, TCounter> { |
| 35 | public: |
| 36 | ~TConnList() { |
| 37 | Clear(); |
| 38 | } |
| 39 | |
| 40 | inline void Clear() { |
| 41 | TConn* conn; |
| 42 | |
| 43 | while (this->Dequeue(&conn)) { |
| 44 | conn->Close(); |
| 45 | conn->UnRef(); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | inline size_t Size() { |
| 50 | return this->GetCounter().Val(); |
| 51 | } |
| 52 | }; |
| 53 | |
| 54 | inline void Put(TConnRef& conn, size_t addrId) { |
| 55 | conn->SetCached(true); |
| 56 | ConnList(addrId).Enqueue(conn.Get()); |
| 57 | conn->Ref(); |
| 58 | Y_UNUSED(conn.Release()); |
| 59 | CachedConn_.Inc(); |
| 60 | } |
| 61 | |
| 62 | bool Get(TConnRef& conn, size_t addrId) { |
| 63 | TConnList& connList = ConnList(addrId); |
| 64 | TConn* connTmp; |
| 65 | |
| 66 | while (connList.Dequeue(&connTmp)) { |
| 67 | connTmp->SetCached(false); |
| 68 | CachedConn_.Dec(); |
| 69 | if (connTmp->IsValid()) { |
| 70 | TConnRef(connTmp).Swap(conn); |
| 71 | connTmp->DecRef(); |
| 72 | |
| 73 | return true; |
| 74 | } else { |
| 75 | connTmp->UnRef(); |
| 76 | } |
| 77 | } |