FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms/src/test/java/GuardedObject.java at master · verifyCode/algorithms · GitHub
verifyCode
algorithms
Repository navigation
Code
Issues
Pull requests
2
(2)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms
/
src
/
test
/
java
/
GuardedObject.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
61 lines (55 loc) · 1.57 KB
Breadcrumbs
algorithms
/
src
/
test
/
java
/
GuardedObject.java
Copy path
File metadata and controls
61 lines (55 loc) · 1.57 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
java
.
util
.
Map
;
import
java
.
util
.
concurrent
.
ConcurrentHashMap
;
import
java
.
util
.
concurrent
.
TimeUnit
;
import
java
.
util
.
concurrent
.
locks
.
Condition
;
import
java
.
util
.
concurrent
.
locks
.
Lock
;
import
java
.
util
.
concurrent
.
locks
.
ReentrantLock
;
import
java
.
util
.
function
.
Predicate
;
public
class
GuardedObject
<
T
> {
//受保护的对象
T
obj
;
final
Lock
lock
=
new
ReentrantLock
();
final
Condition
done
=
lock
.
newCondition
();
final
int
timeout
=
2
;
//保存所有GuardedObject
final
static
Map
<
Object
,
GuardedObject
>
gos
=
new
ConcurrentHashMap
<>();
//静态方法创建GuardedObject
static
<
K
>
GuardedObject
create
(
K
key
) {
GuardedObject
go
=
new
GuardedObject
();
gos
.
put
(
key
,
go
);
return
go
;
}
static
<
K
,
T
>
void
fireEvent
(
K
key
,
T
obj
) {
GuardedObject
go
=
gos
.
remove
(
key
);
if
(
go
!=
null
) {
go
.
onChanged
(
obj
);
}
}
//获取受保护对象
T
get
(
Predicate
<
T
>
p
) {
lock
.
lock
();
try
{
//MESA管程推荐写法
while
(!
p
.
test
(
obj
)) {
done
.
await
(
timeout
,
TimeUnit
.
SECONDS
);
}
}
catch
(
InterruptedException
e
) {
throw
new
RuntimeException
(
e
);
}
finally
{
lock
.
unlock
();
}
//返回非空的受保护对象
return
obj
;
}
//事件通知方法
void
onChanged
(
T
obj
) {
lock
.
lock
();
try
{
this
.
obj
=
obj
;
done
.
signalAll
();
}
finally
{
lock
.
unlock
();
}
}
}
Back
|
FazBrowse Home
|
New Git URL