In Java, I am creating 256 threads which communicate with each other using network socket. All this 256 threads run in parallel. When a thread is spawned, it tries to connect to its neighbor threads. The list of neighbors can be arbitrary. In this situation, how to ensure that all the threads create a connection with their neighbors
- without deadlock
- without a star topology (central node)
In order to form a connection between two threads, one thread has to open a ServerSocket and other thread must join it. Currently, I am using a simple algorithm :
for all edges
do
if edge.tid > my tid
then
connect to edge.ip
endif
done
for all edges
do
if edge.tid < my tid
then
accept connection from edge.ip
endif
done
As you can see above, I am first connecting to bigger neighbors and then I am waiting for smaller neighbor to connect to me. This can result in a deadlock when the neighborhood table looks as given below :
t0 -> t3, t1
t1 -> t2, t0
t2 -> t1
t3 -> t0
Any specific algorithm in your mind which is deadlock free ?? My algorithm uses blocking connect and accept methods in java. I have a feeling this can be done using non-blocking methods but want to know the other ideas first.
FYI, my algorithm works perfectly well for a mesh topology (at-least I think it does).