-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMultithreadedContext.java
74 lines (65 loc) · 2.01 KB
/
MultithreadedContext.java
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
package org.alxkm.patterns.multithreadedcontext;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* The MultithreadedContext class provides a thread-safe context for executing operations.
*/
public final class MultithreadedContext {
private static final MultithreadedContext INSTANCE = new MultithreadedContext();
private final Lock lock = new ReentrantLock();
/**
* Private constructor to prevent instantiation.
*/
private MultithreadedContext() {}
/**
* Returns the singleton instance of MultithreadedContext.
*
* @return the singleton instance
*/
public static MultithreadedContext getInstance() {
return INSTANCE;
}
/**
* Executes a Runnable operation in a thread-safe context.
*
* @param runnable the operation to be executed
*/
public void apply(Runnable runnable) {
lock.lock();
try {
runnable.run();
} finally {
lock.unlock();
}
}
/**
* Attempts to execute a Runnable operation in a thread-safe context without blocking.
* If the lock is not available, the operation will not be executed.
*
* @param runnable the operation to be executed
* @return true if the operation was executed successfully, false otherwise
*/
public boolean tryApply(Runnable runnable) {
if (lock.tryLock()) {
try {
runnable.run();
return true;
} finally {
lock.unlock();
}
}
return false;
}
/**
* Main method demonstrating the usage of MultithreadedContext.
*
* @param args command-line arguments (not used)
*/
public static void main(String[] args) {
MultithreadedContext context = MultithreadedContext.getInstance();
Runnable operation = () -> {
System.out.println("Thread-safe operation is performed.");
};
context.apply(operation);
}
}