devxlogo

Timeouts on Socket Creation

Question:
I am trying to open multiple sockets at differing IP addresses. Is there a way to make it so that the open socket call will wait for only two seconds?

Answer:
There is no supported way of defining a timeoutfor a socket connection attempt. There is noreason this should be so, and is a flaw in thecore Java API. Unfortunately, this has not changed in Java 1.2. You can see my August 1998 Java Pro column, entitled “Socket to Me,” for a discussion of this dilemma. Perhaps the only workaround is to launch the socket connetion attempt in a separate thread and then wait in the main program for the timeout period. If the socket connection succeeds before the timeout, the thread should wake up the main parent thread. If the socket connection is still in progress, the main thread should kill the connection thread. It’s ugly, but it works.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.