当前位置: 首页 > 知识库问答 >
问题:

Singleton构造函数抛出由它的init方法抛出的异常

臧俊杰
2023-03-14
public class Communicator {
    private static Communicator instance = null;

    protected Communicator() {
        init();
    }

    public static Communicator getInstance() {
        if (instance == null) {
            instance = new Communicator();
        }
        return instance;
    }

    public void init() {
        // set up connections
    }
}
public class WindowsMidiCommunicator {
    private MidiDevice.Info[] devices;
    private MidiDevice outputDevice = null;
    private Receiver recvr = null;
    private MidiDevice inputDevice = null;
    private Transmitter trans = null;
    private DumpReceiver outputReceiverDump;
    private Logger log;
    private MessageQueue<Message> queue = null;
    private static WindowsMidiCommunicator instance=null;
    protected WindowsMidiCommunicator() {
        init();
    }
    public static WindowsMidiCommunicator getInstance(){
        if(instance==null){
            instance=new WindowsMidiCommunicator();
        }
        return instance;
    }
    public void init() {
        devices = MidiSystem.getMidiDeviceInfo();
        outputReceiverDump = new DumpReceiver(System.out);
        queue = new MessageQueue<Message>();
        outputReceiverDump.setMessageQueue(queue);
        Logger log = LogManager.getLogger(Saffiretest.class.getName());

        for (MidiDevice.Info info : devices) {
            if (info.getName().contains("Saffire")) {
                MidiDevice device = null;
                try {
                    device = MidiSystem.getMidiDevice(info);
                } catch (MidiUnavailableException e1) {
                    log.error("MidiUnavailableException");
                    e1.printStackTrace();
                }
                if (!device.isOpen()) {
                    try {
                        device.open();
                    } catch (MidiUnavailableException e) {
                        log.error("MidiUnavailableException");
                        e.printStackTrace();
                    }
                }
                if (device instanceof Sequencer) {
                    log.info("Device is a Sequencer");
                }
                if (device instanceof Synthesizer) {
                    log.info("Device is a Synthesizer");
                }
                log.info("Max receivers:" + device.getMaxReceivers());
                if (device.getMaxReceivers() == -1) {
                    outputDevice = device;
                    log.info(device.getDeviceInfo().getName()
                            + "obtained as outputDevice");
                }
                if (device.getMaxTransmitters() == -1) {
                    inputDevice = device;
                    log.info(device.getDeviceInfo().getName()
                            + "obtained as inputDevice");
                }
                log.info("Max transmitters:" + device.getMaxTransmitters());
                log.info("Open receivers:");
                List<Receiver> receivers = device.getReceivers();
                for (Receiver r : receivers) {
                    log.info(r.toString());
                }
                try {
                    log.info("Default receiver: "
                            + device.getReceiver().toString());

                    log.info("Open receivers now:");
                    receivers = device.getReceivers();
                    for (Receiver r : receivers) {
                        log.info(r.toString());
                    }
                } catch (MidiUnavailableException e) {
                    log.info("No default receiver");
                }

                log.info("Open transmitters:");
                List<Transmitter> transmitters = device.getTransmitters();
                for (Transmitter t : transmitters) {
                    log.info(t.toString());
                }
                try {
                    log.info("Default transmitter: "
                            + device.getTransmitter().toString());

                    log.info("Open transmitters now:");
                    transmitters = device.getTransmitters();
                    for (Transmitter t : transmitters) {
                        log.info(t.toString());
                    }
                } catch (MidiUnavailableException e) {
                    log.error("No default transmitter");
                }
            }
        }
        try {
            recvr = outputDevice.getReceiver();
        } catch (MidiUnavailableException e) {
            log.error("no receiver available");
            e.printStackTrace();
        }
        try {
            trans = inputDevice.getTransmitter();
            trans.setReceiver(outputReceiverDump);
        } catch (MidiUnavailableException e) {
            log.error("no transmitter available");
            e.printStackTrace();
        }

    }
protected WindowsMidiCommunicator() throws MidiUnavailableException {
        init();
    }
    public static WindowsMidiCommunicator getInstance() throws MidiUnavailableException{
        if(instance==null){
            instance=new WindowsMidiCommunicator();
        }
        return instance;
    }
    public void init() throws MidiUnavailableException {
        devices = MidiSystem.getMidiDeviceInfo();
        outputReceiverDump = new DumpReceiver(System.out);
        queue = new MessageQueue<Message>();
        outputReceiverDump.setMessageQueue(queue);
        Logger log = LogManager.getLogger(Saffiretest.class.getName());

        for (MidiDevice.Info info : devices) {
            if (info.getName().contains("Saffire")) {
                MidiDevice device = null;

                    device = MidiSystem.getMidiDevice(info);

                if (!device.isOpen()) {

                        device.open();

                }
                if (device instanceof Sequencer) {
                    log.info("Device is a Sequencer");
                }
                if (device instanceof Synthesizer) {
                    log.info("Device is a Synthesizer");
                }
                log.info("Max receivers:" + device.getMaxReceivers());
                if (device.getMaxReceivers() == -1) {
                    outputDevice = device;
                    log.info(device.getDeviceInfo().getName()
                            + "obtained as outputDevice");
                }
                if (device.getMaxTransmitters() == -1) {
                    inputDevice = device;
                    log.info(device.getDeviceInfo().getName()
                            + "obtained as inputDevice");
                }
                log.info("Max transmitters:" + device.getMaxTransmitters());
                log.info("Open receivers:");
                List<Receiver> receivers = device.getReceivers();
                for (Receiver r : receivers) {
                    log.info(r.toString());
                }

                    log.info("Default receiver: "
                            + device.getReceiver().toString());

                    log.info("Open receivers now:");
                    receivers = device.getReceivers();
                    for (Receiver r : receivers) {
                        log.info(r.toString());
                    }


                log.info("Open transmitters:");
                List<Transmitter> transmitters = device.getTransmitters();
                for (Transmitter t : transmitters) {
                    log.info(t.toString());
                }

                    log.info("Default transmitter: "
                            + device.getTransmitter().toString());

                    log.info("Open transmitters now:");
                    transmitters = device.getTransmitters();
                    for (Transmitter t : transmitters) {
                        log.info(t.toString());
                    }

            }
        }

            recvr = outputDevice.getReceiver();
            trans = inputDevice.getTransmitter();
            trans.setReceiver(outputReceiverDump);

    }

这是主要的方法:

public static void main(String[] args) {
        try {
            WindowsMidiCommunicator.getInstance().testConnectivity();
        } catch (InvalidMidiDataException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MidiUnavailableException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            WindowsMidiCommunicator.getInstance().sendCurrentPresetRequest();
        } catch (InvalidMidiDataException | MidiUnavailableException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new java.util.Timer().schedule( 
                new java.util.TimerTask() {
                    @Override
                    public void run() {
                        try {
                            WindowsMidiCommunicator.getInstance().closeDevices();
                        } catch (MidiUnavailableException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }, 
                5000 
        );
    }

运行时,这是堆栈跟踪:

INFO ] 2015-05-05 11:08:32.572 [main] Saffiretest - Max receivers:0
javax.sound.midi.MidiUnavailableException: MIDI IN receiver not available
    at com.sun.media.sound.AbstractMidiDevice.createReceiver(Unknown Source)
    at com.sun.media.sound.AbstractMidiDevice.getReceiver(Unknown Source)
    at WindowsMidiCommunicator.init(WindowsMidiCommunicator.java:79)
    at WindowsMidiCommunicator.<init>(WindowsMidiCommunicator.java:28)
    at WindowsMidiCommunicator.getInstance(WindowsMidiCommunicator.java:32)
    at SafferOrganizedTest.main(SafferOrganizedTest.java:9)
[INFO ] 2015-05-05 11:08:32.573 [main] Saffiretest - 2- Saffire 6USBobtained as inputDevice
[INFO ] 2015-05-05 11:08:32.574 [main] Saffiretest - Max transmitters:-1
[INFO ] 2015-05-05 11:08:32.574 [main] Saffiretest - Open receivers:
[INFO ] 2015-05-05 11:08:32.577 [main] Saffiretest - Max receivers:0
[INFO ] 2015-05-05 11:08:32.577 [main] Saffiretest - 2- Saffire 6USBobtained as inputDevice
[INFO ] 2015-05-05 11:08:32.577 [main] Saffiretest - Max transmitters:-1
[INFO ] 2015-05-05 11:08:32.577 [main] Saffiretest - Open receivers:
javax.sound.midi.MidiUnavailableException: MIDI IN receiver not available
    at com.sun.media.sound.AbstractMidiDevice.createReceiver(Unknown Source)
    at com.sun.media.sound.AbstractMidiDevice.getReceiver(Unknown Source)
    at WindowsMidiCommunicator.init(WindowsMidiCommunicator.java:79)
    at WindowsMidiCommunicator.<init>(WindowsMidiCommunicator.java:28)
    at WindowsMidiCommunicator.getInstance(WindowsMidiCommunicator.java:32)
    at SafferOrganizedTest.main(SafferOrganizedTest.java:18)
[INFO ] 2015-05-05 11:08:37.583 [Timer-0] Saffiretest - Max receivers:0
javax.sound.midi.MidiUnavailableException: MIDI IN receiver not available
[INFO ] 2015-05-05 11:08:37.584 [Timer-0] Saffiretest - 2- Saffire 6USBobtained as inputDevice
[INFO ] 2015-05-05 11:08:37.584 [Timer-0] Saffiretest - Max transmitters:-1
[INFO ] 2015-05-05 11:08:37.584 [Timer-0] Saffiretest - Open receivers:
    at com.sun.media.sound.AbstractMidiDevice.createReceiver(Unknown Source)
    at com.sun.media.sound.AbstractMidiDevice.getReceiver(Unknown Source)
    at WindowsMidiCommunicator.init(WindowsMidiCommunicator.java:79)
    at WindowsMidiCommunicator.<init>(WindowsMidiCommunicator.java:28)
    at WindowsMidiCommunicator.getInstance(WindowsMidiCommunicator.java:32)
    at SafferOrganizedTest$1.run(SafferOrganizedTest.java:28)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)

共有1个答案

朱皓
2023-03-14

不清楚您的实际问题是什么,因为您还没有发布错误消息。但是,您的单例实现并不是真正地道或正确的,主要是因为您的类的构造函数是受保护的。这意味着任何子类您的类都可以创建它的其他实例--使该类不再是一个单独的实例。

在Java5及以上版本中实现单例的最简单方法是使用具有单个值的枚举:

public enum Communicator {
    INSTANCE;

    private Connection conn;

    Communicator() {
        // set up the Connection here
    }

    /* public methods */
    public void doSomething() {
        //...
    }
}

这样,您只需使用communicator.instance.doSomething()调用单例。

 类似资料:
  • 当异常在构造函数中被抛出时,其中创建了多个对象,必须做些什么来清理内存。例如。 我的直觉是,将每个对new的调用放在一个单独的try-catch组中,并删除之前为其调用了,但这太冗长的所有对象(第一个try组不调用析构函数,第二个类调用第一个类的析构函数,第三个类调用前两个类的析构函数,以此类推)。我的问题是:最常见的处理方法是什么? 另外,假设类对象包含一个不是用new创建的对象(因为它在堆栈上

  • //接口 我从这个问题中读到:不能构造-Jackson的实例,但似乎没有帮助,因为我有太多的类从接口实现,不仅仅是一次。

  • 问题内容: 是否有关于对象是否使用异常的构造函数清除的详细信息。 众所周知,定义此方法的时间很短。根据手册: Java编程语言不能保证哪个线程将为任何给定对象调用finalize方法。但是,可以保证,调用finalize的线程在调用finalize时不会持有任何用户可见的同步锁。如果finalize方法抛出未捕获的异常,则该异常将被忽略,并且该对象的终止将终止。 http://docs.oracl

  • 问题内容: 我正在使用Jackson示例代码对POJO进行反序列化: 这行抛出一个NoSuchMethodError: 我不明白 问题答案: 我猜您的Jackson JAR不同步。本类是JAR,和类是在。 确保它们都是相同的版本。

  • 我有一个类(我不能修改),它只有一个构造函数,它接受一个参数,如下所示: 由于构造函数可以抛出错误,我想实现错误处理。我的第一次尝试是: 但是,现在在块的范围内,不能在其他地方使用。如果我理解正确,我不能在没有初始化的情况下声明对象,因此我可以在块之外声明。那么,我该如何捕捉构造函数抛出的错误呢? 编辑:为了澄清,这是在我的中,在中我将中止程序。此外,参数是一个将被打开的文件,因此没有已知的安全输

  • 这是我的代码: 以下是我的任务要求: 一个参数化构造函数,将接收endpoint(作为点)、方向(作为int)和样式(作为字符串)。如果接收到的点或字符串为空,则抛出新的IllegalArgumentException( 我知道我检查样式是虚线、虚线还是双精度的部分出了问题,因为当我把它注释出来时,除了那个部分,所有的东西都工作了。就现在的情况而言,它只是在所有事情上抛出了非法的辩论例外。 我有一