In my application , I have this logic when the user logins , it will call the below method , with all the symbols the user owns .
public void sendSymbol(String commaDelimitedSymbols) {
try {
// further logic
} catch (Throwable t) {
}
}
my question is that as this task of sending symbols can be completed slowly but must be completed , so is there anyway i can make this as a background task ??
Is this possible ??
please share your views .
There is no really simple solution. Basically you need another thread which runs the method, but you also have to care about synchronization and thread-safety.
Maybe a better way would be to use Executors
But you will need to case about thread-safety. This is not really a simple task.
The following is an example of how to use threads. You simply subclass Runnable which contains your data and the code you want to run in the thread. Then you create a thread with that runnable object as the parameter. Calling start on the thread will run the Runnable object's run method.
It sure is possible. Threading is the way to go here. In Java, you can launch a new thread like this
When you call start(), it launches a new thread. That thread will start running the run() function. When run() is complete, the thread terminates. Be careful, if you are calling from a swing app, then you need to use SwingUtil instead. Google that up, sir.
Hope that works.
You need to spawn a separate thread to perform this activity concurrently. Although this will not be a separate process, but you can keep performing other task while you complete sending symbols.
Sure, just use Java Threads, and join it to get the results (or other proper sync method, depends on your requirements)
Something like this is what you're looking for.
Create an executor service. This will keep a pool of threads for reuse. Much more efficient than creating a new Thread each time for each asynchronous method call.
If you need a higher degree of control over your ExecutorService, use ThreadPoolExecutor. As far as configuring this service, it will depend on your use case. How often are you calling this method? If very often, you probably want to keep one thread in the pool at all times at least. I wouldn't keep more than 4 or 8 at maximum.
As you are only calling
sendSymbol
once every half second, one thread should be plenty enough givensendSymbols
is not an extremely time consuming routine. I would configure a fixed thread pool with 1 thread. You could even reuse this thread pool to submit other asynchronous tasks.As long as you don't submit too many, it would be responsive when you call
sendSymbol
.