Skip to content

URL produces too much garbage objects #3494

Closed

Description

@kezhenxu94
  • I have searched the issues of this repository and believe that this is not a duplicate.
  • I have checked the FAQ of this repository and believe that this is not a duplicate.

PROBLEM

Most of the setXxxx and addParameter* in URL such as org.apache.dubbo.common.URL#addParameter and setXxxx will return a new URL object for chaining calls, and most of the "middle objects" are useless and unnecessary, example below:

class org.apache.dubbo.config.spring.SimpleRegistryExporter

    public static Exporter<RegistryService> export(int port, RegistryService registryService) {
        return protocol.export(proxyFactory.getInvoker(registryService, RegistryService.class,
                // HERE
                new URL("dubbo", NetUtils.getLocalHost(), port, RegistryService.class.getName())
                        .setPath(RegistryService.class.getName()) // useless
                        .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) // useless
                        .addParameter(Constants.CLUSTER_STICKY_KEY, "true") // useless
                        .addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000") // useless
                        .addParameter("ondisconnect", "disconnect") // useless
                        .addParameter("subscribe.1.callback", "true") // useless
                        .addParameter("unsubscribe.1.callback", "false")));
    }

class org.apache.dubbo.config.ServiceConfig

    @SuppressWarnings({"unchecked", "rawtypes"})
    private void exportLocal(URL url) {
        if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
            // HERE
            URL local = URL.valueOf(url.toFullString())
                    .setProtocol(Constants.LOCAL_PROTOCOL) // useless
                    .setHost(LOCALHOST_VALUE) // useless
                    .setPort(0);
            Exporter<?> exporter = protocol.export(
                    proxyFactory.getInvoker(ref, (Class) interfaceClass, local));
            exporters.add(exporter);
            logger.info("Export dubbo service " + interfaceClass.getName() + " to local registry");
        }
    }

SOLUTION

And I suggest refactoring the URL with Builder Pattern. And the possible usage may be:

URL url = ...;
URL newURL = new URLBuilder(url)
.addParameter(k, v)
.addParameter(k2, v2)
.setPath(yourPath)
.build();

Though we cannot remove the original addXXX and setXxxx methods due to compability, we can mark them as deprecated and guide users to use the new URLBuilder.

I'd like to try refactoring this if it's good to the comunity :)

Activity

  1. chickenlj commented on Feb 18, 2019

    @chickenlj
    Contributor

    At least, this could avoid the recreation of URL in the export and refer process.

    But, please keep in mind that the URL is designed to be immutable when Invoker is created.

  2. kezhenxu94 commented on Feb 18, 2019

    @kezhenxu94
    MemberAuthor

    @chickenlj The SOLUTION I proposed doesn't break the immutability of URL, the proposed URLBuilder is used to reduce the middle state objects when building a new URL from an old one.

    new URL("dubbo", NetUtils.getLocalHost(), port, RegistryService.class.getName()) // useless middle state URL
                            .setPath(RegistryService.class.getName()) // useless middle state URL
                            .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()) // useless middle state URL
                            .addParameter(Constants.CLUSTER_STICKY_KEY, "true") // useless middle state URL
                            .addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000") // useless middle state URL
                            .addParameter("ondisconnect", "disconnect") // useless middle state URL
                            .addParameter("subscribe.1.callback", "true") // useless middle state URL
                            .addParameter("unsubscribe.1.callback", "false")));

    produces 7 useless URL objects, and

    new URLBuilder("dubbo", NetUtils.getLocalHost(), port, RegistryService.class.getName())
                            .setPath(RegistryService.class.getName())
                            .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName())
                            .addParameter(Constants.CLUSTER_STICKY_KEY, "true")
                            .addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000")
                            .addParameter("ondisconnect", "disconnect")
                            .addParameter("subscribe.1.callback", "true")
                            .addParameter("unsubscribe.1.callback", "false")
                            .build()));

    leverages the same URLBuilder object and finally got the URL wanted.

    If it's not clear for you to understand my point, consider the URLBuilder implementation as follows:

    public final class URLBuilder {
        private String protocol;
    
        private String username;
    
        private String password;
    
        // by default, host to registry
        private String host;
    
        // by default, port to registry
        private int port;
    
        private String path;
    
        private Map<String, String> parameters;
    
        public URLBuilder() {
            protocol = null;
            username = null;
            password = null;
            host = null;
            port = 0;
            path = null;
            parameters = new HashMap<>();
        }
    
        public URL build() {
            if (StringUtils.isEmpty(username) && StringUtils.isNotEmpty(password)) {
                throw new IllegalArgumentException("Invalid url, password without username!");
            }
            port = port < 0 ? 0 : port;
            // trim the leading "/"
            int firstNonSlash = 0;
            if (path != null) {
                while (firstNonSlash < path.length() && path.charAt(firstNonSlash) == '/') {
                    firstNonSlash++;
                }
                if (firstNonSlash >= path.length()) {
                    path = "";
                } else if (firstNonSlash > 0) {
                    path = path.substring(firstNonSlash);
                }
            }
            return new URL(protocol, username, password, host, port, path, parameters);
        }
    
    
        public URLBuilder setProtocol(String protocol) {
            this.protocol = protocol;
            return this;
        }
    
        public URLBuilder setUsername(String username) {
            this.username = username;
            return this;
        }
    
        public URLBuilder setPassword(String password) {
            this.password = password;
            return this;
        }
    
        public URLBuilder setHost(String host) {
            this.host = host;
            return this;
        }
    
        public URLBuilder setPort(int port) {
            this.port = port;
            return this;
        }
    
        public URLBuilder setAddress(String address) {
            int i = address.lastIndexOf(':');
            String host;
            int port = this.port;
            if (i >= 0) {
                host = address.substring(0, i);
                port = Integer.parseInt(address.substring(i + 1));
            } else {
                host = address;
            }
            this.host = host;
            this.port = port;
            return this;
        }
    
        public URLBuilder setPath(String path) {
            this.path = path;
            return this;
        }
    
        public URLBuilder addParameterAndEncoded(String key, String value) {
            if (StringUtils.isEmpty(value)) {
                return this;
            }
            return addParameter(key, URL.encode(value));
        }
    
        public URLBuilder addParameter(String key, boolean value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, char value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, byte value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, short value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, int value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, long value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, float value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, double value) {
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, Enum<?> value) {
            if (value == null) {
                return this;
            }
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, Number value) {
            if (value == null) {
                return this;
            }
            return addParameter(key, String.valueOf(value));
        }
    
        public URLBuilder addParameter(String key, CharSequence value) {
            if (value == null || value.length() == 0) {
                return this;
            }
            return addParameter(key, String.valueOf(value));
        }
    
    // AND MORE METHODS
  3. chickenlj commented on Feb 18, 2019

    @chickenlj
    Contributor

    Great, looking forward to URLBuilder being available soon.

  4. kezhenxu94 commented on Feb 18, 2019

    @kezhenxu94
    MemberAuthor

    @chickenlj FYI, I've opened a PR #3500 to fix this issue

  5. chickenlj commented on Feb 20, 2019

    @chickenlj
    Contributor

    Cool, I am on it.

  6. chickenlj commented on Feb 27, 2019

    @chickenlj
    Contributor

    I've started a thread discussing this feature on the mailing list.

  7. added this to the 2.7.1 milestone on Mar 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions