HTTP posts and multiple threads in Java

I am writing an internal Java Applet to do file uploads via HTTP. I started using the built in ClientHttpRequest which worked great if I want to post one after another. When I try to have multiple threads post at the same time, something on the server side freaks out and the connection will hang for large files while still uploading the smaller files. (Large seems to be around 10 megs) After lots of looking, I would not able to find a timeout that I could set to recover from this error, but finally found ClientHttp from Apache which DOES provide a mechanism to set a timeout. The problem with it is that while it claims to be able to work in a multi-threaded program, it actually only does one request after another. I have found lots of example code for HttpClient which says it will work for multiple threads and have made adjustments to my code to incorporate those changes, but none of them make any difference, and I am still stuck with essentially 1 thread.

While multiple threads really are not required for release (HttpClient does seem to be a bit faster than ClientHttpRequest), it would be really nice to get that extra speed boost since there are a lot of smaller files that could be sent at the same time.

The files are being sent over HTTP because we want to use the same authentication of the already logged in user using their session cookies.

So I am looking for either a way to set a timeout with ClientHttpRequest or code for HttpClient that will actually send multiple requests at the same time as promised.

I am sharing the same HttpClient instance between threads and using the multithreaded connection manager (it won't even work without this) like the docs say and it doesn't help.

Any help would be appreciated and let me know if you need any clarifications.

Asked by: Kate633 | Posted: 21-01-2022

Answer 1

Seeing a sample of your code might help.

Perhaps the problem is the applet environment. Are you testing it in appletviewer, IDE, or in the browser? Browsers are generally setup to limit the number of connections to the same web server to 2. You might try adding a main() and running it standalone to see if that fixes the problem.

Answered by: Maya141 | Posted: 22-02-2022

Similar questions

multithreading - java: adding values to a map by multiple threads (is it possible ?)

is it thread safe to add elements to a Map by multiple threads at the same time ? Like if 10 threads add an element to a Map at exactly the same time, is the Map going to have 10 elements or 1 ? UPDATE: I don't need to iterate through this map, all I need is to add, remove and get elements by key

multithreading - Java class to allow multiple threads to read or one to modify at the same time

Let's say you have the following class: class A { private Foo foo = new Foo(); Foo getFoo() { return foo; //foo.clone()? } void modifyFoo() { //modify //... } } I want to allow: either multiple threads to call getFoo() or one thread to call modifyFoo(), once a thread wants to modi...

multithreading - how to make Java uses multiple cores with threads?

This is a similar question to the one appearing at: How to ensure Java threads run on different cores. However, there might have been a lot of progress in that in Java, and also, I couldn't find the answer I am looking for in that question. I just finished writing a multithreaded program. The program spawns s...

multithreading - Create Multiple Threads in certain time for Java

What is the best way to create 500.000 threads in 5 seconds. (Runnable) I created for loop but it takes lots of time. For example; startTime = System.currentTimeMills(); for (int i=0;i<500.000; i++){ // create thread thread.start(); } resultTime = (System.currentTimeMills() - startTime); So the resultTime is bigger than 5 seconds. I know it depends on my hardware and os configurati...

multithreading - Java multiple threads work on one field

Hi I have the following piece of code: public Item get(int id) { Item i = null; for(Worker w : workers) { w.get(id, i); // Several threads start reading that item from data sources } while(i == null) // Loop until item is found { // this.pause(); there should be a pause but it's not a thread, so I can't do it. } return i; } I think there shou...

multithreading - How to allow multiple threads to access a random access file at the same time in Java

This question already has answers here:

multithreading - Java Swing with multiple threads

The problem is: i have a swing app. Only one form with 2 btns ("Start","Stop"). On these btns i added ActionListener with thread class inside. I want to start in new thread some work when i click btn "Start" and end that work when i click btn "Stop". Code a little bit similar to this works ok in console, but in swing doest. Any help appreciated. Thanks in advance. ) class Action implements Acti...

multithreading - Java - multiple threads writing to same file

This question already has answers here:

multithreading - Using Multiple Threads in Java To Shorten Program Time

I do not have much experience making multi-threaded applications but I feel like my program is at a point where it may benefit from having multiple threads. I am doing a larger scale project that involves using a classifier (as in machine learning) to classify roughly 32000 customers. I have debugged the program and discovered that it takes about a second to classify each user. So in other words this would take 8.8 hours t...

multithreading - Multiple threads unable to share common refresh token in Java Spring OAuth2

I have a Java application that is running within the Spring 3.x framework and utilizes the off-the-shelf Spring OAuth2 implementation (JDBC persistence). My application exposes a REST interface that will be used by partners. Those applications will have a variable number of threads all hitting my application. 'Variable' is the key thing here. Ideally, I would like a single refresh token to be used per partner ...

multithreading - How do I make multiple threads and classes write into the same log file in Java?

Within a java application, I have several Classes and Threads here and there. I would like them all to write their logs to one single file. How can I achieve that? Also here's some more questions: Do I receive the same instance of a logger if I define the same name for them even in different classes. To be clear, are the following two loggers the same: class MyClass1 { Logger lo...

multithreading - Can one object create multiple threads in Java

I am new to multi threading and while practising I wrote the following code. I want to call the createThred method to create a new thread evrytime I call it. However, With the below given code, everytime the createThread method is called, i get the same thread running again and again. Is it possible to create a new thread using the same object? Appararently not but just wanted to confirm if there is a way I dont know of.

multithreading - write from multiple threads on same file without locking, Java

I am making a download manager and I want multiple threads downloading different segments of file to write to file at different places at a time. Just for every one's clarification I dont want file to lock because it will kill the purpose of different threads writing at a time. I am using Apache HttpClient library and FileChannel transferFrom(). Current code only downloads the first segment and simply ignores other segment...

multithreading - In Java, how can I wait for one of multiple threads to exit?

In Java you can use Thread.join() to wait for a thread to exit Is there a similar method that will allow you to wait for any thread in a list of threads to exit? This would be similar to the wait(2) Unix system call that returns when any child process exits.

multithreading - Java Multiple Threads Demo not Working

I'm writing a small program to see how multiple threads can be run in Java. Not sure why I'm not getting any output: class NuThread implements Runnable { NuThread() { Thread t = new Thread(this, "NuThread"); t.start(); } public void run() { try { for (int i=0; i<5; i++) { Thread th = Thread.currentThread();

multithreading - Why is my code slower using multiple threads in Java?

Closed. This question needs debugging detai...

multithreading - using multiple java threads CPU usage reach 100%

i have created a Download Class extends thread and it has a randomaccessfile as a field; inside the run method i use http Header-Range for different portions to be downloaded by multiple Download Class after that i'm using this while loop. @Override public void run() { InputStream stream = null; this.setPriority(Thread.MAX_PRIORITY); try { // Open connection to URL. ...

multithreading - Java run multiple threads from for loop with different names

I am trying to start a variable number of threads within a for loop and want to name the threads prime1, prime2, [...]. The PrimeFinderThread Class extends from Thread. [...] for (int i = 0; i <= numberThreads; i++) { PrimeFinderThread ("prime" + i) = new PrimeFinderThread (lowerBoundary, interval); } [...] I am getting the error:

multithreading - Multiple java threads on a 2-core Mac - Slow

I've been writing the following code for my OS course and I got some weird results. The code creates x threads and runs them concurrently in order to multiply two squared matrices. Every thread will multiply Number_of_rows/Number_of_threads rows of the input matrices. When running it on a 1024X1024 matrices, with 1...8 threads, I get that the fastest multiplication happens when using only one thread. I would expec...

multithreading - How can we call multiple threads in Java?

Is there any way to call a thread after finishing the work of another thread? I just want to call three threads back to back as work gets finished of previous thread. I'm trying this public class TestThreads { public static void main (String [] args) { MyRunnable r = new MyRunnable(); Thread first = new Thread(r); Thread second = new Thread(r); Thread third = new Thread(r); first.start(); second.sta...

multithreading - How do I handle multiple key presses in a Java Applet?

I am teaching myself, from online tutorials, how to write games in Java. I am using Java Applets to create a Pong game. each paddle is controlled from different keys for 1v1 competition. this works fine if both users are hitting the keys at different times. but when one key is being held down and then another key is held down(ex: holding down on the arrow key, then user 2 holds the 'S' key), the second key overrides the ...

multithreading - Getting multiple Java pop3 clients to work with GMail

I have written a nice program in Java that connects to a gmail account and download atachments sent to it. Once an attachment has been downloaded, it is marked as read and is not downloaded ever again. This program will have to run in multiple instances with each program downloading unique attachments so that a single attachment is never downloaded twice. The problem is that at the moment if the attachment is of a decent s...

multithreading - Waiting on multiple threads to complete in Java

During the course of my program execution, a number of threads are started. The amount of threads varies depending on user defined settings, but they are all executing the same method with different variables. In some situations, a clean up is required mid execution, part of this is stopping all the threads, I don't want them to stop immediately though, I just set a variable that they check for that terminates them....

multithreading - Single or multiple thread pools for Java server?

Closed. This question is opinion-based. It is not c...

multithreading - java: adding values to a map by multiple threads (is it possible ?)

is it thread safe to add elements to a Map by multiple threads at the same time ? Like if 10 threads add an element to a Map at exactly the same time, is the Map going to have 10 elements or 1 ? UPDATE: I don't need to iterate through this map, all I need is to add, remove and get elements by key

multithreading - Java logging across multiple threads

We have a system that uses threading so that it can concurrently handle different bits of functionality in parallel. We would like to find a way to tie all log entries for a particular "transaction" together. Normally, one might use 'threadName' to gather these together, but clearly that fails in a multithreaded situation. Short of passing a 'transaction key' down through every method call, I can't see a way to t...

multithreading - Running a command line program multiple times in Java - is this correct?

I have a program (in Java) that needs to use another program multiple times, with different arguments, during it's execution. It is multi-threaded, and also needs to do other things besides calling that program during it's execution, so I need to use Java to do that. The problem is, all Runtime.exec() calls seem to be done in a synchronized way by Java, such that threads get bottlenecked not around the...

multithreading - How does Java makes use of multiple cores?

A JVM runs in a single process and threads in a JVM share the heap belonging to that process. Then how does JVM make use of multiple cores which provide multiple OS threads for high concurrency?

multithreading - Pointer of an object in Java with multiple threads

I have two threads. One thread has an instance of myObjectManager. myObjectManager has a list of objects, and a method for retrieving an object( public myObjectClass getObjectById(int ID) ) I need the first thread to render an object in myObjectManagers list of objects, and the second thread to perform game logic and move it around etc. This is what I tried //thread 1: m =

multithreading - Use of multiple threads in a Java program and vs need to create Swing objects on EDT

Re: Requirement to create Swing Object on Event-Dispatch Thread. I am working on an application, the purpose of which is to monitor and display the condition of various remote embedded servers. I'm pretty new to Java, and my understanding of the requirement with respect to the Swing Objects and the EDT is incomplete. The main GUI is started on the EDT in the usual fashion as follows, jav...

multithreading - Java BlockingQueue of Size=1?

Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue. I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want? Ex...

multithreading - Tools for finding Shared Mutable data bugs in Java

I have a large legacy system to maintain. The codebase uses threads all over the place and those threads share a lot of mutable data. I know, sounds bad. Anyway, don't answer "rewrite the whole application from scratch" or I'll vote you down :-) I have tried to run some static analysis tools on the codebase, but none of those seem to catch this case which occurs a lot in our source code: multiple threads are reading and wr...

multithreading - synchronizing io operation in java on a string method argument?

This question already has answers here:

multithreading - Stopping a Thread in Java?

This question already has answers here:

multithreading - Threading issues in a Java HashMap

Something happened that I'm not sure should be possible. Obviously it is, because I've seen it, but I need to find the root cause & I was hoping you all could help. We have a system that looks up latitude & longitude for a zipcode. Rather than access it every time, we cache the results in a cheap in-memory HashTable cache, since the lat & long of a zip code tend to change less often than we release.

multithreading - Firing a mainline event from a background thread in Java

My question pertains to multi-threading in Java. I'm translating an app I wrote in Visual Basic 2008 into Java. There is a class in VB called BackgroundWorker, which allows the coder to perform a task on another thread, a lot like SwingWorker in Java. The only distinct difference ...

multithreading - Java: Run a Callable in a separate process

Given an instance x of Callable<T>, how can I run x in a separate process such that I can redirect the standard input and output of the process? For example, is there a way to build a Process from a Callable? Is there a standard Executor that gives control over input and output? [UPDATE] It's not important that the Callable

multithreading - How can you ensure in java that a block of code can not be interrupted by any other thread

exampl: new Thread(new Runnable() { public void run() { while(condition) { *code that must not be interrupted* *some more code* } } }).start(); SomeOtherThread.start(); YetAntherThread.start(); How can you ensure that code that must not be interrupted won't be interrupted?

multithreading - Java while loop and Threads!

This question already has answers here:

multithreading - In Java critical sections, what should I synchronize on?

In Java, the idiomatic way to declare critical sections in the code is the following: private void doSomething() { // thread-safe code synchronized(this) { // thread-unsafe code } // thread-safe code } Almost all blocks synchronize on this, but is there a particular reason for this? Are there other possibilities? Are there any best practices on what object to sync...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)