繁体   English   中英

线程安全 Singleton class

[英]Thread-safe Singleton class

在我的项目中,我正在尝试使用 singleton class 在其中存储数据。 当我尝试从服务 class 访问它时,它会创建新实例而不是使用以前的 Singleton 实例。 我在 github 上阅读了很多帖子,但找不到有效的答案

我的 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());
    }
}

将数据添加到 Singleton

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

从 Singleton 获取数据

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

可能你可以这样写,它被命名为 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