summaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/generationholder.h
blob: df44f39ebff770a6d1de41f82cb42bb2ca162526 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include "generationhandler.h"
#include <vector>
#include <memory>

namespace vespalib {

class GenerationHeldBase
{
public:
    typedef GenerationHandler::generation_t generation_t;
    typedef std::unique_ptr<GenerationHeldBase> UP;
    typedef std::shared_ptr<GenerationHeldBase> SP;

    generation_t _generation;
private:
    size_t	 _byte_size;

public:
    GenerationHeldBase(size_t byte_size_in)
        : _generation(0u),
          _byte_size(byte_size_in)
    { }

    virtual ~GenerationHeldBase();
    size_t byte_size() const { return _byte_size; }
};

/*
 * GenerationHolder is meant to hold large elements until readers can
 * no longer access them.
 */
class GenerationHolder
{
private:
    typedef GenerationHandler::generation_t generation_t;
    typedef GenerationHandler::sgeneration_t sgeneration_t;

    typedef std::vector<GenerationHeldBase::UP> HoldList;

    HoldList _hold1List;
    HoldList _hold2List;
    std::atomic<size_t>   _heldBytes;

    /**
     * Transfer holds from hold1 to hold2 lists, assigning generation.
     */
    void transferHoldListsSlow(generation_t generation);

    /**
     * Remove all data elements from this holder where generation < usedGen.
     **/
    void trimHoldListsSlow(generation_t usedGen);

public:
    GenerationHolder();
    ~GenerationHolder();

    /**
     * Add the given data pointer to this holder.
     **/
    void hold(GenerationHeldBase::UP data);

    /**
     * Transfer holds from hold1 to hold2 lists, assigning generation.
     */
    void transferHoldLists(generation_t generation) {
        if (!_hold1List.empty()) {
            transferHoldListsSlow(generation);
        }
    }

    /**
     * Remove all data elements from this holder where generation < usedGen.
     **/
    void trimHoldLists(generation_t usedGen) {
        if (!_hold2List.empty() && static_cast<sgeneration_t>(_hold2List.front()->_generation - usedGen) < 0) {
            trimHoldListsSlow(usedGen);
        }
    }

    void clearHoldLists();
    size_t getHeldBytes() const { return _heldBytes.load(std::memory_order_relaxed); }
};

}