Skip to content

Commit cc6715e

Browse files
committed
안전한 스레드 구성-2
1 parent c82ea18 commit cc6715e

File tree

4 files changed

+11
-4
lines changed

4 files changed

+11
-4
lines changed

src/main/java/io/concurrency/chapter05/exam04/ImmutableExample.java

+2
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,12 @@ public static void main(String[] args) {
2626
}
2727

2828
//상속 못 함
29+
//모든 필드 또한 final로 선언함으로써 필드가 변경될 수 있는 여지를 원천 차단함
2930
final class ImmutablePerson {
3031
private final String name;
3132
private final int age;
3233

34+
//생성과 동시에 값이 할당되며, 수정 못함
3335
public ImmutablePerson(String name, int age) {
3436
this.name = name;
3537
this.age = age;

src/main/java/io/concurrency/chapter05/exam04/READMD.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
- 메서드 내에서 지역 객체 참조 -> 각 스레드의 스택에 독립적으로 생성되기 때문
66
- 다른 주소 값을 갖는 멤버 변수를 다루는 경우
77
- 같은 주소 값을 갖는 멤버 변수를 다루더라도, 그 멤버 변수에 접근하는 것이 synchronized일 때
8-
- 같은 주소 값을 갖는 멤버 변수를 다루더라고, 그 멤버 변수가 불변 객체일 때
8+
- 같은 주소 값을 갖는 멤버 변수를 다루더라도, 그 멤버 변수가 불변 객체일 때

src/main/java/io/concurrency/chapter05/exam04/ThreadSafeLocalReferenceObjectExample.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,13 @@ public String toString() {
1414
}
1515
}
1616

17-
// LocalObject localObject = new LocalObject();
17+
//LocalObject localObject = new LocalObject();
1818

1919
public void useLocalObject() {
2020
// 지역 객체 참조. 각 스레드는 이 객체의 독립된 인스턴스를 가짐.
21+
// 이 메서드가 호출될 때마다 new로 인해 새로운 레퍼런스 객체가 생성되고,
22+
// 그 개별 주소가 각각의 스레드 내의 저장소에 저장되기 떄문
23+
2124
LocalObject localObject = new LocalObject();
2225

2326
for (int i = 0; i < 5; i++) {

src/main/java/io/concurrency/chapter05/exam04/ThreadSafeMemberReferenceObjectExample.java

+4-2
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22

33
public class ThreadSafeMemberReferenceObjectExample {
44
public static void main(String[] args) throws InterruptedException {
5-
new Thread(new MyRunnable(new Company("Company"))).start(); // 스레드에 안전함, 멤버변수를 공유하지 않음
6-
new Thread(new MyRunnable(new Company("Company"))).start(); // 스레드에 안전함, 멤버변수를 공유하지 않음
5+
new Thread(new MyRunnable(new Company("User"))).start(); // 스레드에 안전함, 멤버변수를 공유하지 않음
6+
new Thread(new MyRunnable(new Company("User"))).start(); // 스레드에 안전함, 멤버변수를 공유하지 않음
77

88
Thread.sleep(1000);
99
System.out.println("============================================================");
1010

11+
//객체는 레퍼런스로 생성되기 떄문에, company의 주소값이 동일하게 두 스레드의 매개변수에 들어가서 공유하게 됨
1112
Company company = new Company("Company"); // 스레드에 안전하지 못함, 멤버변수를 공유함
1213
new Thread(new MyRunnable(company)).start();
1314
new Thread(new MyRunnable(company)).start();
@@ -35,6 +36,7 @@ public Company(String name) {
3536
this.member = new Member(name);
3637
}
3738

39+
//지역 변수가 아니라 멤버 변수를 수정하고 있음
3840
public synchronized void changeName(String name) {
3941
String oldName = member.getName();
4042
member.setName(name);

0 commit comments

Comments
 (0)