일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 안드로이드
- 내부 단편화
- 물리 메모리
- 리사이클러뷰
- http발전과정
- appcompatacitivity
- 운영체제
- 프로세스
- 상태관리
- 절대 주소
- AAC
- 디자인 패턴
- http 역사
- DiffUtil
- appcompatactivity
- Kotlin
- flutter
- 플로이드워셜
- recyclerview
- 뷰홀더
- Dispatchers
- apk 빌드 과정
- Android
- 자이고트
- 리사이클러뷰풀
- AsyncListDiffer
- viewModelScope
- GetX
- 데코레이터 패턴
- NestedScrollView
- Today
- Total
hong's android
[안드로이드] Weak Reference VS Strong Reference 본문
Strong reference
일반적으로 New로 생성된 객체를 참조하는 것.
Gc가 발생해도 강한 참조가 된 객체는 회수되지 않는다.
Weak reference
Weak reference object에 의해서 참조하는 것
Weak reference 객체 자체는 강한 참조이고 Weak reference 객체 내부에서 참조를 유지한다.
Weak reference 객체에 의해 참조되는 객체가 weakly reachable 상태이다.
Gc가 발생하면 무조건 Weak reachable 한 객체들을 회수한다.
약한 참조가 사라지는 시점이 GC의 실행 주기와 일치하고, 이를 이용해 짧은 주기에 자주 사용되는 객체를 캐시 할 때 유용하다.
언제 사용할 수 있을까?
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
}
// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
AsyncTask로 이미지뷰를 넣는 스레드이다. 뷰를 Strong Reference로 사용하게되면 뷰를 가지고 있던 원래 객체에서 뷰의 참조를 끊더라도 계속 메모리에 남아있게된다. 그렇기 때문에 위와 같이 약한 참조를 사용해서 Gc 주기에 따라서 뷰를 가비지 컬렉팅 할 수 있다.
이미지의 로딩은 프로세스가 아닌, 쓰레드에서 처리를 하고 있는 것이죠. 다시 말하면, 바로 종료가 안되다는 것입니다. 이때가 WeakReference를 사용하는 최적화 타이밍 입니다. 그래서 안드로이드에서 사용하는 이미지 로더들이 WeakReference를 사용하는 것입니다. 물론 핸들러에서 사용하는것도 권장합니다
Reference.
https://d2.naver.com/helloworld/329631
https://stackoverflow.com/questions/3243215/how-to-use-weakreference-in-java-and-android-development
'Android > Android' 카테고리의 다른 글
[안드로이드] View lifecycle (0) | 2023.01.16 |
---|---|
[안드로이드] Handler, Content Provider, xml 레이아웃 (0) | 2023.01.14 |
[안드로이드] 자이고트 (0) | 2023.01.13 |
[안드로이드] 포어그라운드 서비스 VS 백그라운드 서비스 (0) | 2023.01.10 |
[안드로이드] Serializable과 Parcelable (0) | 2023.01.09 |