简体   繁体   中英

Thread-safe Singleton class

in my project i am trying to use singleton class to store data in it. When im trying to access it from Service class, its creating new instance instead of using previous Singleton instance. I read a lot of post on github and couldn't find working answer

My Singleton class

import android.util.Log;
import com.softelnet.ksavi.android.model.AttachmentRequest;
import java.util.LinkedList;

public class AttachmentsUpdateQueue {


    private static class Holder {
        private static final AttachmentsUpdateQueue singleInstance = new AttachmentsUpdateQueue();
    }


    private AttachmentsUpdateQueue() {
        Log.d("pox", "new instance");
    }

    private LinkedList<AttachmentRequest> attachmentsQueue = new LinkedList<>();

    public static AttachmentsUpdateQueue getInstance() {
        return Holder.singleInstance;

    }

    public AttachmentRequest getAttachmentForUpload() {
        Log.d("pox", "get, size:" + attachmentsQueue.size());
        if (attachmentsQueue.size() > 0) {
            return attachmentsQueue.get(0);
        } else {
            return null;
        }

    }

    public int getSize() {
        return attachmentsQueue.size();
    }

    public void addAttachmentForUpload(AttachmentRequest attachment) {
        attachmentsQueue.addLast(attachment);
        Log.d("pox", "added, size:" + attachmentsQueue.size());
    }
}

Adding data to Singleton

AttachmentsUpdateQueue.getInstance().addAttachmentForUpload(new AttachmentRequest(oprCtx.getUser(),task.getId(),attachment,isAttribute));

Getting data from Singleton

 AttachmentRequest req = AttachmentsUpdateQueue.getInstance().getAttachmentForUpload();

may be you can write like this, which is named DCL(double check lock).

private volatile static AttachmentsUpdateQueue instance = null;
private AttachmentsUpdateQueue(){
    System.out.println("Single: " + System.nanoTime());
}

public static AttachmentsUpdateQueue getInstance(){
    if(instance == null){
        synchronized (AttachmentsUpdateQueue.class) {
            if(instance == null){
                singleInstance = new AttachmentsUpdateQueue();
            }
        }
    }
    return instance;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM