URLConnection.getInputStream and synchronization.

I can't quite understand why url.getInputStream must by globaly synchronized, if it isn't I will start to receive "connection refused" exceptions
import java.net.*;
import java.io.*;
public class TestURL {
    private final Object lock = new Object();
    public void test() {
        for(int i=0;i<1000;i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        while(true) {
                           URLConnection url = null;
                           url = new URL("http://localhost:5222").openConnection();
                           InputStream s;
                           synchronized(TestURL.this.lock) {
                               s = url.getInputStream();
                           while(s.read() != -1) {};                            
                           s.close();
                           System.out.println(Thread.currentThread().hashCode());
                    }catch(Exception e) {
                        e.printStackTrace();
            }).start();
            System.out.println(i);
        while(true);
}

moonlighting wrote:
Hmmm, I don't quite understand your answer could you be more specific ?Without the synchronization you create and start 1000 threads with each one accessing the same URL. Can the server cope with 1000 requests at pretty much the same time?
With the synchronization, each thread has to acquire a lock on the object referenced by 'TestURL.this.lock' so only one can run at a time. All the other 999 will be suspended until they can acquire the lock.

Similar Messages

  • Bad Record MAC. exception while using urlConnection.getInputStream()

    All,
    In my SAP J2EE instance, from filter I am trying to do get data from an url (protocol is https).
    For this I am using urlInstance.openConnection() after that urlConnection.getInputStream() and then reading from this input stream.
    When I use http protocol, everything works fine. But with https, during urlConnection.getInputStream(), I get an exception saying "Bad Record MAC".
    I tried to execute the same code in a standalone java program. It went fine with both http and https.
    I get this error only when I run in SAP J2EE instance and only with https.
    From the exception trace, I can see that while running in J2ee engine, the URLConnection instance is org.w3c.www.protocol.http.HttpURLConnection.
    When I run a standalone program from command prompt, the instance is com.ibm.net.ssl.www.protocol.https.r. This runs without any issues.
    I understand that these instances are different due to different URLStreamHandlerFactory instances.
    But I didnt set the factory instance in either of the programs.
    1. Is the exception I get is simply bcoz of instance org.w3c.www.protocol.http.HttpURLConnection?
    2. In that case how can I change the factory instance in j2ee engine?
    Please help.
    Thanks.
    Edited by: Who-Am-I on Nov 28, 2009 7:54 AM

    May be my question is too complex to understand. Let me put it simple.
    After upgrading to NW 7.01 SP5, an existing communication between SAP J2EE engine and a 3rd party software is not working.
    After a lot of debuggin I came to know that its happening at the filter we implemented to route the requests through the 3rd party authentication system.
    At the filter exception is coming from org.w3c.www.protocol.http.HttpURLConnection.getInputStream.
    This instance of HTTPURLConnection given by protocol handler factory(implementation of URLStreamHandlerFactory) which SAP is considering by default. I want to replace this protocol handler with another handler as I see no problems running the same program outside SAP J2EE instance.
    Can we change this protocol handler factory? Where can we change it?

  • InputStream in = urlconnection.getInputStream();

    Dear All,
    I am trying to zip a file in the client side and sending it to the server side machine......there, i am trying to unzip it and writting it over there...for this, i am using a seperate program in the client side and in the server side.................................
    In the client program, after opening all the necessary streams and all formalities, i am using the code...
    "InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1);"
    only if i use the above code, the zipped file is transfered to my server machine...but in this case, the link with the server is not getting disconnected...i mean the command prompt remains alive, without stopping...what i inferred is, my control is got into the above said "InputStream in = urlconnection.getInputStream();"...indefinitely...
    so i tried of removing the above said statement.....in this case, the zipped file is NOT getting written in my server machine....
    what to do???
    any suggestions please...waiting for the reply very anxiously, refreshing this site for every 2 minutes....
    sakthivel s.
    snippet code for ur reference...
    Client side
    try
    ZipOutputStream zipoutputstream = new ZipOutputStream(urlconnection.getOutputStream());
    ZipEntry zipentry = new ZipEntry(filename);
    zipentry.setMethod(ZipEntry.DEFLATED);
    zipoutputstream.putNextEntry(zipentry);
    byte bytearray[] = new byte[1024];
    File file = new File(filenamedir);
    FileInputStream fileinputstream = new FileInputStream(file);
    BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
    int length = 0;
    while((length=bufferedinputstream.read(bytearray)) != -1)
    zipoutputstream.write(bytearray,0,length);
    fileinputstream.close();
    bufferedinputstream.close();
    zipoutputstream.flush();
    zipoutputstream.finish();
    zipoutputstream.closeEntry();
    zipoutputstream.close();
    InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1); // the said while loop....................
    System.runFinalization();
    urlconnection.getInputStream().close();
    urlconnection.disconnect();
    the way of connecting witht the server : (just a snippet of the code)
    URL serverURL = new URL("http://192.168.10.55:8001/servlet/uploadservlet");
    HttpURLConnection.setFollowRedirects(true);
    urlconnection= (HttpURLConnection)serverURL.openConnection();
    urlconnection.setDoOutput(true);
    urlconnection.setRequestMethod("POST");
    urlconnection.setDoOutput(true);
    urlconnection.setDoInput(true);
    urlconnection.setUseCaches(false);
    urlconnection.setAllowUserInteraction(true);
    urlconnection.setRequestProperty("Cookie",cookie);
    urlconnection.connect();
    Server Side:
    javax.servlet.ServletInputStream servletinputstream = httpservletrequest.getInputStream();
    ZipInputStream zipinputstream = new ZipInputStream(servletinputstream);
    ZipEntry zipentry = null;
    String directory="c:\\test"; // the unzipped file should be written to this directory...
    try
    File file = new File(directory);
    if(!file.exists())
    file.mkdirs();
    catch(Exception exp)
    {System.out.println("I am from Server: " + exp);}
    try
    zipentry = zipinputstream.getNextEntry();
    if(zipentry != null)
    int slash = zipentry.getName().lastIndexOf(File.separator) + 1;
    String filename = zipentry.getName().substring(slash);
    File file1 = new File(directory + File.separator + filename);
    FileOutputStream fostream = new FileOutputStream(file1);
    BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(fostream);
    byte abyte0[] = new byte[1024];
    for(int index = 0; (index = zipinputstream.read(abyte0)) > 0;)
    bufferedoutputstream.write(abyte0, 0, index);
    servletinputstream.close();
    bufferedoutputstream.flush();
    bufferedoutputstream.close();
    zipinputstream.closeEntry();
    zipinputstream.close();
    fostream.flush();
    fostream.close();
    catch(IOException ioexception)
    {System.out.println("IOException occured in the Server: " + ioexception);ioexception.printStackTrace();}
    P.S: I am not getting any error in the server side or cleint side...the only problem is, the command prompt(where i am running my cleint program) is getting standing indefinitely...i have to use control-c to come to the command prompt again...this is because of the while looop said in the client machine....if i remove it...the file is not gettting transfered...what to do????

    snoopybad77 wrote:
    I can't, I'm using java.net.URL and java.net.URLConnection....Actually you are using HttpURLConnection.
    java.net.URLConnection is an abstract class. The concrete implementation returned by openConnection for an HTTP based URL is HttpURLConnection. So you might want to try the previous suggestion and otherwise examining the methods of HttpURLConnection to see how they might be helpful to you.

  • Re: Cannot get new URLconnection.getInputStream() in JAVA

    new URLConnection.getInputStream() does not seem to work.
    Background: I am trying to POST the data to an ASP page and reading the response back but it does not seem to work...if I comment this line out it works but does not do what it is intended for.
    Basically I am trying to upload files to the server and am connecting to the URL and writing to its stream....but cannot read the response back..Please help as I have tried everything I could and have read the forums but no LUCK yet

    Yeah yeah that is what I meant ...please excuse me for that ... jst getting slightly pissed off with this problem....see the code below...
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    this is where the error is coming from and the server throws error no 500.
    I have tried posting to the same URL using a Form and it works without any issues....please help

  • Wireless Network Drive setup to consolidate and synchronize iLife libraries

    What is the simplest system to set-up and use a Hard Drive to be shared wirelessly between my iMac G4, Power Book and two Dell laptops running Windows XP?
    Can i set-up my iPhoto, iTunes and iMovie libraries so that they are on the shared and each of the Macs can access the same libraries and each of the Macs and Dells can access the same iTunes libraries on the shared drive?
    Final question. If it is possible to have the iTunes, iPhoto, IMovie libraries on the shared drive, is it possible to have replicas synchornized locally on the laptops?
    What I'm trying to achieve is to have one consolidated library for iTunes, iPhoto and iMovie so that regardless of which computer my family uses to download photos from the camera or music from the iTunes music store the photos and music will be available in the libraries when any of the other computers are used and if the laptops are used away from home a replica of the complete libraries will be on the local drive.
    Right now we have photos, music and movies spread over 4 machines. Consolidation and synchronization is what I am trying to achieve.
    Thanks!
    Message was edited by: AmbroseStafford

