1/*
2 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24#ifndef SHARE_GC_Z_ZSAFEDELETE_INLINE_HPP
25#define SHARE_GC_Z_ZSAFEDELETE_INLINE_HPP
26
27#include "gc/z/zArray.inline.hpp"
28#include "gc/z/zSafeDelete.hpp"
29#include "metaprogramming/isArray.hpp"
30#include "utilities/debug.hpp"
31
32template <typename T>
33ZSafeDelete<T>::ZSafeDelete() :
34 _lock(),
35 _enabled(0),
36 _deferred() {}
37
38template <typename T>
39bool ZSafeDelete<T>::deferred_delete(ItemT* item) {
40 ZLocker<ZLock> locker(&_lock);
41 if (_enabled > 0) {
42 _deferred.add(item);
43 return true;
44 }
45
46 return false;
47}
48
49template <typename T>
50void ZSafeDelete<T>::immediate_delete(ItemT* item) {
51 if (IsArray<T>::value) {
52 delete [] item;
53 } else {
54 delete item;
55 }
56}
57
58template <typename T>
59void ZSafeDelete<T>::enable_deferred_delete() {
60 ZLocker<ZLock> locker(&_lock);
61 _enabled++;
62}
63
64template <typename T>
65void ZSafeDelete<T>::disable_deferred_delete() {
66 ZArray<ItemT*> deferred;
67
68 {
69 ZLocker<ZLock> locker(&_lock);
70 assert(_enabled > 0, "Invalid state");
71 if (--_enabled == 0) {
72 deferred.transfer(&_deferred);
73 }
74 }
75
76 ZArrayIterator<ItemT*> iter(&deferred);
77 for (ItemT* item; iter.next(&item);) {
78 immediate_delete(item);
79 }
80}
81
82template <typename T>
83void ZSafeDelete<T>::operator()(ItemT* item) {
84 if (!deferred_delete(item)) {
85 immediate_delete(item);
86 }
87}
88
89#endif // SHARE_GC_Z_ZSAFEDELETE_INLINE_HPP
90