diff --git a/bramble-core/src/main/java/org/briarproject/bramble/plugin/bluetooth/BluetoothPlugin.java b/bramble-core/src/main/java/org/briarproject/bramble/plugin/bluetooth/BluetoothPlugin.java index 9b4ba5bb9..a18cbf8b6 100644 --- a/bramble-core/src/main/java/org/briarproject/bramble/plugin/bluetooth/BluetoothPlugin.java +++ b/bramble-core/src/main/java/org/briarproject/bramble/plugin/bluetooth/BluetoothPlugin.java @@ -26,7 +26,10 @@ import org.briarproject.bramble.util.StringUtils; import java.io.IOException; import java.security.SecureRandom; +import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; @@ -252,28 +255,35 @@ abstract class BluetoothPlugin implements DuplexPlugin, EventListener { @Override public void poll(Collection connected) { if (!isRunning() || !shouldAllowContactConnections()) return; - backoff.increment(); - // Try to connect to known devices in parallel + // Try to connect to known devices in a random order Map remote = callback.getRemoteProperties(); + List> entries = new ArrayList<>(); for (Entry e : remote.entrySet()) { - ContactId c = e.getKey(); - if (connected.contains(c)) continue; - String address = e.getValue().get(PROP_ADDRESS); - if (StringUtils.isNullOrEmpty(address)) continue; - String uuid = e.getValue().get(PROP_UUID); - if (StringUtils.isNullOrEmpty(uuid)) continue; - ioExecutor.execute(() -> { + if (connected.contains(e.getKey())) continue; + TransportProperties p = e.getValue(); + if (StringUtils.isNullOrEmpty(p.get(PROP_ADDRESS))) continue; + if (StringUtils.isNullOrEmpty(p.get(PROP_UUID))) continue; + entries.add(e); + } + if (entries.isEmpty()) return; + Collections.shuffle(entries); + backoff.increment(); + ioExecutor.execute(() -> { + for (Entry e : entries) { if (!isRunning() || !shouldAllowContactConnections()) return; if (!connectionLimiter.canOpenContactConnection()) return; + TransportProperties p = e.getValue(); + String address = p.get(PROP_ADDRESS); + String uuid = p.get(PROP_UUID); DuplexTransportConnection conn = connect(address, uuid); if (conn != null) { backoff.reset(); if (connectionLimiter.contactConnectionOpened(conn)) - callback.outgoingConnectionCreated(c, conn); + callback.outgoingConnectionCreated(e.getKey(), conn); } - }); - } + } + }); } @Nullable