    If you find a tool for all of your machines to do this in the background wirelessly, let me know. I'm doing this manually from my Macbook, two Vista machines, and three XP machines. I just copy and paste all of the stuff I want to replicate, and keep everything backed up on the Airport USB drive, which is a 400GB drive. I had a lot of trouble until I changed the drive format to journaled HFS+. Now it all seems to work great. Perhaps rsync could do something like this for you--I believe it runs natively on the Mac, and via Cygwin on PCs.

  • Data replication and synchronization in Oracle 10g XE.

    We are trying to do data replication and synchronization sort of thing for all our servers. We are using Oracle 10g. XE. I guess there are some features in oracle already for replication but I am not very sure about them.
    To explain it more clearly - we will have individual database servers in our sub-divisions and then divisions and centers and then main server. We need to synchronize at various levels. So If any body is aware of any techniques, please let me know.

    Hi,
    Could you tell me what exactly synchronisation your talking about..?
    we will have individual database servers in our sub-divisions and then divisions >>and centers and then main serverIf you have mulitple DB servers then you can connect it by DB links. also if you are talking DB synchronisation then you can have Triggers,Materialized views.
    we also have two independent severs which are synchronised(atleast schema levels).
    Regards!

  • The question about portlet customization and synchronization

    I have a question about portlet customization and synchronization.
    When I call
    NameValuePersonalizationObject data = (NameValuePersonalizationObject) PortletRendererUtil.getEditData(portletRenderRequest);
    portletRenderRequest.setPortletTitle(str);
    portletRenderRequest.putString(aKey, aValue);
    PortletRendererUtil.submitEditData(portletRenderRequest, data);
    Should I make any synchronization myself (use "synchronized" blocks or something else) or this procedure is made thread-safe on the level of the Portal API?

    HI Dimitry,
    I dont think you have to synchronize the block. i guess the code is synchronized internally.
    regards,
    Harsha

  • Diff between Serialization and Synchronization

    Hi I am new to java.
    Pl. give me the difference between Serialization and Synchronization.
    Thankq
    Sridhar

    Don't you look at the timestamps of posts? They could
    have been typing at the same time.
    /KajPlease stop! I'll die laughing. LOL
    Re: Diff between Serialization and Synchronization
    Author: Annie.   Apr 11, 2005 10:30 AM (reply 1 of 4)  
    Re: Diff between Serialization and Synchronization
    Author: glrao   Apr 12, 2005 8:31 AM (reply 2 of 4) I really like your sense of humor.
    xH4x0r

  • Introduction of flow control and synchronization steps in Test Description

    Hi ALL,
              I am working on developing of Test Scripts in ATML standards. Can any one inform me how to introduce flow control (if, else, end, for, while, break etc)  and synchronization (wait etc) steps into the Test scripts. Thanks in advance.
    With Best Regards,
    Kalyan 

