I am working in online application, in which there is facility of creating group. I want facility to send mail to all group user when any activity done in group. like comments , start new discussion etc. But problem is that . if any small activity i send thorusand of mail at run time. it slow the performance.
For that i am thinking to create new independent thread. to send mail which send mail to thousand of user and main thead with out any problem come to group page.
How i will make new thread in class.
thanks in advances.
for more info visit http://www.rameshsengani.in
new Thread(new Runnable() {
#Override
public void run() {
// do stuff here
}
}).start();
This is the accepted Java pre-1.5 way. You can take a look at the java.util.concurrent package and the executor framework.
Related
On my Android App, I'm implementing SignalR connection (https://github.com/erizet/SignalA) to connect to a Hub server to send requests and receive responses.
a sample of my code is as follows:
signalAConnection = new com.zsoft.SignalA.Connection(Constants.getHubUrl(), this, new LongPollingTransport())
{
#Override
public void OnError(Exception exception)
{
}
#Override
public void OnMessage(String message)
{
}
#Override
public void OnStateChanged(StateBase oldState, StateBase newState)
{
}
};
if (signalAConnection != null)
signalAConnection.Start();
There's also the sending bit
signalAConnection.Send(hubMessageJson, new SendCallback()
{
public void OnError(Exception ex)
{
}
public void OnSent(CharSequence message)
{
}
});
The sending and receiving will occur across activites, and some responses will be sent at random times regardless of the activity, also, the connection should be opened as long as the app is running (even if the app is running in the background) that's why I wish to implement the signalA connection as a background service
The question is should I implement it as:
1 - a Service (http://developer.android.com/reference/android/app/Service.html)
OR
2 - an Intent Service (http://developer.android.com/training/run-background-service/create-service.html)
Keeping in mind that I will need to send strings to the service and get response strings from the service.
I would be most grateful if someone would show me how to implement this kind of connection in code as a background service/intentservice.
Thanks for reading.
UPDATE:
Please see this demo activity made by the developer as how he implemented SignalA
https://github.com/erizet/SignalA/blob/master/Demo/src/com/zsoft/SignalADemo/DemoActivity.java
The problem is AQuery (which I know nothing about) is being used in this demo activity. Does AQuery run in the background all the time ?
The problem is, the latest update on SignalA mentions the following
I have changed the transport. LongPolling now uses basic-http-client
instead of Aquery for http communication. I've removed all
dependencies on Aquery.
Hence I'm not sure whether I should follow this demo activity or not
Update 2:
This is the thing that is confusing me most
in the IntentService, the OnHandleIntent method calls stopSelf after it finishes its tasks, when I actually want the code in the IntentService to keep running all the time
protected abstract void onHandleIntent (Intent intent)
Added in API level 3
This method is invoked on the worker thread with a request to process. Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic. So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf().
SignalA is running on the thread that creates and starts the connection, but all network access is done in the background. The remaining work on the starting thread is really lightweight, hence its perfectly ok to do it on the UI tread.
To answer your question, you need to have a thread running the signala connection. Therefore I think a Service is the best choice since SignalA need to be running all the time.
Regarding Aquery and the demo project. I removed all dependencies to Aquery in the libraries, not in the Demo. To be clear, you don't need Aquery to run SignalA.
In my case, what I wanted was a Service not an Intent Service, since I wanted something that would keep running until the app closes
im using play framework 2.1.1 and java ,
im submitting a form and i can insert the data to the database,
also im sending mail by using the wonderful mailer plugin
what will be the best way to perform both action paralleled instead of one after the other ,
should i use ThreadPools or there is a more simple solution.
UPDATE SOLUTION :
this is how i solve it in the end
private static void sendMailHelper(final UserData formData) {
Akka.system().scheduler().scheduleOnce(
Duration.create(10, TimeUnit.SECONDS),
new Runnable() {
public void run() {
SendMail.sendMail(formData);
}
}, Akka.system().dispatcher());
}
i sent mail 10 sec after the user submit the form
If you are using Scala, then these pages should help you:
http://docs.scala-lang.org/overviews/core/futures.html
http://www.playframework.com/documentation/2.1.1/ScalaAsync
If you are using Java, then these pages should help you:
http://www.playframework.com/documentation/2.1.1/JavaAsync (as Carsten pointed out)
You could also use Akka Actors, check this page:
http://www.playframework.com/documentation/2.1.1/JavaAkka
Is there a way to call an #Signal function from within an Activity in an Amazon SWF Workflow.
I want to be able to notify the workflow that some processing has completed and it should spawn a child workflow for that subset of the processing.
How would this be done?
It sounds like you want to tell workflow that some part of activity is complete, but you want to continue running current activity. If this is the case, then I recommend you to split your activity into 2 parts and use result from first part to tell if child workflow need to be spawned. I don't think that sending signal to workflow in the middle of activity is possible in Flow framework. But you can use raw SWF API to send signal (in this case you'll need to pass "Run ID" to your activity as one of parameters).
The generated workflow external client should be used to send signal from within activity code. ActivityExecutionContext contains all the data necessary to initialize it:
public class MyActivitiesImpl implements MyActivities {
private final ActivityExecutionContextProvider contextProvider = new ActivityExecutionContextProviderImpl();
public void sendSignalBackActivity() {
ActivityExecutionContext context = contextProvider.getActivityExecutionContext();
AmazonSimpleWorkflow service = context.getService();
String domain = context.getDomain();
WorkflowExecution workflowExecution = context.getWorkflowExecution();
MyWorkflowClientExternalFactory factory = new MyWorkflowClientExternalFactoryImpl(service, domain);
GreeterClientExternal workflow = factory.getClient(workflowExecution);
workflow.signalMethod();
}
}
As external client calls SignalWorkflowExecution SWF API it can fail due to intermittent connectivity issues. So an activity implementation might decide to catch and deal (possibly by retrying) with AmazonServiceException which is thrown in such cases.
I'm struggling to wrap my head around what needs to happen here. I'm currently working on an app that runs a service. The service when started opens a webserver that runs in a background thread.
At any point while this service is running the user can send commands to the device from a browser. The current sequence of events is as follows.
User sends request to server
Server sends a message to the service via the msg handler construct, it sends data such as the url parameters
The service does what it wants with the data, and wants to send some feedback message to the user in the browser
?????
The server's response to the request contains a feed back message from the service.
The way my functions are set up I need to pause my serve() function while waiting for a response from the service and then once the message is received resume and send an http response.
WebServer.java
public Response serve( String uri, String method, Properties header, Properties parms, Properties files )
{
Bundle b = Utilities.convertToBundle(parms);
Message msg = new Message();
msg.setData(b);
handler.sendMessage(msg);
//sending a message to the handler in the service
return new NanoHTTPD.Response();
}
CommandService.java
public class CommandService extends Service {
private WebServer webserver;
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
execute_command(msg.getData());//some type of message should be sent back after this executes
};
Any suggestions? Is this structure the best way to go about it, or can you think of a better design that would lead to a cleaner implementation?
I think the lack of answers is because you haven't been very specific in what your question is. In my experience it's easier to get answers to simple or direct questions that general architecture advice on StackOverflow.
I'm no expert on Android but I'll give it a shot. My question is why you have a Webservice running in the background of a Service, why not just have one class, make your Service the Webservice?
Regarding threading and communication and sleeping, the main thing to remember is that a webserver needs to always be available to serve new requests, whilst serving current requests. Other than that, it's normal that a client will wait for a thread to complete its task (i.e. the thread "blocks"). So most webservers spawn new a thread to handle each request that comes in. If you have a background thread but you block the initial thread while you wait for the background thread to complete its task, then you're no better off than just completing everything on the one thread. Actually, the latter would be preferable for the sake of simplicity.
If Android is actually spawning new threads for you when requests come in, then there's no need for a background thread. Just do everything synchronously on one thread and rejoice in the simplicity!
I'm developing a multithreaded web server for an android app and I've some problems with a page that uses an external .css file, and a .js file, but only with Google Chrome! With Firefox and Opera the page is rendered fine, with Google Chrome sometimes the .css is loaded, sometimes the .js, sometime both or neither.
This is my app's structure:
WebServer.java
class WebServer implements Runnable{
protected boolean ON;
public void start(){
if(!ON){
ON=true;
thread=new Thread(this,"WebServer");
thread.start(); }}
public void run(){
while(ON){
listenSocket = new ServerSocket(port);
Socket connectionSocket = listenSocket.accept();
Thread t = new Thread(new Client(connectionSocket));
t.start();
listenSocket.close();}
}}
Client.java
class Client implements Runnable {
public void start(){
thread=new Thread(this,"Client");
thread.start();}
public void run(){
//parse the request and send a file
}
}
myApp.java
public class myApp extends Activity{
onCreate(){
WebServer ws=new WebServer(8080);
}
onClick(){
...
ws.start();
}}
When I click a button on the activity, it call webserver.start(); In my opinion google chrome sends more requests concurrently and there's a problem with threads...
Can you help me?
[EDIT]
I had forgotten to write the loop in the run() method in the question
[EDIT 2]
I just tried with an other pc, and there are problems also with firefox..
There is a general misunderstanding of the thread mechanism in your code.
A runnable has to override run. Not start. The run() method of the runnable will be called when the nesting thread will be started. In other words, the start method of your client will never be used, and hope fully, as it would create a thread inside a thread.. not very usefull.
Redesign your webser so that, :
it's start method starts a new nesting thread as you did
it's run method does the following
your webserver binds to a port
in a loop : accept new connections and start new client thread for each.
the loop could be controlled by a boolean flag that you could rise to stop the server (ON would fit, even if the name of this variable doesn't follow java naming conventions and is rather poor semanticly speaking)
then each client would, in it's run (no more start method) :
read data from socket input stream
reply on socket outputstream
briefly, implement http protocole.
You could find some java code to inspire you on the web, some examples are well documented. Also, you could consider using java.nio package that is maybe less effective for a single request but much more effective at handling massive multiple connections. But code is harder.
You should consider reading more about runnables and also consider reading some stuff about synchronized key word to ensure that your web server doesn't start twice a connection for the same client or get confused in case of simultaneous requests.
Regards,
Stéphane