Synchronization in Vector

I read that the class Vector is synchronized, but does this mean that it automatically synchronizes access from different threads or is it another feature?
If it is another feature, do I have do synchronize both the Vector as the elements that it contains? Thank you for the answer!
BlueRibbon

it means it's thread safe. for the other collections have a look at Collections.synchronizedSet( ... ) and the like methods.
robert

Similar Messages

  • Vector did not retrun the correct values.

    in my class the vector use BigDecimal not bigInteger. but my problem now is that my vector retruns the first value stored in vector until the loop completed.
    the following is print statment while I add to the vector:
    while (rs.next())
         CustNum=rs.getBigDecimal("CustNum");
         CType = rs.getString("TYPE");
         row.addElement(CustNum);
         row.addElement(CType);
         ret.addElement(row);
         System.out.println(CustNum);
    ***********1119
    ***********2220
    ***********3331
    but in my JSP:
    Vector v = new getNumber().getCustNumber();
    Iterator i = v.iterator();
    while (i.hasNext()) {
    Vector row = (Vector)i.next();
    Object CustNum = row.get(0);
    Object name = row.get(1);
    system.out.println(CustNum);
    that retrun the wrong result:
    ***********1119
    ***********1119
    ***********1119

    As warnerja said, you apparently only have multiple references to the same 'row' in your 'ret' Vector.
    If your code in your post is exactly your actual code, then you are adding the same Vector to 'ret' multiple times. That Vector will have two values (CustNum and CType) for each row.
    So, your 'ret' will have three elements, each with six elements (I separated the elements with commas):
    ret.get(0):   ******1119, Type1, ******2220, Type2, ******3331, Type1
    ret.get(1):   ******1119, Type1, ******2220, Type2, ******3331, Type1
    ret.get(2):   ******1119, Type1, ******2220, Type2, ******3331, Type1Each element of 'ret' is identical--you have three copies of the same Vector.
    In your loop to populate 'ret', initialize 'row' to a new Vector at the beginning of each loop iteration. Also, you may want to try using ArrayList instead of Vector. You probably don't need the synchronization that Vector gives. Even if you do need synchronization, use Collections.synchronizedList(new ArrayList()).

  • Vectors in java

    I have created a vector inside vector
    Now my vector contains [one,two ,three]
    I want to display the contents of this vector in fashion
    two
    one
    three
    How can I do that?

    I use vectors bcos each time i run my application it has to store randomly generated data, whose length i cant pre-determine.ArrayList will adjust the length for you. Just use java.util.ArrayList instead of java.util.Vector. It will do the same thing, only faster (if you need the synchronization that Vector provides, there are methods in java.util.Collections to help you with that).
    May I now ask another question, I am looking for random number distribution generator in java. i could
    write one, but i figured i will just reuse. this will be different from the Math.random or rand() in java.
    I need it for a random exponential distribution.If nothing in java.util.Random works, then you could write your own, possibly using the output of those methods as a starting point. Otherwise, there are probably pre-existing Java exponential distribution classes on the web if you search for them.

  • Guide: Optimizing Your Windows XP/Vista Notebook

    purpose:
    to build a highly optimized, personalized, faster, smaller and more secure OS installation using windows xp (can use vista also but this guide will not cover it in any detail)
    plus i was bored to tears
    information:
    this is a somewhat advanced guide not meant for those unfamilure with the tools and techniques used here
    the basics of this guide can be applied to most/all windows xp/vista notebooks and desktops, not just Lenovo, however in my case i run windows xp pro on a T60 (8743) with an add-on graphics card (similar to a T60p i assume) and this guide will be geared toward this config.
    many alterations can be made, so it is very general in nature and should not be taken literally
    this is my personal machine and i am not on a private network. you may have to adjust as necessary.
    disclaimer:
    it ain't my fault
    what will you gain:
    * a highly customized OS
    * faster boot times
    * more free disk space
    * a lighter, snappier feeling OS
    * a more secure OS
    * a more stable OS
    * more free RAM
    * less problems (or maybe more if you're not careful)
    with all due respect to Lenovo, i have found that the less Lenovo software i install the fewer glitches i have and the faster things run. this is often the case for various other hardware vendors that supply proprietary software which is often not needed, or not all of which is needed.
    what you will need: (all free, except for possibly the OS):
    * a windows xp/vista installation disk. though you may be able to do this using your i386 directory (perhaps on the recovery partition), a full, non-OEM disk is preferred.
    * SP2 and SP3 (it is my understanding that either SP1 or SP2 should be installed before installing SP3, though i have built installations with SP3 only).
    * dotNet runtime
    * nLite (or vLite for vista) - http://www.nliteos.com/
    * Ryan's Windows XP Post-SP3 Update Pack - http://www.ryanvm.net/msfn/
    * Ryan's integration tool - http://integrator.siginetsoftware.com/index.php?do​wnload
    * all current drivers for your hardware
    please read any license agreements for the above (for instance, nLite is not to be used for commercial applications)
    also visit the nLite and RyanVM forums as there's a ton of helpful info there, add-on packs, etc., and please consider donating to them both if you like the software. both are great guys. i wouldn't bother running windows anymore without nLite. from Nuhi's page (his english is not the best):
    Have you ever wanted to remove Windows components like Media Player, Internet Explorer, Outlook Express, MSN Explorer, Messenger...
    How about not even to install them with Windows ?
    nLite is a tool for pre-installation Windows configuration and component removal at your choice. Optional bootable image ready for burning on media or testing in virtual machines.
    With nLite you will be able to have Windows installation which on install does not include, or even contain on media, the unwanted components.
    Features
    * Service Pack Integration
    * Component Removal
    * Unattended Setup
    * Driver Integration *
    * Hotfixes Integration **
    * Tweaks
    * Services Configuration
    * Patches ***
    * Bootable ISO creation
    basic build procedure:
    * install the dotNet runtime
    * install nLite (or vLite for vista)
    * create a directory structure something like:
    c:\nlite\source\
    c:\nlite\working\
    c:\nlite\sp\
    c:\nlite\hotfix\
    * download Ryan's post SP3 update pack and dump it in c:\nlite\hotfix\
    * download Ryan's integration tool and dump in c:\nlite\hotfix\ 
    note that you can use nLite to integrate service packs and hotfix's, but i prefer Ryan's tool as i have had problems in the past using nLite to integrate Ryan's post SP update cabs, though this happened during the earlier beta days of nLite.
    * download xp SP2 and SP3 service packs and dump in c:\nlite\sp\
    * copy contents of windows installation disk to c:\nlite\source\
    * using Ryan's integrator, set update pack path to c:\nlite\sp\WindowsXP-KB835935-SP2-ENU.exe, windows source to c:\nlite\source\, and destination to c:\nlite\working\ and start integration
    * using Ryan's integrator, set update pack path to c:\nlite\sp\WindowsXP-KB936929-SP3-x86-ENU.exe set windows source to c:\nlite\working\ and destination to c:\nlite\working\ and integrate SP3. after SP3 is integrated, if you want to save the windows installation for the next time you install, copy it elsewhere before moving on.
    *  using Ryan's integrator set source to c:\nlite\hotfix\ (where you dumped Ryan's post SP3 update cab) and destination to c:\nlite\working\ and run it.
    * start nLite and set the windows installation path to c:\nlite\working\
    make sure that, in the "version" box, that SP3 is written, otherwise you've made an error earlier.
    IMPORTANT: when using nLite be very careful and move slowly, making sure to READ ALL DESCRIPTIONS and explore all options -- it's easy to skip or screw up something if you're not very careful. 
    rule of thumb: don't remove something if you don't know what it is or what the implications might be
    * following the wizard, select your options. i would suggest the following:
    remove components
    unattended
    options
    patches
    tweaks
    build ISO
    in the case of my thinkpad my hard drive will not be recognized by windows unless i integrate the driver for the SATA controller using nLite OR enter BIOS setup and put the controller in compatibility mode so i can install the driver from windows (after which BIOS needs to be changed again).  integrating drivers will require extra reading on your part and is beyond what i wish to get into here, so, to make things easy if you're not comfortable doing this, just put your controller in compatibility mode if necessary and install the driver from within windows.
    * following the wizard and hitting "next" as necessary, if you've selected the options above, nLite will pop-up a compatibility options window where you want to select what components you really need (prevents you from removing dependancies later).
    * in the next step you'll remove unwanted components - the part i enjoy most.  be careful what you remove! stuff in red is important. this is what i typically remove, give or take:
    Accessibility Options
    Briefcase
    ClipBook Viewer
    Defragmenter (replaced with JKDefragGUI)
    Games
    Internet Games
    Paint
    Pinball
    Screensavers (useful only for very old CRT monitors)
    WordPad (replaced with PSPad)
    Keyboards (i remove all - nLite will keep default for your language)
    ActiveX for streaming video (depends on IE which i remove parts of)
    AOL ART Image Format Support (depends on IE which i remove parts of)
    Images and Backgrounds (desktop eye candy)
    Luna desktop theme (cartoonish desktop theme)
    Media Center
    Mouse Cursors
    Movie Maker
    Music Samples
    Old CDPlayer and Sound Recorder (replaced in part by foobar2000)
    Speech Support
    Tablet PC
    Windows Media Player (replaced by foobar2000, VLC and Satsuki codec pack)
    Windows Media Player 6.4 (replaced by foobar2000, VLC and Satsuki codec pack)
    Windows Picture and Fax Viewer (replaced by XnView)
    Windows Sounds (unneeded sound themes)
    Communication tools (phone dialer, hyperterminal, etc., some replaed by better 3rd part s/w)
    FrontPage Extensions
    Internet Connection Wizard (not needed to create a connection)
    Internet Explorer (i keep the core (there's 2 options for removing this; one to remove parts but keep basic functionality and another to remove the core, which i suggest keeping) as it's functionality is needed by many applications - removing this will remove the "Program Files\Internet Explorer" directory, but you can still browse the web using windows explorer (file manager) if need be. i replace with Firefox)
    Internet Information Services (IIS) (i use Apache (WAMP) for web development)
    IP Conferencing
    MSN Explorer (partially replaced with Miranda IM)
    Netmeeting
    Outlook Express (replaced with Thunderbird)
    Peer-to-Peer (only for MS networks, nothing to do with P2P)
    Share Creation Wizard
    Synchronization Manager
    Vector Graphics Rendering (VML) (depends on IE i think, which i remove parts of)
    Web Folders
    Windows Messenger (replaced with Miranda IM
    .NET Framework (i don't install this at all)
    Blaster/Nachi removal tool
    Color Schemes (predefined desktop color schemes)
    Desktop Cleanup Wizard (replaced with CCleaner)
    Disk Cleanup (replaced with CCleaner)
    File and Settings Wizard (used to transfer settings between 2 computers)
    File System Encryption (try TrueCrypt or AxCrypt - note that MS encryption is propritary and, as such, should not be trusted)
    Help and Support (huge space hog)
    IExpress Wizard
    Manual Install and Upgrade (ability to upgrade OS, which is always a bad idea (better to install clean))
    MS Agent (used for annoying animated paperclip in MS office)
    Out of Box Experience (OOBE) (do NOT remove unless you have a VLK)
    Remote Installation Services (RIS)
    Search Assistant (annoying animated dog in search window)
    Security Center (replaced with Comodo firewall)
    Service Pack Messages
    Shell Media Handler
    Tour (useless windows tour)
    User account pictures
    Web View
    Zip Folders (replaced with IZArc and Universal Extractor)
    Automatic Updates (hardly needed once attack vectors are removed)
    Beep Driver (annoying beep, such as when you press too many keys at once)
    Error Reporting (automitic error reporting to MS - i suppose vista is the result?)
    IMAPI CD-Burning COM Service (replaced with ImgBurn)
    Remote Registry
    Secondary Logon
    System Restore Service (bloated nonsense used for restoring viruses to their orgional state - better to reinstall)
    Languages (i remove all - nLite will keep your default language)
    as should be apparent from the above, security is already enhanced since many attack vectors were removed (OE, WMP, MSN, remote registry, system restore, etc., etc., etc.).
    missing functionality is replaced by better, more functinal and more secure software
    * for the "unattended setup" step, you can select many options, change default paths (Program Files), disable hibernate, configure network adapters and much more.
    * next is "options" where you are presented with many more choices.
    * next is "patches". here i would highly suggest turning off SFC (windows file protection) as this is an incredible annoyance for many people and will greatly increase the time required for your installation.  furthermore, malicious folks and vendors that write drivers know how to get around this nonsense anyway.
    * next is "tweaks" and then you'll finish up by building your installation. i typically cut the size of a default windows xp install by about 50%, but i'm a bit agressive with what i remove.  also some of that space is used by 3rd party software to replace the components removed.
    * if you are comfortable with virtual machine software, that'd be the way to test your shiny new installation ISO. if not, then get ready to take the plunge
    when installed an nLite OS on my thinkpad for the first time (a day or 2 after i got it), i did a test install first - i kept the recovery partition in tact. once i got comfortable with installing the drivers and got everything working, i un-hid and formatted the recovery partition -- gone! you may want to do the same, though speaking from expierence i can tell you that it's rather trivial to get everything working on my T60 (though i do not have nor did i want a fingerprint reader, i would doubt it would be an issue to get working).
    * once windows is up and running, there will be allot of broken stuff  
    some of the "Fn" keys will not work, some will (because the hardware is configured in BIOS). you'll need to install the drivers for the items that you want to work, and this is another area where i depart from the norm. here's some things i don't install and the reasons why (whenever possible, any hardware below is disabled in BIOS or device manager):
    * easy eject utility - not needed/i don't use it anyway
    * hotkey driver - bloated and sometimes buggy software that may corrupt OGL and DX full-screen display (games) and cause stop errors (BSOD)
    * trackpoint - i don't use it, though it works anyway with limited functionality if not disabled in BIOS/device manager
    * trusted platform module - yeah, well i don't trust it
    * away manager -  don't use it/lighter weight alternitives available
    * keyboard customizer - not needed/i don't use it
    * scroll lock indicator - not needed/i don't use it
    * software installer - bloated mess/not needed (subscribe to the Lenovo RSS feed to be made aware of updates)
    * thinkpad configuration package - i'll configure it myself, thanks
    * thinkvantage access connectkions - bloated mess/slows boot time/not needed (better and lighter weight alternitives * available if you need this functionality)
    * ultra-nav wizard - not needed
    * bluetooth - i install the microsoft bluetooth stack (which is smaller and simpler) and have noticably less lag with bluetooth devices resuming from a standby state (mouse in particular)
    * display drivers - i use the highly acclaimed and optimized Omega drivers.
    for the drivers i do install, i install only the drivers, NOT the software (in other words i do not run the installer). i do this by extracting the installer using IZArc or Universal Extractor and using device manager to point the hardware to the extracted *.inf files.  for me, there is only one device that comes up "unknown device" before drivers are installed (i forget which).  the rest are named, so it's easy to tell what path to give them for the drivers. installing drivers for the unknown device is then simple a process of elimination, or you can use software to help identify the device.
    ::: the end :::
    hack it 'till it BREAKS!

    *bookmarked for desection*
    I already see flaws, like turning off remote registry for example. Remote registry only has very limited access, and you can change the access, but why would you? You can see what it has access to by going into Control Panel > Administative Tools > Local Security Policy > > Local Polices > Security Options, then scroll a little more than half-way, and it's under the Network access box.
    There are so many crack pot guides out there, that the only good advice is to look where they looked, and if you don't get it, and don't go though all of it, LEAVE IT ALONE! It only makes servicing the box at a later time a HUGE pain, and if it's in a business, it'll just be reimaged.
    Keep this guy's disclaimer in mind at all times. Just do the easy ones to start, like run CCleaner, it basically does everything for you, and doesn't cause any errors (or as far as I know, and I use it just about every other day)
    Currently Just passed the CompTIA A+ 601 with flying colours! =D
    Owner of an SL500 running Vista Business with 4GB of PC2 6400 RAM

  • Can anyone tell me about Connection Pools???

    Hi,
    Is there a freely downloadable Connection Pool implementation available on the net? I need it specifically for Oracle databases... This is for a prod environment and am looking for a stable implementation... Any good information/links is most appreciated.
    Thanks
    Prowzen

    Hi,
    I actually implemented it long time back. This is a best case to implement the Singleton Pattern. Just to give an idea, here is how it goes. I'll try to post the code too but cannot guarantee it right now.
    Basically the Pool information like the database, userid, password, SID etc. should be configurable through a properties file as you are saying that it is a production environment.
    1. Implement your Connection Pool as a Singleton class that has methods like init, getConnection, releaseConnection, createConnection etc. Have private member - a java.util.Vector of java.sql.Connection objects.
    2. Anyone who wants to use the connection pool gets an instance with the getInstance method which will call init method.
    3. The init should read the properties file and get the necessary details. Then create required number of connections and put them in the Vector of connections (pool). You are good to go now. Ideally this should all be done at the startup of the whole Application.
    4. Each client will call the getConnection method of the Singleton. The getConnection should Synchronize the Vector and remove the connection at index 0 of the pool (vector) and return it.
    i.e. public java.sql.Connection getConnection ()
    //wait until someone notifies me after returning a connection back to the pool
    if(connectionPool_.size() == 0)
    wait();
    Connection con = null;
    synchronized(connectionPool_)
    con = (Connection)connectionPool_.elementAt(0);
    connectionPool_.removeElementAt(0);
    return con;
    5. Each client SHOULD call the releaseConnection method of the Singleton once it is done using the connection. The releaseConnection should Synchronize the Vector and add the connection back to the pool.
    So, basically the connections in the pool will be used in a Round-Robin Fashion.
    i.e. public void releaseConnection (java.util.Connection con)
    connectionPool_.addElement(con);
    //Notify all the waiting Clients. Let JVM decide who gets the connection.
    notifyAll();
    return con;
    This is the core logic of what I had written. But there are lot of other cases that you need to consider to write robust code like Lost Connections, when you need to throw that connection away from the pool and add a new one. This is more so significant in busy databases configured to timeout inactive connections. I used to have a low priority thread kicked off at the start along with this main pool that would wake up around 4 or 5 in the night and replenish all the connections in the pool so that it will be good to go for one more day before it gets replenished again. Of course, in such a case, the clients have to have a retry mechanism in case you don't respond in reasonable amount of time while replenishing the connection pool.
    Hope this helps.
    Amar.

  • Data structure - tokenization

    Hi,
    I want to do the tokenization of several documents, saving the tokens (as strings) into a data structure. Obviously, I don't know the number of the tokens (it depends of the lenght of the documents). What is the data structure that you advice me?
    Thanx
    MP

    it seems you want the kinda of data structure that grows dynamically..however other factors can play a role too
    - want fast iteration --> use ArrayList
    - want synchronization --> use Vector
    - no duplicates --> use HashSet
    - want order --> use TreeSet
    - etc..many other i can't remember now..
    so it's really ur choice
    hope this helps

  • Do I need to synchronize vector to do this?

    I need to add some code to an existing legacy java class. In this class,
    it already has had a Vector call v.
    What I need to do is remove the last element from the vector and do
    something. I think I can add the following code to do this:
    <pre>
    v.remove(v.size()-1).
    </pre>
    However, in multi-thread environment, this could cause problems. Say, the vector
    has size 2. The first thread comes in and get v.size() =2, and then the second
    thread comes in and get vi.size()=2. Then both of them is try to remove the
    second element.
    I think I can add a synchronized(v) around the code, but this is really performamce-expensive. considering vector is already synchronized. Does anyone have a better idea about how to handle this?
    thanks,
    JT

    Can you refactor so that you always remove thefirst
    element? zero is always the first elementregardless
    of what the other thread is doing.
    Not true, if a thread thinks that a Vector's size is
    greater then zero (thus it can remove an element), and
    then is interrupted, another thread comes in, removes
    the last element, element zero, then the first thread
    is resumed, then the first thread will fail with an
    exception.
    You are, of course, correct.
    I had assumed that was the only thread removing things and there is another thread adding

  • Need help in Understanding synchronization through code

    I read someone that synchronization is suppose to allow only one thread to access a synchronized method or block of code. But then I wrote some code just to test it out.
    import java.util.ArrayList;
    import java.util.Vector;
    public class Testing extends Thread {
         private String someString;
         static Vector<Integer> someVec;
         static ArrayList<Integer> someArrayList;
         public Testing(String value) {
              someString = value;
              someVec = new Vector<Integer>();
              someArrayList = new ArrayList<Integer>();
         public static void main(String args[]) {
              Testing one = new Testing("one");
              Testing two = new Testing("two");
              one.start();
              two.start();
         public void run() {
              if (someString.equals("one")) {
                   for (int i = 0; i < 1000; i++) {
                        try {
                             someVec.add(i);
                        } catch (RuntimeException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        System.out.println("adding with " + i);
              } else
                   for (int i = 0; i < someVec.size(); i++)
                        try {
                             System.out.println("getting .. " + someVec.get(i)+ " from "+someVec.size());
                        } catch (RuntimeException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
    }Now my questions
    1. Why the 2nd thread is able to access the someVec ( Vector) when the 1st thread is still adding some values?
    2. When I changed someVec to someArrayList the result is still the same. I wonder why ?
    3. Lastly, Can anyone modify my code so only either a Vector or a Arraylist will make the program run without error ? Because right now I can run them both fine, so I don't see the difference.
    Thank you.
    Regards,
    Mustafa

    Vrijmetse wrote:
    1. Why the 2nd thread is able to access the someVec ( Vector) when the 1st thread is still adding some values?You have not added any synchronization around your Vector operations. Vector's individual methods are synchronized, but that only extends to the execution of those methods. There's no way for that syncing to know that you're doing stuff in a for loop. If you want to complete the for loop without anything else affecting that Vector, then you need a sync block around the body of the loop, and anything else that acceses the Vector must also sync on the same object. The Vector itself is a good candidate for the lock here.
    (There may be other problems as well. I haven't read your code closely. Just noticed the for loop and lack of syncing.)
    2. When I changed someVec to someArrayList the result is still the same. I wonder why ?Same reason.
    3. Lastly, Can anyone modify my code so only either a Vector or a Arraylist will make the program run without error ?No.

  • Can i know what type of object is stored in Vector?

    i have written a program for vector where i am adding elements like
    sunday, monday , 3.14, 9,5.56 and i want to sum all elements of type double only double data type numbers. it should not add int number or string ?
    import java.util.*;
    class VectorBasic
         public static void main(String args[ ])
              Vector v1=new Vector(1);
              Double d1=new Double(3.14);
              v1.addElement(d1);
              v1.addElement("sunday");
              v1.addElement(new Integer(2));
              v1.addElement(new Double(5.56));     
              v1.addElement(new Integer(5));
              for (int i=0;i<v1.size();i++ )
              System.out.println(v1.elementAt(i));
    }

    Questions:
    1: Why are you using Vector? You should be using ArrayList in most new code. If you need synchronization (Vector is synchronized), use Collections.synchronizedList(). You don't need synchronization for the code you showed.
    2: Why initialize the size of Vector (or ArrayList) as 1? That just makes you have to reallocate the size of the list (done for you by the Vector class) as soon as you add a second element. Why not just use a new Vector() [or, better, a new ArrayList()] with the default size?
    3: Why are you mixing type in your Vector in the first place? Is this just a test class to learn how to tell the type of an object?
    Comment:
    1. You should use Double.valueOf(3.14) and Integer.valueOf(2), instead of calling "new Double(3.14)" and "new Double(2)".
    In the future, when posting code, use the code tags to keep it formatted nicely. There's a button for it above the posting box. Select your code, then press that "code" button. It will put code tags around your code. You can also type the tags manually--put one at the beginning of your code, and one at the end:

  • Use ArrayList vs Vector

    I'm writing an application that accept multiple connections.
    To check the connections I have a thread that check these connections if they are in use, i iterate over these connections and if they are not used for a periode of time, i close this connection and remove them from my list and iterate further.
    If i use a Vector to collect the connections, everything goes fine, but if i use a Arraylist, i get a concurrentmodificationexception, i now, this is normal, because the failfast of the iterator, so, i used the synchronize method of collections, but i got the same exception,
    any suggestions to make ik work with an ArrayList.

    If i can make it work with a list i'me happy, i will try it with a linked list, thx
    Heres the code of the methode
    public void run() {
    while (true) {
    try {
         Enumeration enum = null;
         sleep(frequency);
         long currTime = System.currentTimeMillis();
         enum = TimeoutInputStream.instanceList.elements();
         while (enum.hasMoreElements()) {
    TimeoutInputStream stream =
         (TimeoutInputStream) (enum.nextElement());
    //ITERATOR FAILS HERE
         long lastActive = stream.getLastActive();                    System.out.println(".");
         if (lastActive == 0) {
              stream.setLastActive(currTime);
         } else if ((currTime - lastActive) > timeout) {
              stream.abort();
    //HERE DO I REMOVE THE CONNECTION OUT OF THE LIST
              System.out.println("Timeout: input stream aborted");
         } catch (InterruptedException e) {
              System.out.println(e);

  • List v = new Vector() how can i write this ?

    List v = new Vector() how can i write this ?
    vector does not 'extends' List rather it 'implements' only ......so how can write this way ? ( polymorphism applies only for 'extends' ).

    my question in a simple way is :
    List some_list extends Vector
    No, List is an interface; Vector is a concrete class. Read the javadocs.
    Vector implements List
    >
    AND
    List some_list implements Vector
    are these two same in behaviour
    our  apart from theoretical differences ?thanks
    Interfaces don't have any implementation; they're pure method signatures. When a concrete class implements an interface, it makes a promise that says "I will provide implementations for exactly these methods. Any client can call a method from the interface and I will do something 'sensible' if I'm written correctly."
    From the point of view of static and dynamic types, there's no difference between interfaces and classes.
    C++ has interfaces, too - they're classes with all pure virtual methods. If you understand how C++ works, the concept shouldn't be hard.
    ArrayList is preferred precisely because it isn't synchronized by default. (You can always make it so using java.util.Collections if you wish later on.) If you don't need synchronization, why pay the performance penalty?

  • Synchronize question in servlet

    Hello everybody!
    I have some question regarding synchronization in a servlet, and hope someone can help me.... (see example code below)...
    1) The methods "getNames(), addNames(), removeNames()" need to be synchronized due to that the "names" vector can be accessed by many at the same time, right?
    2) Do I need to synchronize the method "addANumber()"? why/why not?
    3) Do I need to synchronize the methods "setString(), getString()" placed in the "Test" class? why/why not?
    4) All "global" variables, i.e. the variables declared as object or class variable, need to be synchronized. Is this valid for servlet methods as well? For example the addANumber() method, or whatever method (that doesnt use global variables) I place in the Servlet class (ASR-class)
    Please all your experts out there, help me.....
    Thanx in advanced
    TheMan
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    public class ASR extends HttpServlet {
        private Vector names;
        private ServletConfig config;
        public void init(ServletConfig config) throws ServletException {
              synchronized(this) {
                this.config=config;
                names = new Vector(100,10);
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            //add a name to the vector
            String theName = request.getParameter("inpName");
            addNames(theName);
            //get the vector and print that name
            Vector tmp = getNames();
            int pos = Integer.parseInt(request.getParameter("number"));
            out.println("a person " + tmp.get(pos));
            addANumber(pos);
            //remove a name
            removeNames(pos);
            //create a test object
            Test t = new Test();
            //set a string in the test object
            t.setString("yyy");
            //print that string
            out.println("test string: " + t.getString());
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            doGet(request, response);
        //needs to be synchronized?
        public int addANumber(int number){
            int adding = number + 10;
            return adding;
        public synchronized Vector getNames(){
            return names;     
        public synchronized void addNames(String theName){
            names.add(theName);
         public synchronized void removeNames(int pos){
             names.remove(pos);
    class Test {
        public String str = "xxx";
        //needs to be synchronized????
        public void setString(String str){
            this.str = str;
         //needs to be synchronized????
        public String getString(){
            return str;
    }

    The teachers, which are responsible for the
    servlet-courses that I have taken, never spoke about
    the member variables, in the same way you did. They
    used member variables and synchronized methods or
    synchtronized code blocks to access them. They never
    said that "one should not/try not to use member
    variables". I can understand this in the context of using Servlets to gain understanding on some of the issues involved with multithreading. In a classroom, servlets may pose an easier laboratory (so to speak) for learning threading concepts than something like nachOS or something like that.
    For example, they made a ordinary "page counter",
    i.e. a counter which increases by one for each "hit"
    on the page. I that example they, and I, thought it
    would be a good idea to use a member variable (a int
    counter), since all instances of the servlet will use
    the same variable. How should one construct such page
    otherwise? Local variables and databases is one way.As mentioned in an earlier post, in the real world I can think of very few reasons as to why a particular servlet may need to keep state. In terms of keeping a counter, what you would probably do is to analyze the access logs...Yes -- not a programmatic solution, but a very doable, low maintenance, and quick one. One important lesson to learn is that not all problems are best solved in code. This is probably not the right answer for a test though...
    I just got a bit confused, my teachers had no problem
    with member variables, but you guys recomend me to
    use local variables instead. Which leader should I
    follow :) ?Capitalist answer: whoever pays you :) Seriously, why not talk to your teachers about what you have learned here versus what they are teaching?
    - N

  • Synchronization on a static object

    If I have a code like:
    synchronized(_otherParsers)
    _otherParsers = new Vector();
    } knowing the _otherParsers is a static object in the class, the synchronization will block all access to the object or it will block the access to the sync. block?
    OBS: So when one thread enters the synchronized block, accesses to that object by other threads are blocked until the original thread exits the synchronized block. [PENDING: verify previous statement, and figure out if synch'ed blocks block out all method calls on the object or just synch'ed ones] (quote from Java Tutorial, http://java.sun.com/docs/books/tutorial/together/bingo/synchronized.html)

    IIRC, when using synchronize(someObject) then
    someObject is locked, meaning that the original object
    isn't locked. So other methods will execute correctly.let's say the following:import java.util.Vector;
    public class A {
      public static Vector v = null;
      public A() {
        v = new Vector();
      public static void main(String[] args)
         B b = new B();
         new Thread(b).start();
         new A();
    class B implements Runnable {
      public void run() {
        synchronized(A.v) {
            A.v = new Vector();
            A.v.add("test");
    }As you can clearly see, the static vector, member of A class is initialized twice (once by the new A() in the main method of A class and once by A.v = new Vector() in the run() method of B class). Assuming the thread enters the synchronized block before the call to new A() in the main method, when that call ocures, is the A.v object locked? or not?

  • How do I synchronize a code-section? semaphores?

    I know how to use the synchronized methods, but how do I synchronize code-sections inside mehods?
    For instance, if I have a vector in a class that must never be tampered with by two threads at the same time but i don't feel like making synchronized wrapper-methods around the methods in the Vector class. This is easily done with semaphores, but there are no semaphores in java (why the heck not, by the way?).
    Someone told me it's possible to use a statement involving synchronize, is this the case?
    Any ideas are very much appreciated!
    /Mattias

    A couple of things to note:
    1) Vector's methods are already synchronized, so if you just don't want one method call on the Vector interfering with another, it's already taken care of for you.
    2) If you need to sync across larger operations--for example {add, add, sort, delete}, with the ops listed in braces being "atomic" then you could do like ShagVT suggested, with my "{}" ops being his "// do critical".
    However, you need to be careful here. Every piece of code that could potentially interfere with this--every piece that has to respect that atomicity--must also sync on the same Vector.
    private void veryRudeOp() {
      Vector v = getSameCriticalVectorAsOtherCode();
      // do rude stuff to v without synchronizing
    }Here, another thread can come in, and since it's not syncing on the critical vector, it can run willy nilly all over the middle of what's supposed to be an atomic op. The key point is that "synchronized" doesn't "prevent any other thread from accessing the object" (as some people mistakenly believe); rather, it prevents any other thread from obtaining the same object's lock (until the sync block exits or calls wait() )

  • Is it legal to use Vector in EJB?

    Chapter 24 of the EJB spec states:
    "An enterprise Bean must not use thread synchronization primitives to synchronize execution of multiple instances."
    As far as I know Vector ist thread save.
    Does this mean you must not use Vector in EJB? Or is it allowed to use Vector as only one bean instance accesses one Vector instance?

    I'd sure like to hear a clear answer to this question. I've been tasked with adding an EJB interface to an existing server application. Right now, we have 2 main methods of sending requests to the server, RMI and IP. We have clients that are requesting an EJB interface. What I'd like to do is create a Session bean( haven't decided on Stateless or Stateful yet ) that invokes the same underlying objects that the RMI and IP objects use. However, those classes were not written with EJB's in mind. They start threads. They access files. They have static data which is manipulated. All those things are forbidden( or at least, strongly discouraged ) in the EJB spec, as I understand it.
    Of course, I could create a Session bean that used the existing RMI or IP interface to talk to an instance of our application running in a different JVM, which would eliminate the problem. But that seems like a bit of a hack to me.
    Marc Robertson
    Staff Consultant
    DST Systems, Inc.

Maybe you are looking for