在Java中,我们通过优雅地完成什么意思?

时间:2018-02-12 19:02:32

标签: java garbage-collection

  package com.madhubanti.singleprocess.player.interaction.main;

    import com.madhubanti.singleprocess.player.interaction.initiation.Initiator;
    import com.madhubanti.singleprocess.player.interaction.receiver.Receiver;

    /**
     * Starts application, Instantiate Players and help in garbage collection
     * 
     */
    public class MainApp {

        /**
         * main method instantiates Initiator and Receiver and helps in message
         * communication between them
         * 
         * Also sets unused objects to null and callss System.exit
         * 
         * @param args
         *            String array
         */
        public static void main(String[] args) {
            // Instantiates Initiator
            Initiator initiatorPlayer = new Initiator();
            // Instantiates Receiver
            Receiver receiverPlayer = new Receiver();
            // start sending message
            initiatorPlayer.sendMessage(receiverPlayer);
            // sets the value of the unused instances to null for garbage collection
            initiatorPlayer = null;
            receiverPlayer = null;
            System.exit(0);
        }

    }

    package com.madhubanti.singleprocess.player.interaction;

    import com.madhubanti.singleprocess.player.interaction.initiation.Initiator;

    /**
     * Parent class of {@link Initiator} and {@link Receiver}
     * 
     * @author Madhubanti Jash
     * 
     */
    public class Player {

        /**
         * returns counter value in string
         * 
         * @param counter
         *            1,2,3 etc
         * @return String format of counter
         */
        public String checkCounter(int counter) {
            switch (counter) {
            case 1:
                return "first";
            case 2:
                return "second";
            case 3:
                return "third";
            case 4:
                return "fourth";
            case 5:
                return "fifth";
            case 6:
                return "sixth";
            case 7:
                return "seventh";
            case 8:
                return "eighth";
            case 9:
                return "ninth";
            case 10:
                return "tenth";
            default:
                return "garbage collection";
            }
        }

    }

    package com.madhubanti.singleprocess.player.interaction.initiation;

    import java.util.logging.Level;
    import java.util.logging.Logger;

    import com.madhubanti.singleprocess.player.interaction.Player;
    import com.madhubanti.singleprocess.player.interaction.log.ConfigLogger;
    import com.madhubanti.singleprocess.player.interaction.receiver.Receiver;

    /**
     * Initiates message communication with {@link Receiver} and receives new
     * message from it.
     * 
     * @author Madhubanti Jash
     * 
     */
    public class Initiator extends Player {

        /** initializes logger */
        private static final Logger LOGGER = Logger.getLogger(Initiator.class.getName());

        /**
         * sends message to Receiver and receives new message in return
         * 
         * @param receiverPlayer
         *            instance of Receiver
         * 
         */
        public void sendMessage(Receiver receiverPlayer) {
            ConfigLogger.addLoggerHandler(LOGGER);
            String message = "";
            String prefix = "Sent message for ";
            String postfix = " Time";
            for (int counter = 1; counter <= 10; counter++) {
                message = prefix + super.checkCounter(counter) + postfix;
                LOGGER.log(Level.FINER, "message to be sent is: {0}", message);
                String newReceivedMessage = receiverPlayer.receiveMessage(message, counter);
                LOGGER.log(Level.FINER, "Received new message from Receiver is: {0}", newReceivedMessage);
            }
        }
    }

    package com.madhubanti.singleprocess.player.interaction.receiver;

    import com.madhubanti.singleprocess.player.interaction.Player;
    import com.madhubanti.singleprocess.player.interaction.initiation.Initiator;

    /**
     * Receives message communication from {@link Initiator} and sends back new
     * message
     * 
     * @author Madhubanti Jash
     * 
     */
    public class Receiver extends Player {

        /**
         * receives message from initiator and sends back new message in return
         * 
         * @param message
         *            received message
         * @return newMessage new message to Initiator
         * 
         */
        public String receiveMessage(String message, int counter) {
            String messageForNullValue = "have not received message; so not returning new message.";
            String postfix = " time from Receiver class.";
            String receivedMessage = message;
            String prefix = "Received message for ";
            String checkCounter = checkCounter(counter);
            String counterString = " The counter is: ";
            String newMessage = receivedMessage == null ? messageForNullValue
                    : prefix + checkCounter + postfix + counterString + counter;
            return newMessage;
        }

    }

    package com.madhubanti.singleprocess.player.interaction.log;

    import java.util.logging.ConsoleHandler;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    /** responsible to add log level and handler */
    public class ConfigLogger extends Logger {

        /**
         * parameterized constructor
         * 
         * @param name
         *            A name for the logger
         * @param resourceBundleName
         *            name of resource bundle
         * 
         */
        protected ConfigLogger(String name, String resourceBundleName) {
            super(name, resourceBundleName);
        }

        /**
         * add log level and handler
         * 
         * @param logger
         *            LOGGER
         */
        public static void addLoggerHandler(Logger logger) {
            ConsoleHandler consoleHandler = new ConsoleHandler();
            logger.addHandler(consoleHandler);
            consoleHandler.setLevel(Level.ALL);
            logger.setLevel(Level.ALL);
        }
    }

我上面提到了5个班级。这里Initiator启动与Receiver的通信。响应那个Receiver发回消息。 发送和接收消息10次后,我想优雅地完成不需要的对象。

为此,我在完成工作后将initiatorPlayerreceiverPlayer的值设置为null,然后在MainApp.java中调用System.exit(0)。这是实现“优雅地完成”的正确方法吗?

1 个答案:

答案 0 :(得分:3)

优雅地结束意味着通常以可以调用拆卸/取消设置操作的方式完成最终确定 为此,您必须确保应用程序无法通过崩溃终止。

完成宽限期不需要

不需要将变量设置为null,因为在JVM终止时将删除所有Java对象。所以你应该删除这些语句。

除了调用System.exit(0);之外,您将通过让main()线程完成执行来获得相同的结果。

优雅结束的例子

假设在您的代码中,Receiver在引擎盖下创建了一个未附加到JVM的资源,例如用于接收消息的网络套接字。
当程序终止时,您希望不再需要所有不再需要的资源:正在运行的JVM分配的对象以及打开的套接字。 JVM出口不必关闭连接到套接字的所有资源。调用receiverPlayer.dipose()可能是实现这一目标的方法。 但要做到这一点,你需要让程序优雅地完成。

例如:

public static void main(String[] args)  {
  Receiver receiverPlayer = null;
  try{
       // Instantiates Initiator
          Initiator initiatorPlayer = new Initiator();
       // Instantiates Receiver
          receiverPlayer = new Receiver();
       // start sending message
         initiatorPlayer.sendMessage(receiverPlayer); 
     }
  finally{
       if (receiverPlayer != null){
          receiverPlayer.dispose(); 
       }
  }
}