简体   繁体   English

线程安全 Singleton class

[英]Thread-safe Singleton class

in my project i am trying to use singleton class to store data in it.在我的项目中,我正在尝试使用 singleton class 在其中存储数据。 When im trying to access it from Service class, its creating new instance instead of using previous Singleton instance.当我尝试从服务 class 访问它时,它会创建新实例而不是使用以前的 Singleton 实例。 I read a lot of post on github and couldn't find working answer我在 github 上阅读了很多帖子,但找不到有效的答案

My Singleton class我的 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将数据添加到 Singleton

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

Getting data from Singleton从 Singleton 获取数据

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

may be you can write like this, which is named DCL(double check lock).可能你可以这样写,它被命名为 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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