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

Similar Messages

  • Do I need to synchronize a singleton just for reads?

    Hello forum. Here's my situation: I keep config data for pages on my website in an XML file, I load said XML file in a startup servlet, creating a JDOM Document object, accessed by a singleton.
    Every time a page is loaded, the page accesses this Document object via the singleton, sees whether the page is secure, which template it should use, a bunch of stuff.
    Now, because the Document object is created when the context is started, and is never written too, only read, do I need to synchronize it?
    I read "Threading lightly, Part 1: Synchronization is not the enemy," on ibm.com (http://www-128.ibm.com/developerworks/java/library/j-threads1.html) in hopes of answering my own question, and the most relevant paragraph states:
    "If you are writing data that may be read later by another thread, or reading data that may have been written by another thread, then that data is shared, and you must synchronize when accessing it."
    But does my scenario fit? Yes I'm writing data that will be read by another thread, but no thead is accessing this data until the context is fully loaded and the object is fully instantiated. The object is not being written to by threads asynchronously... I just run the risk of it being read at the same time. Do I need to synchronize? If so... having synchronized variables in a servlet environment is bad, so what other approach should I take?
    Thanks for your help.

    But does my scenario fit? Yes I'm writing data that
    will be read by another thread, but no thead is
    accessing this data until the context is fully loaded
    and the object is fully instantiated. The object is
    not being written to by threads asynchronously.If all the writing is complete before any of the reading starts, then there's no need to synchronize the reading.
    .. I
    just run the risk of it being read at the same time.There's no risk in multiple concurrent reads.
    Do I need to synchronize? If so... having
    g synchronized variables in a servlet environment is
    bad, so what other approach should I take?Couple minor points:
    * You don't have synchronized variables. You have synchronized blocks and methods.
    * Using synchronization in a servlet context isn't in and of itself necessarily bad. Having multiple requests sync on the same lock can hurt response time, so try to avoid it, and if you must do it, keep the critical sections as small as possible.

  • Do I need to Synchronize session connection??

    I am working on a project in which requires sending out emails.
    Multiple users may send out emails at the same time by using same email account and session. Question is do I need to synchronize this or just let mail server handle this concurrency. Or session's getDefaultsession method have already considered this? Looking forward to your answer!! Best regards,

    Multiple users may send out emails at the same time by using
    same email account and session.Don't do that. Each thread should have its own session. Otherwise you'll have chaos. Sure, you could synchronize so the threads take turns using a single session, but if you do that there isn't much point in having separate threads, since 99% of the time they will be lining up to use the session.
    However if those "users" are running in separate JVMs, perhaps even on separate computers, then the question doesn't arise. They would automatically have their own sessions.

  • Need for Synchronization in Servlet

    Hi,
    If I have a method lets say saveCustInfo() and I call it from doget(). Roughly something like this:-
    Customer extends HttpServlet {
    doGet(req, res)
    parameters = ......
    saveCustInfo(parameters);
    saveCustInfo(....)
    //code for saving customer information
    Now question is, whether there is a need to synchronize on method saveCustInfo() or not???

    Thanks for the responses. Some things are clear to me but some things are still not. One of the responses said that I need to synchronize only if I am using a object or variable which is shared. But another response said that I need to synchronize if I am manipulating data inside the method.
    My method does not have shared variables or objects but definitely some data manipulation is there inside the method.
    Question is Do I need to synchronize if the some data manipulation is there locally inside the method? My understanding was that every call gets its own copy of the method on the stack so all the variables are local but still distinct.
    Please someone share their knowledge on this.
    Thanks

  • I need to synchronize my computer

    I need to synchronize Pc to my I phone 4s to get pictures and video from pc to i phone. How do i do that?

    Camera roll photos and videos don't sync at all.  The must be imported to your computer as you would any digitial camera.  Follow this guide: http://support.apple.com/kb/HT4083.

  • Do I need to declare a transaction in this case?

    I am struggling to understand when it is necessary to declare my own transaction to ensure the data is properly updated.
    For example, in the following code, which is part of a java bean in the EJB project, KeyFacade is a stateless session bean tied to the entity "Key". it is a standard EJB created with the netBeans 5.5 wizard. I have changed no defaults.
    Do I need to declare a transaction, commit the transaction and close it when I use the "KeyFacade.edit(key);" in order to ensure the database is updated? Or is it automatically done because the .edit() method uses the entityManager and the persistence is container managed?
    Would it make a difference if this bean was part of a WAR project?
        public BigInteger getNextKey(String tableName){
            KeyFacadeLocal KeyFacade = this.lookupKeyFacade();
            Key key = KeyFacade.findByTablename(tableName);
            long nextKey = key.getKeyvalue();
            BigInteger BINextKey =BigInteger.valueOf((int)nextKey);
            //  now update the table by incrementing the key value by 1
            long incrementKey = nextKey + 1;
            key.setKeyvalue(incrementKey);
            KeyFacade.edit(key);
            return BINextKey;
        }

    808239 wrote:
    I have a Map<Integer, List<T>> data, and all the lists are initialized using Collections.synchronizedList().Seems like overkill to me. Your Map also looks like a Multimap, of which there are several existing implementations.
    When I do the traversal, I want to traverse ALL lists in the map at the same timeI suspect not. What you want to do is to traverse each one in sequence.
    so I have to sync all lists as shown in the API doc as follows: ...Seems like overkill to me, and will probably result in a very slow Map (not that there's any problem with that if it's the right thing to do; in this case, I suspect it isn't).
    Is this approach ok?What are you trying to achieve? If you need full consistency for your iterators (ie, a snapshot of the entire Map at the time the iterator is created), you have a two choices (assuming you don't want to deal with update journals):
    1. Lock the Map.
    2. Clone the Map (and your clone() method should be synchronized).
    Of the two, the second seems best to me, but neither is all that wonderful.
    However, if all you need is weak consistency - that is to say, what you return reflects the state of the Map when Iterator.next() is called - all you really need to do is make sure that your Lists are synchronized when you do the read.
    Since the List updates are the responsibility of your Map (I'm still presuming this is some sort of Multimap implementation), there's no real need to synchronize them; just synchronize the Map's own update methods.
    I'd also suggest that you make sure your getValue() method hands back an [url http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#unmodifiableList%28java.util.List%29]unmodifiable List to clients; otherwise they could start adding or removing values themselves.
    HIH
    Winston

  • Help Needed - My BB 8520 Curve has this message-CRTranRec::GetLinkedRecordID:Invalid linked record id while sychronisation using the desktop software

    Hi!
    Need some help with the same:
    Help Needed - My BB 8520 Curve has this message-CRTranRec::GetLinkedRecordID:Invalid linked record id while sychronisation using the desktop software

    Hi sameer197301 and welcome to the BlackBerry Support Community Forums!
    To clarify, are you seeing this message displayed on your BlackBerry® smartphone or on your computer?
    Thanks.
    -CptS
    Come follow your BlackBerry Technical Team on twitter! @BlackBerryHelp
    Be sure to click Kudos! for those who have helped you.Click Solution? for posts that have solved your issue(s)!

  • Attachments: I am creating an online application for employment and need applicant o submitt credentials, Is thier a way they can attach docs to the application?

    Attachments: I am creating an online application for employment and need applicant o submitt credentials, Is thier a way they can attach docs to the application?

    Hi Syclopz88,
    You can use 'File Attachment' option in the form which will allow the user to attach documents to the application.

  • 1 year ago i installed Elements 12 on my PC with a serial number.  Today i have installed Elements 12 also on my laptop. But,...there is a problem with validation of the serial number on my laptop. Is there a need to validate Elements  or will this progra

    One year ago i installed Elements 12 on my PC with a serial number and it was OK.
    Today i have installed Elements 12 also on my laptop.
    But,...there is a problem with validation of the serial number on my laptop. Is there a need to validate Elements  or will this program real disapeare in 7 days?
    Hans

    Hi,
    Since you already have one copy activated the serial number must be logged in your account details - I would first check that the one logged and the one you are attempting to enter are the same.
    You can check your account details by going to www.adobe.com and clicking on Manage Account. You need to sign in with your Adobe Id and then click on View All under Plans & Products. Next click on View your products and after a while it should produce your list.
    If there is a problem with the serial number, only Adobe can help you there (we are just users). Please see the response in this thread
    First of all, I would have to say that getting in touch with you is a nightmare and I am not at all happy that I can't just email or live chat with someone who can help!  I am not a technical person, I just want to be able to use Photoshop Elements and ge
    Brian

  • I'm about to buy a 27" i-Mac. I would like to connect my 30" Cinema Display to it as a second monitor. What will I need to do that? Will this slow down the overal performance?

    I'm about to buy a 27" i-Mac. I would like to connect my 30" Cinema Display to it as a second monitor. What will I need to do that? Will this slow down the overall performance?

    The new iMacs do not come with a MiniDisplayPort, they have Thunderbolt, so unless you are talking about purchasing one of the previous generation iMacs such as this refurbished model in the online Apple store, it won't work. And yes, if you are going to get the full range of video resolutions you will need the Dual-Link version.
    For details see the store's web page on the Dual-Link display adapter.

  • I'm trying to open files which are telling me to instal Adobe Reader.  Which I did but the agreement which needs to be ticked off so this reader can open doesn't come up.  Please could you be of some assistance.

    I'm trying to open files which are telling me to instal Adobe Reader.  Which I did but the agreement which needs to be ticked off so this reader can open doesn't come up.  Please could you be of some assistance.

    Select one of the files, Choose GetInfo from the Finder's File menu, look for the field named "Open With", and choose Preview from the adjacent menu. Accept that ALL such files will Open with Preview, and your major problems should be solved.
    Occasionally, a particularly complex .pdf file or one that needs to be modified and re-written will not work quite right with Preview, but such issues are rare.

  • After upgrading to Lion, I went to open Mail and received the message that it needed to upgrade my Mail database - this may take a few minutes. The bar shows it is about 1/5 along and has been there for over 10 hours. Help!

    After upgrading to Lion, I went to open Mail and received the message that it needed to upgrade my Mail database - this may take a few minutes. The bar shows it is about 1/5 along and has been there for over 10 hours.
    I tried quitting and starting again but it just jumps back to the same spot.

    It is quite large, but I have tried two of the fixes suggested and things now seem to be moving along.
    (I was unable to seach properly before which is why I posted the question - it was a bit of a panic)

  • Do I need to create a view for this?

    Hi Ihave got 2 tables emp and project
    In emp tabe:
    emp_no
    family name
    given name
    In porgect table:
    emp_no
    status(assigned,unassigned)
    start_date
    end_date
    emp_no Family_name given_name
    1 Smith John
    In project table same employee can have many assigement eg
    emp_no status start_date end_date
    1 assigned 01-may-08 01-july-08
    1 assigned 01-sep-08 01-july-09
    1 unassigned 01-july-09 01-oct-09
    In the form:
    there are 2 querable fields "project ends between field1(date) and field2(date)" which is used to
    retrive records which have end date between field1 and field2.
    The following fields are needed to get from database:
    emp.family_name emp.given_name project.start_date project.end_date No.of time assigned
    Requirements:
    1. project.start_date and project.end_date must be the latest project_end_date for the same emp
    so in the above sample date
    2. No. of time assigned is a count of total of number records which have status='assign'
    So for the given sample data the record expected after query would be(field1=01-jun-08 field2=02-july-09)
    emp.family_name emp.given_name project.start_date project.end_date No.of time assigned
    Smith John 01-sep-08 01-july-09 2
    What is the best approach to get:
    1 The lastest project(latest end_date) for the emp
    2. get No.of time assigned.
    Do I need to create a view for this? If yes, any sample sql code this this?
    Thanks for your help

    Hi W1zard,
    Thanks for your reply. Could you clarify the following points for me:
    1.) you could create a master block basing on your emp table and a detail block basing on your project table with the relation over emp_no. set the default_where clause of your detail block programmatically using
    set_block_property('project', default_where, 'status = ''assigned'' and <your_date_criteria>');
    Q1: where I pit this code? in pre-query trigger in detail block?
    2.) Of course you could create a view to join both of your tables if you don't want to use master detail blocks; Also do the join over emp_no
    create or replace force view v_emp as
    select emp.family_name, emp.given_name, project.start_date, project.end_date
    from emp, project
    where emp.emp_no = project.emp_no
    Q2 As I mentioned before, there are multipal entries for the same emp in project table and we only need the maching record from project table which has latest end_date. So I think I need something like
    max(project.end_date) somewhere in create view to make sure only one record for one employee.
    Also is there possible to include the no. of assigned field(select count(*) from project where status='assigned' and emp=emp_no) into the view as well?
    Q3 All the fields mentioned above are diaplay-only. So Can I create a control block which has all the fields from emp and project. Then populate them with my sql. The question is
    where I put this customerised sql so when user click excute query. My sql will run and display one the form?
    REally appreciated your help!
    Michael

  • Getting error while creating form and report on webservice: ORA-20001: Unable to create form on table. ORA-02263: need to specify the datatype for this column.

    i am using the following description to create a web service reference:
    web reference :REST
    Name :Yahoo Map
    URL :http://local.yahooapis.com/MapsService/V1/mapImage
    HTTP Method: GET
    Basic Authentication: No
    Add Parameter:
    Name       Type
    appid        String
    location    String
    Output Format: XML
    XPath to Output Parameters : /Result
    Output Parameter:
    Name       Path       Type
    Url          /text()      String
    Then i tried to create form and report on webservice:
    Web Service Reference Type: Yahoo Map
    Operation: doREST
    All the fields i keep as default
    I tick the checkbox (url)in report Parameter
    After clicking next whereever required i click create button
    I get the following error
    ORA-20001: Unable to create form on table. ORA-02263: need to specify the datatype for this column.
    Please someone help to solve this as i need to fix it urgently.

    i exported the application from apex.oracle.com and imported it to our environment
    import went fine, but when I ran the IR page I got
    ORA-20001: get_dbms_sql_cursor error ORA-00904: : invalid identifier
    evidently the problem is a lack of public execute on DBMS_LOB, which is used in the generated IR source.
    while waiting for the DBA to grant privs on DBMS_LOB, changing the dbms_lob.getlength call to length() fixes the IR.
    however, i am not getting the download link on the associated form page... changed templates, that's not the issue -- we'll see if that's a dbms_lob issue as well

  • APEX:Getting error while creating form and report on webservice: ORA-20001: Unable to create form on table. ORA-02263: need to specify the datatype for this column.

    I am using Apex 4.2.2.00.11
    am using the following description to create a web service reference:
    web reference :REST
    Name :Yahoo Map
    URL :http://local.yahooapis.com/MapsService/V1/mapImage
    HTTP Method: GET
    Basic Authentication: No
    Add Parameter:
    Name       Type
    appid        String
    location    String
    Output Format: XML
    XPath to Output Parameters : /Result
    Output Parameter:
    Name       Path       Type
    Url          /text()      String
    Then i tried to create form and report on webservice:
    Web Service Reference Type: Yahoo Map
    Operation: doREST
    All the fields i keep as default
    I tick the checkbox (url)in report Parameter
    After clicking next whereever required i click create button
    I get the following error
    ORA-20001: Unable to create form on table. ORA-02263: need to specify the datatype for this column.
    Please someone help to solve this as i need to fix it urgently.

    336554,
    Looks like there is a 127-column limit on the number of report columns supported when using that wizard. Do you have more than that?
    57434

Maybe you are looking for

  • Muliple iPods on 1 computer

    I recently bought a 2nd iPod for my girlfriend, and she wanted access to my music library. Our computer is on Windows XP, and we each have our own log in accounts. As per instructions, I created a new Apple account for her under her log in. Then I lo

  • How Can i use the key file Generated by RSACryptoServiceProvider to encrypt with php?

    I need to be able to encrypt data in PHP using a public key generate by .NET(RSACryptoServiceProvider).  I will then decrypt the data later in C# using the private key. Code Snippet <RSAKeyValue><Modulus>xU5JyaPNDKXI/h/uo5Vk89wZSz3zsB1+c+1IMYIQa+mCmu

  • Error when running Periodical Services in E-Recruiting

    Hello, Could someone help me better understand this error? In SLG1 while periodical services is running I recieve the following error over and over again with different NA object ID's. "Error while saving a search profile in document storage" Diagnos

  • Multi DUT test with shared instrument​s

    Hello, I have a 6 DUT Testand application, using parallel model. All the measurement equipment in shared by each test instance. I'm using VISA functions, to initialize and perform measurements. For a single DUT application with sequential model, I wo

  • Where is the theme sound?

    When I create a new movie (iMovie 10.0.2) and select a theme, there is no sound in the timeline.  Where is the sound track from the theme?