    I had a similar issue in a project I am working on. I'm not sure if I did this the "Best Practices" way or not, but it works perfectly.
    In the head area of my JSP I include the following:
    <f:view>
        <h:outputText id="refresher1" rendered="#{queryHandler.queryRunning}">
            <f:verbatim escape="false">
                <meta http-equiv="refresh"
                      content="5,<%=response.encodeURL(request.getContextPath()+
                              "/queryStatus.jsf")%>">
            </f:verbatim>
        </h:outputText>
        <h:outputText id="refresher1" rendered="#{queryHandler.queryFinishedRunning}">
            <f:verbatim escape="false">
                <meta http-equiv="refresh"
                      content="5,<%=response.encodeURL(request.getContextPath()+
                              "/queryResults.jsf")%>">
            </f:verbatim>
        </h:outputText>This puts a 5 second refresh meta in the header to direct the browser to the correct page based on the status of the query thread.
    There are many ways to accomplish the effect you want. I suggest putting all the controls into the JSP and making use of the rendered attributes instead of the JSTL conditionals to show the controls you want for the state of the application.
    -jeffhoward

  • Looking for the perfect workflow on two computers and backup photo's and synchronize LR 5

    I work on two computers. A workstation in the studio and a laptop. I have a harddisk inside the computer containing all photo's. I have a external disk to backup these photo's.
    On the worksation LR catalog sits on a second internal disk. LR runs from another disk. (On the laptop LR runs and contains the catalog on the same disk)
    When working on location I download my photo's to this external harddisk. I also use this external disk to work on my photo's on location (home) with my laptop. Back in the studio I sync the internal and external harddisks.
    I work with LR5 on both the computer and the laptop. After synchronizing the harddisks I open LR and synchronize the folder(s) using " Synchronize Folder ".
    The adjustments I made to the photo's are still there because LR stores these in the RAW files and I use " Include Develop settings in metadata inside JPEG, TIFF, PNG and PSD files "
    But the Virtual copies are not there. I understand why this is happening. I read all about exporting and importing Catalogs.
    How can I synchronize the LR catalog?
    For example. I worked on location. I imported the photo's to the external disk attached to the laptop. I worked on the photo's using LR on the laptop. The next day I want to work on them in the studio using my computer.
    In order not to lose any adjustments and virtual copies I have te export the folder containing the new photo's and import them with LR on my studio computer. I have to include the RAW files in this export: " Export negative files "
    What is the problem?
    So I will need another harddisk. Next the export takes forever. Then I have to import it again. Takes forever too. When I synchronize the harddisk (using synchronizing software) it goes very quickly. But I lose the virtual copies because the LR catalog cannot be synchronized .
    I tried to export the new files as a catalog without "Export negative files" and then after synchronizing the harddisks import this catalog on the second computer.
    This is what happens:
    LR does not see the photo's are already there. The option to import only the metadata is grayed out. It is not possible to tell LR where it should import the photo's. Then LR could see the files are already there and it only has to import the metadata changes.
    Because I need to work on my photo's in the studio and on location this is realy a big problem.
    I know I can work from a external disk on both computers. But that will slow down the workflow extremely because the catalog and the photo's are on the same disk. There are 261.216 photo's in this catalog. So export as a catalog back and forth is not a option.
    Using Export As A Catalog also is a problem.
    When I import new photo's from my camera (card) it is possible to tell LR where to store the files using a Date Format.
    I use YYYY / YYYY-MM / YYYY-MM-DD:
    But when I want to Import From A Other Catalog and tell LR where to store the files it does not see the folder structure already exciting. This a root problem. So it will put the folders where I direct it to and then I have to move the new photo's manually to the correct folders.
    If the folder already excists it cannot merge them. In that case I have to move the new photo's from each day into the appropriate folder for each day !
    This folder structure is important for me because many older photo's are not taged, but are easy to be found by date.
    I probably are overlooking something and the solution is very simple. But I cannot find it ...
    QUESTION : can anyone tell me what would be the best workflow in my case ? And still have a fast system ?

    Here's what I do with the laptop/desktop workflow. Dedicate an big, fast external drive and place ALL Photo's, LR's catalog and presets (set preferences to Store Preset's with Catalog). You have one drive that has all the data you need to access your images and database on any number of computers. All the computer needs is a working copy of Lightroom. Clone that external drive to the backup drive, a 2nd external. Make as many clone's as you wish (one offsite, one in a fire proof safe, one to take on location etc). When one drive has newer data, just clone that to the others, they are all now in sync. One catalog. One master drive. The drive has all images and necessary associated files LR needs to work with (the expectation is lens and DNG camera profiles, the later can be embedded into a DNG and is thus on the drive too).

  • I have two iPhones and synchronize with the same macbook. How I do segregate both applications and data?

    I have two iPhones and synchronize with the same macbook.  How do I segregate both applications and all the data?

    Hi Jamesdwills,
    Welcome to the Support Communities!
    If you are using the same Apple ID on both devices, the Game Center profile should be the same.
    Check out this information from the iPad User Guide.  Try signing out of the Game Center on both devices and then sign back in with the correct Apple ID:
    Using Game Center
    http://support.apple.com/kb/ht4314
    Game Center settings - iPad User Guide
    http://help.apple.com/ipad/7/#/iPad9a13d039
    Game Center settings
    Go to Settings > Game Center, where you can:
    Sign out (tap your Apple ID)
    Allow invites
    Let nearby players find you
    Edit your Game Center profile (tap your nickname)
    Get friend recommendations from Contacts or Facebook
    Specify which notifications you want for Game Center. Go to Settings > Notifications > Game Center. If Game Center doesn’t appear, turn on Notifications.
    Change restrictions for Game Center. Go to Settings > General > Restrictions.
    Cheers,
    - Judy

  • Strange pop-up message after opening LR, import and synchronize disabled, must force quit to close

    I recently started getting this message when running Lightroom and not only does it seem to disable both "Import" and "Synchronize" but it won't close. Nothing happens when I click stop and in order to close my catalog I have to force quit. Any help is much appreciated. Btw, I did have a plug-in which I disabled but that didn't seem to help.
    thanks,
    Adam

    Contact Adobe support thru chat. 
    Serial number and activation chat support (non-CC)
    http://helpx.adobe.com/x-productkb/global/service1.html ( http://adobe.ly/1aYjbSC )

  • Overlay and synchronize video

    Hello,
    Does anyone know, how to overly and synchronize 2 or more videos of athletes, for example alpine skiers, using Premiere Pro? You can see that on the TV sometimes, where 2 racers are put into one track over each other and you can compare their rides? They are using special technology on the TV, probably Dartfish. But I hope somebody has some idea how to do it in Premiere? I have put one video over the second and set the opacity to 50%. Then I moved the upper video and adjusted its size, so that the gates (the skiers were at) matched. I created keyframes for couple of gates and for each of them I repeated the same and hoped Premiere would do the rest. But the result isn't good, the skiers drive away just a moment after leaving the gate. Any tips? Thanks. Ivan

    Just for future reference, should anyone be looking at this thread for more information:
    This link has a table with all major DIAdem features and what type of license (Base, Advanced or Professional) is required to use these features:
    http://www.ni.com/diadem/buy/
    The Professional license adds
    3D model data mapping
    GPS map layouts
    to the features already present in the Advanced version (including video synchronization).
    This page has a very detailed list of features, with more in depth descriptions and screen shots:
    http://sine.ni.com/ds/app/doc/p/lang/en/id/ds-263#view.base
    Maybe this is helpful to someone ...
         Otmar
    Otmar D. Foehner
    Business Development Manager
    DIAdem and Test Data Management
    National Instruments
    Austin, TX - USA
    "For an optimist the glass is half full, for a pessimist it's half empty, and for an engineer is twice bigger than necessary."

  • Getting images using URLConnection.getInputStream

    Hi,
    I'm trying to get an image with the following code but the image is garbled. Does anyone know what I'm missing?
    try
    PrintWriter out =response.getWriter();
    String userUrl= "http://freshmeat.net/img/url_changelog.gif"
    int buffer=4096;
    byte[] stream = new byte[buffer];
    int input=0;
    URL url = new URL(userUrl);
    URLConnection conn = url.openConnection();
    String contentType=conn.getHeaderField("Content-Type").toUpperCase();
    if(!contentType.equals("TEXT/HTML"))
    response.setContentType(contentType.toLowerCase());
    BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
    while((input = in.read(stream, 0, buffer)) >=0 )
    out.write(new String(stream).toCharArray());
    in.close();
    in=null;
    out.flush();
    out.close();
    Thanks,
    Ralph

    It's not what you are missing, it's what you have extra. You are converting the stream of bytes to a String. That is what garbles your image. Don't do that. Instead, doOutputStream out = response.getOutputStream();and copy the bytes to it, using basically the same code you are using now.

  • URLConnection.getInputStream() craches thread

    Hi
    I'm trying to parallelize a downloading process i'm developing, and my download started to behave a bit sporadic. The thread dies right after the System.out.println("1") in the following code snippet, s is an url.
    for(String s:urls) {
      try {
        URL url = new URL(s);
        URLConnection uc = url.openConnection();
        System.out.println("1 " + s);
        InputStream is = uc.getInputStream();
        System.out.println("2");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));the output from strace (list of system commands) on my system shows the following relevant part:
    [pid  4438] write(1, "1 http://alatest1-cnet.com.com/4"..., 513 http://alatest1-cnet.com.com/4941-3000_9-0-1.html) = 51
    [pid  4438] write(1, "\n", 1
    ) = 1
    [pid  4438] gettimeofday({1174556453, 323179}, NULL) = 0
    [pid  4438] send(17, "GET /4941-3000_9-0-1.html HTTP/1"..., 177, 0) = 177
    [pid  4438] recv(17, <unfinished ...>
    [pid  4438] <... recv resumed> 0xb52e6cb0, 8192, 0) = ? ERESTARTSYS (To be restarted)
    this is the last output from this pid, it seems like it just lies down and dies efter it got the ERESTARTSYS.
    I have tried this on java 1.6.0 and 1.5.0_07 with linux kernel 2.6.17.7.
    Am I calling the connecting function wrong, or is there some other error maybe?

    sorry to be a little unclear.
    I don't get any exceptions, and i also added a catch(Exception e) { System.out.println(e); } to make sure.
    The Thread doesn't hang, it just dies silently.

Maybe you are looking for

  • How can I disable Pages 5.1 and make 4.0.3 the default again?

    Does anyone know how to disable Pages 5.1 so that it NEVER opens a doc again unless I somehow re-enable it? I don't want to delete it in case someone sends me a tainted 5.1 Pages doc. Plus I'm sure if I DO delete it, it will keep showing up like a ba

  • Error while running report from Form. i am using Forms 10g.

    dear all, here is a problem when running the report from a fom. gives the pollowing error. REP-110: Unable to open file 'f:\oracle\accano\gl\coa_list.rdf'. REP-1070: Error while opening or saving a document. REP-0110: Unable to open file 'f:\oracle\a

  • How do I sync bookmarks between my desktop and my Android phone?

    ''locking - please continue in your original thread - https://support.mozilla.org/en-US/questions/998765'' I watched a Firefox tutorial. It said to pull down the Firefox menu and click on "Sign in to sync" However, when I pull down the Firefox menu o

  • Error opening PDF attachment (via email)

    Hello, I've problems to send a PDF file with the function: 'SO_DOCUMENT_SEND_API1' At first a small overview of my process: - 'SCMS_DOC_READ'                 -> to read the file from the archive - 'SCMS_BINARY_TO_FTEXT'     -> to convert from bin. to

  • How do i find my iphone if its offline

    help me i lost my i phone and it dead and off line and i dont know what to do