I have a Spring Boot app (jar file) that is running on Windows server and is used to sync data between some tables in a database and other parts of infrastructure (consumer apps via ActiveMQ).
It is crucial to have it running 24/7 without any downtime (or with very little).
I am currently trying to find the best way to do this as our current solution is to run multiple instances of the same app and define one to be active and ping it continuously (via an entry in database where it writes every 15 seconds), while other instances are just running and do nothing (inactive state, cause lock is taken). If an active instance has stopped to update lock entry (freeze or crashed) in database one of the available instances will take its place and start to handle data.
I have a feeling, that it is not so flexible solution, especially when I need to prepare different part of my code to check lock entry and sync all those instances. It adds complexity to the code and I want to avoid it.
Is there any better solution? Plugins, implementation pattern or tools?
PS:
I read about health endpoints that are available in a SpringBootApplication and think that it can help me somehow (ping\check them from some other Watchdog software\tool, maybe?), but don't know how.
In case of a crash you still have a delay of 15 seconds while a request can fail
I would go with a zuul router from netflix (open source)
It will balance the load between instances and will retry your request on another instance if the first call has failed
I'm pretty sure it's already done but use windows services to restart instance in case of hard crash
Bidding sites like quibids and ebay has a countdown showing how much time left for the auction. I know this can be taken care on FE and should be fairly easy. What I want to know is how to do this on server side? like sending an email to people participate but didn't win and updating database when times up. I've thought about two approaches to do this.
keep the timer on client side and do updates when the first request hit
open a new thread and make it sleep for x amount of time then wake up to do the updates.
Both approaches don't sound right to me and will lead to issues I think. Like user will likely not getting the updates on time, or server will have lots of sleeping beauty waiting.
What I want to know is how to do this on server side? like sending an
email to people participate but didn't win and updating database when
times up.
The best way may vary depending of technology stack of your server side.
You if are running from a Servlet container (e.g.: Tomcat, Jboss...), you
probably want to do something similar to this: Background timer task in JSP/Servlet web application
If you are running a Spring application (e.g.: Spring Boot or Spring MVC), then I recommend #Scheduled or other Task Execution and Scheduling
For advanced scenarios you may want to go with Quartz
Something else, then you should try hooking it up with Java Timer Task
To schedule a task, use a ScheduledExecutorService.
I am an experienced application developer who now has to develop a web application which I don't have a lot of experience in.
I am working on a project that has a number of distributed server components. It currently has a client application that monitors these components, view alarms and logs etc. The state of each of the server machines is delivered via a proprietary protocol over tcp/ip.
The current UI based app has a thread that continually monitors the socket connection for messages and once received stores in-memory the current state of everything and then displays this to the user.
My question is how do I achieve something similar in a web application environment. My first thought was to create a similar comms thread on server start and then when the user requests data the response is built up from the in-memory data but reading about web applications starting your own threads is bad practise.
I have read a little about using Quartz or TimerTask to run periodic schedule tasks in web applications but this task is more continuous. Is it still the way to go?
I'm developing the web app in Java using JSF running Tomcat on Linux. Oh and the application will have a low number of concurrent users. (25 max but more likely 2 or 3)
Approach 1
Using Quartz is good. It is advised not to use TimerTask.
Approach 2
I am assuming that the web application has some sort of database. Since you need to display the states on user request, not real time what you can do is that write a standalone daemon application (not a web application) which reads for server states and updates a table which is visible to the web application. When the user request is made this table can be referred to produce output.
Why make this a server concern? In your client (the browser) you can poll the current state and adjust the display according. Doing this removes a lot of complexity.
As to how your client will be updating, that's dependent on your app. If you can allow for only modern browsers, you could look into HTML5 WebSockets. Other options are using AJAX for partial update of the screen or a complete screen refresh.
I am working on project in which we have an authentication mechanism. We are following the below steps in the authentication mechanism.
The user opens a browser and enter his/her email in a text box and click the login button.
The request goes to a server. We generate a random string (for example, 123456) and send a notification to the user's Android/iPhone and makes the the current thread wait with the help of the wait() method.
The user enters a password on his/her phone and clicks the submit button on his/her phone.
Once the user clicks the submit button, we are making a webservice hit the server and passing the previously generated string (for example, 123456) and password.
If the password is correct against the previously entered email, we call the notify() method to the previously waiting thread and send success as the response and the user gets entered into our system.
If the password is incorrect against the previously entered email, we call the notify() method to the previously waiting thread and send failed as the response and display an invalid credential message to the user.
Everything is working fine, but recently we moved to a clustered environment. We found that some threads are not notified even after replied by the user and for an unlimited waiting time.
For the server, we are using Tomcat 5.5, and we are following The Apache Tomcat 5.5 Servlet/JSP Container for making tomcat cluster environment.
Answer :: Possible problem and solution
The possible problem is the multiple JVMs in a clustered environment. Now we are also sending the clustered Tomcat URL to the user Android application along with generated string.
And when the user clicks on the reply button, we are sending the generated string along with the clustered Tomcat URL so in this case both requests are going to the same JVM, and it works fine.
But I am wondering if there is a single solution for the above issue.
There is a problem in this solution. What happens if the clustered Tomcat crashes? The load balancer will send a request to the second clustered Tomcat and again the same problem will arise.
The underlying reason for your problems is that Java EE was designed to work in a different way - attempting to block/wait on a service thread is one of the important no-no's. I'll give the reason for this first, and how to solve the issue after that.
Java EE (both the web and EJB tier) is designed to be able to scale to very large size (hundreds of computers in a cluster). However, in order to do that, the designers had to make the following assumptions, which are specific limitations on how to code:
Transactions are:
Short lived (eg don't block or wait for periods greater than a second or so)
Independent of each other (eg no communication between threads)
For EJBs, managed by the container
All user state is maintained in specific data storage containers, including:
A data store accessed through, eg, JDBC. You can use a traditional SQL database or a NoSQL backend
Stateful session beans, if you use EJBs. Think of these as Java Bean that persists its fields to a database. Stateful session beans are managed by the container
Web session This is a key-value store (kinda like a NoSQL database but without the scale or search capabilities) that persists data for a specific user over their session. It's managed by the Java EE container and has the following properties:
It will automatically relocate if the node crashes in a cluster
Users can have more than one current web session (i.e. on two different browsers)
Web sessions end when the user ends their session by logging out, or when the session is inactive for longer than the configurable timeout.
All values that are stored must be serializable for them to be persisted or transfered between nodes in a cluster.
If we follow those rules, the Java EE container can successfully manage a cluster, including shutting down nodes, starting new ones and migrating user sessions, without any specific developer code. Developers write the graphical interface and the business logic - all the 'plumbing' is managed by configurable container features.
Also, at run time, the Java EE container can be monitored and managed by some pretty sophisticated software that can trace application performance and behavioural issues on a live system.
< snark >Well, that was the theory. Practice suggests there are pretty important limitations that were missed, which lead to AOSP and code injection techniques, but that's another story < /snark >
[There are many discussions around the 'net on this. One which focuses on EJBs is here: Why is spawning threads in Java EE container discouraged? Exactly the same is true for web containers such as Tomcat]
Sorry for the essay - but this is important to your problem. Because of the limitations on threads, you should not block on the web request waiting for another, later request.
Another problem with the current design is what should happen if the user becomes disconnected from the network, runs out of power, or simply decides to give up? Presumably you will time out, but after how long? Just too soon for some customers, perhaps, which will cause satisfaction problems. If the timeout is too long, you could end up blocking all worker threads in Tomcat and the server will freeze. This opens your organisation up for a denial of service attack.
EDIT : Improved suggestions after a more detailed description of the algorithm was published.
Notwithstanding the discussion above on the bad practice of blocking a web worker thread and also the possible denial of service, it's clear that the user is presented with a small time window in which to react to the the notification on the Android phone, and this can be kept reasonably small to enhance security. This time window can also be kept below Tomcat's timeout for responses as well. So the thread blocking approach could be used.
There are two ways this problem can be resolved:
Change the focus of the solution to the client end - polling the server using Javascript on the browser
Communication between nodes in the cluster allowing the node receiving the authorization response from the Android App to unblock the node blocking the servlet's response.
For approach 1, the browser polls the server via Javascript with an AJAX call to a web service on Tomcat; the AJAX call returns True if the Android app authenticated. Advantage: client side, minimal implementation on the server, no thread blocking on the server. Disadvantages: During the waiting period, you have to make frequent calls (maybe one a second - the user will not notice this latency) which amounts to a lot of calls and some additional load on the server.
For approach 2, there is again choice:
Block the thread with an Object.wait() optionally storing the node ID, IP or other identifier in a shared data store: If so, the node receiving the Android app authorization needs to:
Either find the node that is currently blocking or broadcast to all nodes in the cluster
For each node in 1. above, send a message that identifies the user session to unblock. The message could be sent via:
Have an internal-only servlet on each node - this is called by the servlet performing the Android app authorization. The internal servlet will call Object.notify on the correct thread
Use a JMS pub-sub message queue to broadcast to all members of the cluster. Each node is a subscriber that, on receipt of a notification will call Object.notify() on the correct thread.
Poll a data store until the thread is authorized to continue: In this case, all the Android app needs to do is save the state in a SQL DB
Using wait/notify can be tricky. Remember that any thread can be suspended at any time. So it's possible for notify to be called before wait, in which case wait will then block for ever.
I wouldn't expect this in your case, as you have user interaction involved. But for the type of synchronisation you are doing, try using a Semaphore. Create a Semaphore with 0 (zero) quantity. The waiting thread calls acquire() and it will block until another thread calls release().
Using Semaphore in this way is much more robust that wait/notify for the task you described.
Consider using an in-memory grid so that the instances in the cluster can share state. We used Hazelcast to share data between instances so in case a response reaches a different instance it still can handle it.
E.g. you could use distributed countdown latch with value of 1 to set the thread waiting after sending the message, and when the response arrives from the client to a separate instance it can decrease, that instance can decrease the latch to 0 letting to run the first thread.
Your clustered deployment means that any node in the cluster could receive any response.
Using wait/notify using threads for a web app risks accumulating a lot of threads that may not be notified which could leak memory or create a lot of blocked threads. This could eventually affect the reliability of your server.
A more robust solution would be to send the request to the android app and store the current state of the users request for later processing and complete the HTTP request. To store the state you could consider:
A database that all tomcat nodes connect to
A java cache solution that will work across tomcat nodes like hazelcast
This state would be visible to all nodes in your tomcat cluster.
When the reply from the android app arrives on a different node, restore the state of what your thread was doing and continue processing on that node.
If the UI of the application is waiting on a response from the server, you might consider using an ajax request to poll for the response state from the server. The node processing the android app response does not need to be the same one handling UI requests.
Using Thread.wait in a web service environment is a colossal mistake. Instead, maintain a database of user/token pairs and expire them at intervals.
If you want a cluster, then use a database that is clusterable. I would recommend something like memcached since it's in-memory (and fast) and low on overhead (key/value pairs are dead simple, so you don't need RDBMS, etc.). memcached handles expiration of tokens for you already, so it seems like a perfect fit.
I think the username -> token -> password strategy is unnecessary, especially because you have two different components sharing the same 2-factor authentication responsibility. I think you can further reduce your complexity, reduce confusion for your users, and save yourself some money in SMS-send fees.
The interaction with your web service is simple:
User logs into your website using username + password
If primary authentication (username/password) is successful, generate a token and insert userid=token into memcached
Send the token to the user's phone
Present "enter token" page to the user
User receives token via phone and enters it into the form
Fetch the token value from memcached based upon the user's id. If it matches, expire the token in memcached and consider the second-factor successful
Tokens will auto-expire after whatever amount of time you want to set in memcached
There are no threading problems with the above solution and it will scale across as many JVMs as you need to support your own software.
After analysing your question, I came to the conclusion that the exact problem is of multiple JVMs in a clustered environment.
The exact problem is because of the cluster environment. Both requests are not going to the same JVM. But we know that a normal/simple notify works on the same JVM when the previous thread is waiting.
You should try to execute both requests (first request, second request when the user replies from an Android application).
I'm afraid, but threads cannot migrate over classic Java EE clusters.
You have to rethink your architecture to implement the wait/notify differently (connection-less).
Or, you may give it a try with terracotta.org. It looks like this allows to cluster an entire JVM process over multiple machines. Maybe it's your only solution.
Read a quick introduction in Introduction to OpenTerracotta.
I guess the problem is, your first thread sends a notification to the user's Android application in JVM 1 and when the user reply back, the control goes to JVM 2. And that's the main problem.
Somehow, both threads can access the same JVM to apply wait and notify logic.
Solution:
Create a single point of contact for all waiting threads. Hence in a clustered environment, all the threads will wait on a third JVM (single point of contact), so in this way all the requests (any clustered Tomcat) will contact the same JVM for waiting and notify logic and hence no thread will wait for an unlimited time. If there is a reply, then the thread will be notified if the same object has waited and is being notified the second time.
I want to send stored RMS data using an HTTP connection when the application is in idle mode.
So if the user is not doing anything with the application at that time, my thread will invoke and send RMS data to server.
For this requirement, how do I how find out if the application in active mode or idle mode?
You could wait for the backlight to go off, if that's enough of an indication of whether the application is active.
Implement the SystemListener2 interface, there's a method backlightStateChange() that will be invoked after the object is registered with Application.addSystemListener
I do not see any smarter solution than using Displayable.setCommandListener(CommandListener l).
The command listener should use Timer. When a certain timeout (let's say 60 seconds) is expired, the timer task should run and trigger sending your data. I think that if you have access to the midlet's code, this solution is not so bad.