Synchronized in Iterator..??

I have some problem with handling Vector.
I use Vector because of multi-thread - that is to say, to use synchronized in Vector.
As you know, Vector can produce Iterators. But the Iterators seems to not synchronized.
Suppose the case when two thread do with two Iterators from a Vector. If thread 1 iterates its element while thread 2 removes them, what happen??
How can I synchronize the array shared with the Vector & two of Iterators??

How can I synchronize the array shared with the
Vector & two of Iterators??Since you're going to have to do synchronization beyond what the Vector provides, using the Vector class isn't a good idea, because now you're synchronizing twice. I'd use ArrayList, and then pick an object (perhaps create a class that holds the array, ArrayList, and iterators) and synchronize once on that object.

Similar Messages

  • Reposting: Question regarding iteration over synchronized list

    [added proper markup]
    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
         * Create new animals from existing animals
         * @return The cohort of newborn animals
        public List<IAnimal> regenerate() {
            List<IAnimal> children = new ArrayList<IAnimal>();
            synchronized (animalList) {
                Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
                 while (it.hasNext()) {
                     IAnimal a = it.next();
                     if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
                         IAnimal child = a.reproduce();
                         children.add(child);                    // newborns
    //                     animalList.add(child);                    // the whole population  //THROWS CME!
                 animalList.addAll(children);                                     // does not throw CME
            return children;
        }Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
          List<IAnimal> backingList =
                new LinkedList<IAnimal>() {
                     * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
                     * try again.
                     * @param   animal  The animal to be added
                     * @return  true
                    public boolean add(IAnimal animal) {
                        boolean added = false;
    outer:
                        do {
                            // synchronized (this) {                // DIDN'T HELP
                            Iterator<IAnimal> iAnimals = iterator();
                            while (iAnimals.hasNext()) {
                                //FIXME: this algorithm assumes square animals
                                Point existingAnimalLocation = iAnimals.next().getLocation();
                                double distance = existingAnimalLocation.distance(animal.getLocation());
                                if (distance < animal.getSize().getWidth()) {
                                    animal = new Animal();
                                    continue outer;
                            //}  //end unhelpful synchro block
                            super.add(animal);
                            added = true;
                        while (!added);
                        return added;
                    } // end method add
                };

    Jefferino wrote:
    spoon_ wrote:
    By the way that Iterators in Java are designed, you are not allowed to modify a list as you iterate over it.
    Not true: Iterator.remove().
    Edited by: Jefferino on Mar 20, 2008 2:24 AMOh yeah, you can modify it using the iterator's methods; but not using any of the collection's methods, like add().

  • Question regarding iteration over synchronized list

    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
    * Create new animals from existing animals
    * @return The cohort of newborn animals
    public List<IAnimal> regenerate() {
    List<IAnimal> children = new ArrayList<IAnimal>();
    synchronized (animalList) {
    Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
         while (it.hasNext()) {
         IAnimal a = it.next();
         if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
         IAnimal child = a.reproduce();
         children.add(child);                    // newborns
    //     animalList.add(child);                    // the whole population //THROWS CME!
         animalList.addAll(children); // does not throw CME
    return children;
    Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
    List<IAnimal> backingList =
    new LinkedList<IAnimal>() {
    * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
    * try again.
    * @param animal The animal to be added
    * @return true
    public boolean add(IAnimal animal) {
    boolean added = false;
    outer:
    do {
    // synchronized (this) {                // DIDN'T HELP
    Iterator<IAnimal> iAnimals = iterator();
    while (iAnimals.hasNext()) {
    //FIXME: this algorithm assumes square animals
    Point existingAnimalLocation = iAnimals.next().getLocation();
    double distance = existingAnimalLocation.distance(animal.getLocation());
    if (distance < animal.getSize().getWidth()) {
    animal = new Animal();
    continue outer;
    //} //end unhelpful synchro block
    super.add(animal);
    added = true;
    while (!added);
    return added;
    } // end method add
    };

    Your code is not formatted (use code tags for this) but it seems to me that you add elements to the list while you iterate over it, hence a ConcurrentModificationException is thrown. Use a ListIterator if you want to add to the list while iterating.

  • Synchronized object problem

    Information on the API specification pages shows that
    to iterate through an ArrayList requires synchronization to avoid ConcurrentModificationException. I have written the code (also found in the Java tutorial) and get a type
    require or } missing error even if I put the code in a method, a solution suggested elsewhere in the forum.
    I want a button to iterate to the next item in the ArrayList.
    Here's the code :
    public class Targets extends javax.swing.JFrame {
    List vocTar =
    Collections.synchronizedList(new ArrayList());
    synchronized(vocTar) {
    Iterator gB = vocTar.iterator();
    The closing brace comes later after much code.
    What's up.

    Can you post the full code. Or maybe send it to
    [email protected]
    I guess this should be relatively easy to crack.
    Best Regards,
    Manish

  • Synchronized and java.util.ConcurrentModificationException

    Hi,
    I keep getting a java.util.ConcurrentModificationException when running the following code:
    ArrayList tObjects = ...
    synchronized (tObjects) {
    Iterator tObjectsIterator = tObjects.iterator();
    while (tObjectsIterator.hasNext()) {
    Object tObject = tObjectsIterator.next(); -----> Exception
    I run synchronized on tObjects so I can't understand why (and how) I get the Exception, can anyone help?
    Thanks,
    Iggy

    thanks for the help, I still have some difficulties:
    I have a (static) class ObjectsHolder which holds an ArrayList tObjects, I have various methods that access the ArrayList and return one/some elements.
    I would like to synchrinize on the ArrayList tObjects in ObjectsHolder, but the holder returns the ArrayList itself I am unsure whether the access to the ArrayList will be synchronized even in the calling method.
    A.

  • ConcurrentModificationException in synchronized block?

    Edit: Narrowed it down to this:
    Caused by: java.util.ConcurrentModificationException: null
         at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
         at java.util.LinkedList$ListItr.next(Unknown Source)
         at server.ConversationServiceImpl.clientExit(ConversationServiceImpl.java:28)
    public void clientExit() {
         String currentUserId = getCurrentUserId();
         synchronized(users) {
              Iterator<User> it = users.iterator();
              while(it.hasNext()) {
                   User aUser;
                   synchronized(aUser = it.next()) { // Line 28
                        if(aUser.getId() == currentUserId) {
                             users.remove(aUser);
         UserList userList = new UserList(getUserListStrings());
         addEventToAllUsers(userList);
    }Surely since there is a synchronized block, there shouldn't be any ConcurrentModificationException?
    Edited by: ta2 on 29-Mar-2009 02:22

    Maxideon wrote:
    Not really. The problem was this line
    users.remove(aUser);When you are iterating through a collection you're suppose to remove elements with the iterator.
    it.remove();You also seem to be using synchronize blocks of code kind of haphazardly.
    For example in your original post you had a synchronized block around an object in local scope.
    synchronized(aUser = it.next()) {
    Yeah you're right... I don't really know what I'm doing with the synchronized blocks. Though another thread could get that particular user by going users.get(int thatOne), but I've already blocked that with the synchronized(users) bit. Is that what you mean?
    Cheers

  • Why is it necessary to make the block synchronized while iteratiing

    Why is it necessary to make the block synchronized while iteratiing thru Synchronization Wrappers?
    here is the code sample for same:
    Collection c = Collections.synchronizedCollection(myCollection);
    synchronized(c) {
    Iterator i = c.iterator(); // Must be in synchronized block!
    while (i.hasNext())
    foo(i.next());
    }

    If at the first place I am getting all the methods synchronized by calling
    Collection c = Collections.synchronizedCollection(myCollection);
    that means no two threads can enter the data structure of this collection, I am not getting how ConcurrentModificationException will be thrown while iterating thru this collection?
    Can u please explain in a little depth?

  • ConcurrentModificationException on a synchronized set

    Thanks to anyone who can help me here - I'm very confused.
    I have a class WebAppUtility that looks like this:
    private static Set<HttpSession> openSessions = Collections
                   .synchronizedSet(new HashSet<HttpSession>());
         public static void addSession(HttpSession session) {
              synchronized(openSessions){
                   openSessions.add(session);
         public static boolean removeSession(HttpSession session) {
              synchronized(openSessions){
                   return openSessions.remove(session);
         public static Set<String> getLoggedInUsers() throws Exception {
              Set<String> set = new HashSet<String>();
              synchronized (openSessions) {
                   for(Iterator i = openSessions.iterator(); i.hasNext();){
                        HttpSession session = (HttpSession)i.next();
                                  //grab attribute from session here and stick in "set"
              return set;
         }Somehow when I have many users logging in and out I'm getting a ConcurrentModificationException under the getLoggedInUsers method:
    java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
    at java.util.HashMap$KeyIterator.next(HashMap.java:823)
    at com.studentuniverse.utility.WebAppUtility.getLoggedInUsers(WebAppUtility.java:68)
    Line 68 is the one that looks like:
    HttpSession session = (HttpSession)i.next();Am I misusing the synchronizedSet in some way? Please guide me to proper threaded Set usage! Thank you very much.
    _kris                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You need to synchronize around your iterator.
        synchronized(tempSet) {
                   for(Iterator i = tempSet.iterator(); i.hasNext();){
                        HttpSession session = (HttpSession)i.next();
                        try {
                             Principal p = (Principal) session.getAttribute("so_user");
                             if (p != null) {
                                  set.add(p.getName());
                        } catch (Exception e) {
                             log.warn("error when getting attribute from session");
        }From [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#synchronizedSet(java.util.Set)]Collections.synchronizedSet
    Returns a synchronized (thread-safe) set backed by the specified set. In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set.
    It is imperative that the user manually synchronize on the returned set when iterating over it:
      Set s = Collections.synchronizedSet(new HashSet());
      synchronized(s) {
          Iterator i = s.iterator(); // Must be in the synchronized block
          while (i.hasNext())
              foo(i.next());
      }Failure to follow this advice may result in non-deterministic behavior.

  • Are Collection classes synchronized.

    I learned from the ver 1.2, which was the first to add collections framework that the collection classes were not synchronized and as such a programmer had to do it manually.
    What about in 1.4 and 1.5? Plz guide me.
    or
    plz give me some docs/links of help.

    There is a Collection class, which is the base class for all collections (such as List, Set, Map). Then there is a Collections class...which is like a Collection utility class...actually, i thin that's exactly what it is. If so, they should have called it CollectionUtil...when i first saw this class..it was confusng at first...then i noticed the "s" in Collection
    THe "Collections" class provides method to synchronize your "collection"
        List list = new ArrayList();   // unsynchronize list
        list = Collections.synchronizedList(list);  the 2nd line basically, say...use the collection utility class to create a wrapper around the list objject and make the list synchronized....return the wrapper 9wich is a synchronized list)
    to iterate over the collection
    synchronized(list) {
          Iterator i = list.iterator(); // Must be in the synchronized block
          while (i.hasNext())
             foo(i.next());
    }example taken from the Sun Java Collections API

  • Key Handler

    //My source code:
    package keyhandler;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import javax.swing.JFrame;
    public class Handler implements KeyListener {
    private boolean FINISH = true;
    private Set<Integer> set;
    *@param args*
    public Handler() {
    set = Collections.synchronizedSet(new HashSet<Integer>());
    public void handle() {
    while (FINISH) {
    synchronized (set) {
    Iterator<Integer> i = set.iterator();
    String k= "";
    while (i.hasNext()) {
    int key = i.next();
    switch (key) {
    case 27: FINISH=false;break;
    case 38:k = k.concat(" Up");break;
    case 39:k = k.concat(" right");break;
    case 40:k = k.concat(" down");break;
    case 37:k = k.concat(" left");break;
    default :k = k.concat(" "+key);break;
    System.out.println(k);
    System.exit(0);
    public static void main(String[] args) {
    Handler handler = new Handler();
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.addKeyListener(handler);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    handler.handle();
    @Override
    public void keyPressed(KeyEvent arg0) {
    synchronized (set) {
    set.add(arg0.getKeyCode());
    @Override
    public void keyReleased(KeyEvent arg0) {
    synchronized (set) {
    set.remove(arg0.getKeyCode());
    @Override
    public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub
    // I 've got this code to handle keys. I am making an interface for a game and I would like to handle more than one key at same time. I want to handle the arrow keys. It seems to be fine except when I am holding down the Up arrow key i can hold just another key at same time.
    Example :
    Down Left Right - holding down left and right arrow key at same time
    Up left - with up arrow key i can hold just another one key. Not more.
    Can anybody help me to sort out this source?

    Thanks for your idea, very cool very useful
    [fresh fridays |http://reggae-cd.net/fresh-fridays-reggae-dance-in-jamaica]
    [passa passa DVD |http://reggae-dvd.com/passa-passa-reggae-music-and-dancing]
    [passa passa  |http://bestreggaemusic.com/passa-passa-90-mavado-fall-rain-fall-official-dance]
    [reggae videos|http://reggae-dancehall.net/crabb-up-friday-dancehall-reggae]

  • Custom event handling

    Hi,
    Please could someone help? I've been working my way through
    the examples in the book 'essential guide to flex 2 and
    actionscript 3.0'. When working through the example in chapter 10
    I've been unable to get the custom CartEvent event of type
    bookSelected to run.
    I've stored the
    small set of files in a
    zip... please could someone tell me where I'm going wrong?
    Thanks.
    Craig

    The most common definition for fireXXXEvent...public void fireXXXEvent(XXXEvent event) {
        synchronized (xxxListenerList) {
            Iterator i = xxxListenerList.iterator();
            while (i.hasNext()) {
                ((XXXListener) i.next()).xxx(event);
    }Firing the event is simple. Firing the event in a dedicated event-handling thread (a-la AWT) is less simple - set up an event queue (a-la java.awt.EventQueue) to oversee the event handling thread.
    Depending on your circumstances, chances are you won't need a separate thread. In fact, unless you specifically require multi-threading, things will be much simpler if you stick to a single thread.
    There's nothing magical about events - it is simply a useful logical representation of a physical model.

  • Can someone show me how to use sorted/tree set

    i have a server program, and i want to create a sortedset, then everytime a client connects an element(nickname) is added to the sortedset.. i have to create a syncronized one
    i need to know how to add elements, and read elements one-by-one into a string.. thanks in advance..
    -adam

    i have this so far, can someone show me where i have gone wrong plz
    public class Server
      // ServerSocket used for accepting new connections
      private ServerSocket serverSocket;
      // A mapping from sockets to DataOutputStreams. This stores all
      // Dataoutput stream information so it can easily send to all clients
      private Hashtable outputStreams = new Hashtable();
      static SortedSet nicktree;
      static Iterator i;
      // Constructor, while-accept loop
      public Server( int port ) throws IOException {
         nicktree = Collections.synchronizedSortedSet(new TreeSet());
         listen( port );
      }this is the method that stores one value, then has a loop reading each value one-by-one and sending it..
      void storenick(String nick){
         synchronized(nicktree) {            
            Iterator i = nicktree.iterator();
            nicktree.add(nick);
            while (i.hasNext())  {  
               String sendnext = (nicktree) i.next();
               sendToAll(sendnext);
      }thanks in advance
    --Adam                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

  • Observable/observer nightmare

    I'm currently simulating a robot with a graphical front end linked to a model using a model-view architecture. In fact there are two views running in parallel: a graphical representation and a set of JLabels displaying parameters of the model as they change. I have recently discovered that making the model extend the Observable class and the views implement the Observer interface is the way forward.
    However, this has messed up my architecture. Before, the model was a member of both the view classes. i.e. the model does not see the views. Unfortunately, the model needs to see the views to register them as Observers. What can be done? Is there a simple example of how to use the observing techniques properly?

    You also wanted an example, so, here goes.....
    Assuming that you dont change your listeners very much (and by the sounds of it, you dont), you can do something like the following (If you do change them around quite a bit, consider using AWTEventMulticaster).
    // The model that you can watch:
    public interface RobotModel
      public void addRobotListener(RobotListener r);
      public void removeRobotListener(RobotListener r);
    // The listener
    public interface RobotListener
      /* Note: You may want to consider giving an actual
         'change event' to describe the change - but In the
         simple case, your view can query the model when
         it knows it's been updated
      public void robotModelChanged(RobotModel aModel);
    // Impl
    public class YourModel implements RobotModel
      private List mListenerList;
      public YourModel()
       mListenerList=new LinkedList;
      public void addRobotListener(RobotListener aListener)
        /* Need to sync on the list - if you add/remove quite
           a lot, consider AWTEventMulticaster instead
        synchronized(mListenerList)
          if(!mListenerList.contains(aListener))
            mListenerList.add(aListener);
      public void removeRobotListener(RobotListener aListener);
        /* Again, sync on the list  */
       synchronized(mListenerList)
          mListenerList.remove(aListener);
      protected void pNotify()
        /* Call this when you want to notify your listeners
           of a change to your model
        synchronized(mListenerList)
          Iterator anIterator=mListenerList.iterator();
          while(anIterator.hasNext())
            RobotListener aListener=(RobotListener)anIterator.next();
            // Do the notification:
            aListener.robotModelChanged(this);
      /* Example of changing something */
      public void changeSomethingInTheModel()
        // Do the change, then:
        pNotify();
    // Your view:
    public class ViewImpl implements RobotListener
      private RobotModel mModel;
      public ViewImpl(RobotModel aModel)
        // You said the view knew about the model:
        mModel=aModel;
        // register as a listener to the model:
        mModel.addRobotListener(this);
      // We receive notification of changes thru this method:
      public void robotModelChanged(RobotModel aModel)
        if(aModel!=mModel)
          // receiving dodgy notification!
          // (probably dont need this check in practice!)
        else
          // Model updated - query the model and update
          // the view!
    }Note that your model does NOT need to know about a view - it just needs to know about a RobotListener.
    Dave.

  • ConcurrentModificationException when operating on an ArrayList

    Hi,
    I've got a strange problem. I'm working with a heavily multithreaded program. I have the following code:
    public abstract class GHAgentTaskThread implements Runnable, GenericObserverSubject {
    protected List observingResultDispatchers = new ArrayList();
    public final void addObserver(GenericObserverObserver subscriber) {
    synchronized (observingResultDispatchers) {
    observingResultDispatchers.add(subscriber);
    public final void removeObserver(GenericObserverObserver subscriber) {
    synchronized (observingResultDispatchers) {
    observingResultDispatchers.remove(subscriber);
    protected final void notifyObservingDispatchers() {
    synchronized (observingResultDispatchers) {
    Iterator i = observingResultDispatchers.iterator();
    GenericObserverObserver currentObserver;
    while (i.hasNext()) {
    currentObserver = (GenericObserverObserver) i.next(); //****
    currentObserver.notify(this);
    observersIterator = null;
    //Other stuff
    public class TokenryServerRequestTokenTask
    extends GHAgentTaskThread
    implements Runnable {
    public void run() {
    //do some stuff
    notifyObservingDispatchers();
    I have an external class which creates a new instance of the thread:
    GHAgentTaskThread myThread = new TokenryServerRequestTokenTask();
    It then adds itself as a listener:
    myThread.addObserver(this);
    This all works ok. I then start then thread and it goes and does the work I've specified. However, at the end of the run method when I try and notify the observers that the work is done with notifyObservingDispatchers(), I'm getting a:
    java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:444)
    at java.util.AbstractList$Itr.next(AbstractList.java:421)
    The line this is happeneing at is the :
    currentObserver = (GenericObserverObserver) i.next();
    line, which I've marked //**** in the code above.
    Why is this happening? I thought, that given I've synchronized all of the code that deals with the List (which is private) on the List itself that only one thing could be operating on it at one time, and hence this shouldn't occur. Strangely enough too, it doesn't seem to be affecting my program either - it works. However, exceptions are not thrown for no reason!
    If anyone can suggest how this could be sorted I'd be very grateful.
    Many thanks,
    Stu

    To englarge slightly on what _JN said, I speculate
    that when your GenericObserverObserver.notify() method
    is called, it calls one of your other methods in a way
    that modifies the list.
    cut
    Got it in one - I've just spotted that. I was attempting to remove the observer from the subject from within the GenericObserverObserver.notify() method... whoops!
    Cheers for the suggestion about the LinkedList - that's also a good idea.
    Thank you both for your help.
    Cheers,
    Stu

Maybe you are looking for

  • How do I easily transfer itunes back to my Macbook Pro?

    I transferred my whole iTunes folder from my Macbook Pro onto my Time Capsule in order to save space on my Macbook Pro. However this has caused plenty of problems especially when opening iTunes on my Macbook and it not being able to find the library.

  • Translation UTF8 - ISO-8859-1

    Hi there, When translating a UTF8 file to ISO-8859-1 during loading of that file (using dbms_lob.loadclobfromfile) I notice that an UTF8 right single quotation mark ' (2019) is converted to an inverted quotation mark ¿. The left single quotation mark

  • Boot Fail after latest BIOS Update on Flex 2-15D

    Hi everyone, I have a severe problem (I guess) after the latest BIOS Update. Windows 7 freezes during startup. I own a 64-bit Lenovo FLex 2 15D with AMD A6-6310 and R4, 4GB RAM and a SSHD (8GBSSH). I purchased it without OS and installed Windows 7 -

  • TM backup - How large would you set the partition for a 105gb HD?

    I'm preparing to upgrade from Snow Leopard to Mountain Lion and am making a TM backup to a 1TB external harddrive that has 500gb free, using Disk Utility to create a new partition. The size of the hard drive to backup is 105gb with 22gb remaining. Ho

  • Photoshop CC error opening

    I can't open Photoshop CC. When trying to open it after a second of initializing blue intro panel appears an initializing photoshop error. I was working fine with photoshop CS6 with no probs. After installing CC and disinstalling CS6 no way to use ph