0

Hi i have made a something that extends thread that adds adds an object that has a IP in it. then i made two instances of this thread and started them. they use the same list.

I now want to use Synchronized to stop the concurrent update problem. But its not working and i cant work out why.

My main class:

import java.util.*;
import java.io.*;
import java.net.*;

class ListTest2 {
    public static LinkedList<Peer>  myList = new LinkedList<Peer>();

    public static void main(String [] args) {   
        try {
            AddIp test1 = new AddIp(myList);
            AddIp test2 = new AddIp(myList);

            test1.start();
            test2.start();      
        } catch(Exception e) {
            System.out.println("not working");
        }
    }
}

My thread class:

 class AddIp extends Thread {
     public static int startIp = 0;

     List<Peer> myList;

     public  AddIp(List<Peer> l) {
         myList = l;
     }


     public synchronized void run() {      
        try {
            startIp = startIp+50;
            int ip = startIp;
            InetAddress address = InetAddress.getByName("127.0.0.0");
            Peer peer = new Peer(address);

            while(ip <startIp+50) { 
                ip++;
                address = InetAddress.getByName("127.0.0."+ip);

                peer = new Peer(address);

                myList.add(peer);

                if(myList.indexOf(peer)== (myList.size() -1)) {
                } else {
                    System.out.println("Lost"+peer.peerIp);
                }
            }     
        } catch(Exception e) {
        }
    }
}

Can anyone help me out here im lost for ideas thanks.

Bex
  • 2,905
  • 2
  • 33
  • 36
1ftw1
  • 656
  • 2
  • 14
  • 26

4 Answers4

5
 public synchronized void run() 

Synchronizes on calling instance: this.

So, 1st thread synchronizes on test1 and 2nd thread synchronizes on test2, which doesn't help at all.

You want to synchronize on the shared resource, in this case: myList

public void run() {
  synchronize(myList){
   //your Logic
  }
}

As a side note: Implement runnable instead of extending a Thread. Read more here.

Community
  • 1
  • 1
rocketboy
  • 9,573
  • 2
  • 34
  • 36
1

You'd be better off implementing Runnable oppose to extending thread

also

public void run() {
  synchronize(list){
   //stuffs
  }
}
mcr619619
  • 435
  • 1
  • 4
  • 13
0

they use the same list.

You can try to use Vector instead List. Vector is synchronized

or set your List to be synchronized:

List myList = Collections.synchronizedList(myList);

instead to use:

synchronize(myList){

 } 
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
0

The easiest way is to use a List implementation that can handle multiple threads. Try CopyOnWriteArrayList.

Bex
  • 2,905
  • 2
  • 33
  • 36