반응형

정말 싱글턴 패턴은 1개의 객체만 생성해줄까?

 

class Singleton{
    private static Singleton Instance;
    private int count;

    private Singleton(){
        count = 0;
    }
    public static synchronized  Singleton getInstance(){
        if(Instance == null)
            Instance = new Singleton();

        return Instance;
    }
    public synchronized void add(){
        if(Instance == null)
            return;

        count++;
    }
    public int getCount(){
        return Instance == null ? 0 : count;
    }
}

 

 

class myFunc implements Runnable{
    @Override
    public void run(){
        final Singleton classInstance = Singleton.getInstance();

        for(int i = 0 ; i < 1000000; i++){
            classInstance.add();
        }
    }
}

 

 

package com.example.singletontest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView count = findViewById(R.id.singletonCount);

        final Singleton mainInstance = Singleton.getInstance();

        // lambda OnClickListener
        findViewById(R.id.btn).setOnClickListener((v)->{
            count.setText(mainInstance.getCount() +"");
        });

        // lambda thread
        Thread t1 = new Thread(()->{
            Singleton lambdaInstance = Singleton.getInstance();

            for(int i = 0 ; i < 1000000; i++) {
                lambdaInstance.add();
            }
        });
        t1.start();

        // using class implements runnable
        Runnable r2 = new myFunc();
        Thread t2 = new Thread(r2);
        t2.start();
        try { // wait for thread
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

메인에서도 싱글턴 생성을, 스레드 1,2에서도 싱글턴 객체 생성을 하지만 

 

정확하게 객체를 한개만 생성함을 알 수 있다.

 

하지만 위의 코드가 싱글턴을 제대로 수행하고 있지만

 

synchronized 키워드가 무겁기 때문에 조금더 개선이 필요하다.

 

반응형

'Basic > Android' 카테고리의 다른 글

안드로이드 뷰(Android View)란?  (0) 2019.07.10
Android에서 여러가지 콜백 방법  (0) 2019.07.03
Android Support Annotations  (0) 2019.06.25
Android에서 Intent란?  (2) 2019.06.10
[Eclipse] 한글입력시 오류 해결법  (0) 2014.01.23