blob: 39ab28bd90f0064d89abff06d1cc9e50cd4c648d (
plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
|
package com.earth2me.essentials.storage;
import com.earth2me.essentials.IConf;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.api.IReload;
import java.io.File;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import org.bukkit.Bukkit;
public abstract class AsyncStorageObjectHolder<T extends StorageObject> implements IConf, IStorageObjectHolder<T>, IReload
{
private transient T data;
private final transient ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final transient Class<T> clazz;
protected final transient IEssentials ess;
public AsyncStorageObjectHolder(final IEssentials ess, final Class<T> clazz)
{
this.ess = ess;
this.clazz = clazz;
try
{
this.data = clazz.newInstance();
}
catch (Exception ex)
{
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
public T getData()
{
return data;
}
public void acquireReadLock()
{
rwl.readLock().lock();
}
public void acquireWriteLock()
{
while (rwl.getReadHoldCount() > 0)
{
rwl.readLock().unlock();
}
rwl.writeLock().lock();
rwl.readLock().lock();
}
public void close()
{
unlock();
}
public void unlock()
{
if (rwl.isWriteLockedByCurrentThread())
{
rwl.writeLock().unlock();
new StorageObjectDataWriter();
}
while (rwl.getReadHoldCount() > 0)
{
rwl.readLock().unlock();
}
}
@Override
public void reloadConfig()
{
new StorageObjectDataReader();
}
@Override
public void onReload()
{
new StorageObjectDataReader();
}
public abstract void finishRead();
public abstract void finishWrite();
public abstract File getStorageFile();
private class StorageObjectDataWriter extends AbstractDelayedYamlFileWriter
{
StorageObjectDataWriter()
{
super(ess, getStorageFile());
}
@Override
public StorageObject getObject()
{
acquireReadLock();
return getData();
}
@Override
public void onFinish()
{
unlock();
finishWrite();
}
}
private class StorageObjectDataReader extends AbstractDelayedYamlFileReader<T>
{
StorageObjectDataReader()
{
super(ess, getStorageFile(), clazz);
}
@Override
public void onStart()
{
rwl.writeLock().lock();
}
@Override
public void onSuccess(final T object)
{
if (object != null)
{
data = object;
}
rwl.writeLock().unlock();
finishRead();
}
@Override
public void onException()
{
if (data == null)
{
try
{
data = clazz.newInstance();
}
catch (Exception ex)
{
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
rwl.writeLock().unlock();
}
}
}
|