-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAtomicReferenceExample.java
72 lines (60 loc) · 2.53 KB
/
AtomicReferenceExample.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
package org.alxkm.patterns.atomics;
import java.util.concurrent.atomic.AtomicReference;
/**
* Demonstrates the usage of AtomicReference in a multithreaded environment.
*/
public class AtomicReferenceExample {
static class SharedResource {
private String data;
public SharedResource(String data) {
this.data = data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
/**
*
* Demonstrates how AtomicReference ensures atomic updates of a shared reference in a multithreaded environment
* without requiring explicit synchronization.
*
* The SharedResource class represents a shared object that contains some data.
* The main method creates an AtomicReference initialized with an instance of SharedResource.
* Two threads are created: a writer thread and a reader thread.
* The writer thread sets a new instance of SharedResource with updated data using atomicReference.set().
* The reader thread reads the current value of the shared resource using atomicReference.get().
* Both threads run concurrently.
* After both threads have completed, the main thread prints the final state of the shared resource.
*
*/
public static void main(String[] args) {
SharedResource initialResource = new SharedResource("Initial Data");
AtomicReference<SharedResource> atomicReference = new AtomicReference<>(initialResource);
// Define worker threads
Thread writerThread = new Thread(() -> {
SharedResource newResource = new SharedResource("New Data");
atomicReference.set(newResource);
System.out.println(Thread.currentThread().getName() + " sets new data: " + newResource.getData());
});
Thread readerThread = new Thread(() -> {
SharedResource currentResource = atomicReference.get();
System.out.println(Thread.currentThread().getName() + " reads data: " + currentResource.getData());
});
// Start worker threads
writerThread.start();
readerThread.start();
// Wait for worker threads to complete
try {
writerThread.join();
readerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Final result
SharedResource finalResource = atomicReference.get();
System.out.println("Final data: " + finalResource.getData());
}
}