I want to run the events of firebase on different thread. On the last version of firebase I had this code that did it
Config firebaseConfig = new Config();
firebaseConfig.setEventTarget(new EventTarget() {
ExecutorService executor = Executors.newSingleThreadExecutor();
#Override
public void postEvent(Runnable runnable) {
executor.execute(runnable);
}
#Override
public void shutdown() {
executor.shutdown();
}
#Override
public void restart() {
}
});
Firebase.setDefaultConfig(firebaseConfig);
How can I do it in the new api? Their is a way or I have to implement it by my self? (create runnable of every function and run it in the executor)
The Firebase Database client performs all networking, disk I/O and other maintenance on a separate thread. It then surfaces the callbacks to your code on the main thread, so that you can interact with the UI.
In most situations you don't have to do anything special and can just let the Firebase client deal with the cross-threading handling. Only when you need to do some heavy work in your callback (e.g. onDataChange()) will you have to run that work off the main thread again. You can use the usual Android threading mechanisms for that.
Related
I have an OSGI bundle of a following structure:
//...
public ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
//...
#Activate
public void activate() {
executor.submit(new Runnable() {
#Override
public void run() {
//call 3 functions and log the data
}
}
}
#Deactivate
public void deactivate(){
//call 2 other functions
}
The executor in the activate method makes sure that 3 functions are called in a separate from all other bundles thread, because those functions actually implement some sophisticated Windows-message-loop, i.e. a while true loop, that's why, in order not to block other bundles, it is activated in a separate thread. Now what I've sadly noticed, that in order to run 2 functions in deactivate method I need to run them in the same thread, in which 3 functions in activate method were run. Simply speaking, I need to be sure, that activate and deactivate methods of my bundle run in the one same thread, but still to keep this bundle activation separated (in an own thread) from the other bundles.
My question is: how to implement this?
I am not a guru in concurrency in Java, I've tried simply to call this executor in the deactivate method too but I don't know how to do it with one Runnable task, since in deactivate I have only to call 2 functions and in activate only 3 functions and no other calls should be made.
UPD: sorry, I forgot to mention, that there is a routine in another bundle, which calls in certain situations context.getBundle(0).stop() in order to call a deactivation for all bundles. If I want just to add the same submit routine in the deactivate method as is in activate, then in such situation I could clearly see, that those 2 functions from deactivate method of my bundle in the submit's body were not called.
Simply do another executor.submit in deactivate. As it is a single threaded executor it will make sure only one thread processes both.
The only question is how to shut down the executor reliably. Normally after deactivate a component should have closed all its resources.
This sounds like a very common problem. I would just make it explicit you're using a thread and use the methods in Thread that were designed for this. At activate you start the thread, at deactivate you interrupt it. Your main loop watches the interrupt status and executes your deactivate functions after it is interrupted. After interrupt, it is best to join the thread to ensure your activate() method does not return before the background thread has finished running your deactivate functions.
Since exiting the framework (stopping bundle 0) must stop all bundles, and a stopped bundle will deactivate its components, this should all work.
public class Foo extends Thread {
#Activate void activate() { start(); }
#Deactivate void deactivate() throws Exception { interrupt(); join(); }
public void run() {
while(!isInterrupted()) try {
... your 3 function loop
} catch( InterruptedException e) {
break;
}
... 2 deactivate functions
}
}
if we look inside DefaultThreadFactory of Jgroups the following code is present
protected Thread newThread(Runnable r,String name,String addr,String cluster_name) {
String thread_name=getNewThreadName(name, addr, cluster_name);
Thread retval=new Thread(r, thread_name);
retval.setDaemon(createDaemons);
return retval;
}
As new thread is used so I believe in a managed server environment this can cause issues and is also not a good practice.
If I just replace the default thread factories and executors with Managed factories and executors of WebSphere will the behavior of Jgroups be still the same ?
Any pointers will be helpful ..?
Update
My intention is to use JGroups with WebSphere AS 8.5. I am keen to not have any un-managed threads. My main use case is for leader election and some message passing. It will be used to manage Spring Integration pollers and ensure only one poller is running within the cluster.
WAS 8.5 still uses the CommonJ api for Work management.
I am using Spring to abstract the Task Executors and Schedulers.
It was initially easy enough to replace the ThreadPools with task executors as they share the Executor api.
The TaskScheduler had to be adapted to work with your TimeScheduler interface.
They are very similar and perhaps extending from the ScheduledExecutorService could be an option here. I implemented to your interface and delegated to Springs TaskScheduler.
The main issue is with the ThreadFactory. CommonJ does not have this concept. For this I created a ThreadWrapper that encapsulates the Runnable and delegates out to a TaskExecutor when the "Thread's" start method is called. I ignored the thread renaming functionality as this will not have any effect.
public Thread newThread(Runnable command) {
log.debug("newThread");
RunnableWrapper wrappedCommand = new RunnableWrapper(command);
return new ThreadWrapper(taskExecutor, wrappedCommand);
}
public synchronized void start() {
try {
taskExecutor.execute(runnableWrapper);
} catch (Exception e) {
throw new UnableToStartException(e);
}
}
This is where I ran into problems. The issues were in the transports. In a number of cases with in the run method of some of the internal runnables e.g. the DiagnosticsHandler, the TransferQueueBundler of TP and ViewHandler of GMS there is a while statements that checks the thread.
public class DiagnosticsHandler implements Runnable {
public void run() {
byte[] buf;
DatagramPacket packet;
while(Thread.currentThread().equals(thread)) {
//...
}
}
}
protected class TransferQueueBundler extends BaseBundler implements Runnable {
public void run() {
while(Thread.currentThread() == bundler_thread) {
//...
}
}
}
class ViewHandler implements Runnable {
public void run() {
long start_time, wait_time; // ns
long timeout=TimeUnit.NANOSECONDS.convert(max_bundling_time, TimeUnit.MILLISECONDS);
List<Request> requests=new LinkedList<>();
while(Thread.currentThread().equals(thread) && !suspended) {
//...
}
}
}
This does not co-operate with our thread wrapping. If this could be altered so that the equals method is called on the stored thread it would be possible to override it.
As you can see from the various snippets there are various implementations and levels of protections varying from package, protected and public. This is increased the difficulty of extending the classes.
With all of this done it still did not remove completely the issue of unmanaged threads.
I was using the properties file method of creating the protocol stack. This initialises the protocol stack once the properties are set. To remove the Timer threads that are created by the bottom protocol. The TimeScheduler must be set prior the to stack being initialised.
Once this is done the threads are all managed.
Do you have any suggestions on how this could have been achieved more easily?
Yes, you can inject your on thread pools, see [1] for details.
[1] http://www.jgroups.org/manual/index.html#_replacing_the_default_and_oob_thread_pools
I want to use dependency injection for my Swing UI components in a Spring-Boot application and having a hard time figuring out, how to properly execute the UI behavior on the Event Dispatch Thread.
What I came up with first was like this:
App
#SpringBootApplication
public class App {
private static AppView view;
#Bean
public AppView appView() {
return view;
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(() -> view = new AppView());
SpringApplication app = new SpringApplication(App.class);
app.run(args);
}
}
AppView
public class AppView extends JFrame {
...
#Inject
private DependencyWithTimeConsumingOperations backendController;
#Inject
private JPanel someChildComponent;
#PostConstruct
public void init() {
constructView(); // inits frame properties and child components
showView();
}
private void showView() {
SwingUtilities.invokeLater(() -> {
pack();
setVisible(true);
});
}
...
}
The backend dependency gets called when certain UI events occur. What I observe is, that the backend calls get excuted on the EDT instead of the main application thread, which is bad, I assume. As I understand, not having much experience with Swing, is, that only UI updates should be executed on the EDT.
Is there a better way to wire my dependencies so that everything is executed in its proper thread? What I could find out so far seems a bit outdated or I plainly did not understand the answers :-)
Not sure if it is still relevant to you after so long :), but since it may help others, I'll try to answer.
Spring is only injecting the objects, it is not managing the threads. The behaviour would be the same if you'd instantiated and set the backendController manually, meaning that the EDT (or any thread that is calling the operation) would be the one to execute the code on the controller.
If you explicitly want to run in a different thread, we'd need to know more about the methods in the controller. Are they methods that you want to call and not wait for a reply (fire and forget)? Or maybe you need the reply but can run more than one at the same time? In these scenarios you can take advantage of the Executors class and do something like:
Executors.newSingleThreadExecutor().execute(() -> backendController.timeConsumingOperation1()); // Fire and forget. The operation timeConsumingOperation1 will be executed by a separate thread and the EDT will continue to the next line (won't freeze your GUI)
If you need a result, you may submit it to the pool and poll for the result (maybe with a "refresh" button on the screen). Keep in mind that as soon as you call "get()" the current thread will wait for the pooled thread to finish before proceeding to the next line.
Future result = Executors.newSingleThreadExecutor().execute(() -> backendController.timeConsumingOperation2);
result.isDone(); // You can add a "refresh" button or a scheduled task to check the state...
doSomething(result.get()); // This will hold the current thread until there is a response from the thread running the timeConsumingOperation
Or maybe you do want to freeze the GUI until you have a response from all methods called in the controller, but they can be safely called in parallel:
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Future<Object>> results = executorService.invokeAll(
Arrays.asList(() -> backendController.timeConsumingOp3(), () -> backendController.timeConsumingOp4));
results.forEach(e -> doSomething(e.get())); // The tasks will be executed in parallel and "doSomething()" will be called as soon as the result for the given index is available
executorService.shutdown(); // Always shutdown
Of course this is just an example, but in large Swing applications it is good practice to create pools of threads (shared by the controllers) to which we submit our long running tasks. You can configure the pool size based on the number of cores (Runtime.getRuntime().availableProcessors()) to best use the resources available on the machine (the tasks submitted will be queued up with no restriction, but only X threads will execute the tasks in parallel, where X is the pool size).
Just use code
SpringApplicationBuilder(Main.class).headless(false).run(args);
I am working on a webserver written in Java. The web server is handling websocket communication with the clients and therefore we have a class called ClientHandler that has a socket and id as instance variables. The ClientHandler will need to have a function that will listen for messages from the clients. This function needs to work in paralell to the rest of the server, and since the "reading of messages" is a thread blocking function, we need a separate thread for this.
Here's the two alternative ways of implementing this:
public class ClientHandler implements Runnable{
//Instance variable
public Thread listener = new Thread(this);
.
.
.
public void run() {
while (!Thread.interrupted()){
//Listening code here
}
}
}
And then start the listener thread by writing
clientHandler.listener.start();
And stop it by writing
clientHandler.listener.interrupt();
Or this method:
public class ClientHandler {
//Instance variable
private Thread listenerTread;
private boolean alive; //set to true in constructor
.
.
.
public void listenToClient() {
listenerTread = new Thread(new Runnable() {
#Override
public void run(){
while (!alive){
//Listening code here
}
}
});
}
}
and then start the thread by calling the function listenToClient()
clientHandler.listenToClient();
and stop it by switching alive = false.
I have tried to find someone explaining the best solution, but most comparisons are between implementing Runnable or extending Thread. Is the any downsides to using either of the methods above? What method is best if I want to have multiple threads in one class?
I'm not sure you want to explicitly create a Thread instance. Why don't you try using a ThreadPoolExecutor to which you submit the tasks for execution. Read here more about thread pool. http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html
Since you can have many clients, using a thread pool may improve the performance of your application.
You have two tasks. One is to listen for new connections and initiate serving of that connections. Second is to actually serve a connection. The decision to serve each connection within a separate thread is an implementation detail of the second task. In principle, it can be served in other ways, with a thread pool or with async IO. So this implementation detail should be hidden inside the code of the second task and must not be visible to the code of the first task. So use the second way.
I'm trying to get a TimerTask set up to remove entries from Google App Engine's dataStore periodically. So I set up a ServletContextListener with a Timer.
Inside the contextInitialized, I have registered my Objectify classes:
ObjectifyService.register(Person.class);
However, when the task actually runs, it complains that no API environment has been set up:
Exception in thread "Timer-0" java.lang.NullPointerException: No API environment is registered for this thread.
at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppId(DatastoreApiHelper.java:80)
at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppIdNamespace(DatastoreApiHelper.java:90)
at com.google.appengine.api.datastore.Query.<init>(Query.java:214)
at com.google.appengine.api.datastore.Query.<init>(Query.java:143)
at com.googlecode.objectify.impl.cmd.QueryImpl.<init>(QueryImpl.java:72)
at com.googlecode.objectify.impl.cmd.LoadTypeImpl.createQuery(LoadTypeImpl.java:50)
at com.googlecode.objectify.impl.cmd.LoadTypeImpl.filter(LoadTypeImpl.java:58)
at myApp.MyServletContextListener$MyTask.run(MyServletContextListener.java:58)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Any ideas? I've tried changing the line that registers the class to ObjectifyService.factory().register(Person.class); but it didn't seem to help.
From the documentation of java.util.Timer class:
Corresponding to each Timer object is a single background thread.
And peeking to the inner code of the java.util.Timer class, we can see that it basically instantiates the thread by invoking new Thread().
Meanwhile, from App Engine's documentation about the use of threads in their Java sandbox:
You must use one of the methods on ThreadManager to create your threads. You cannot invoke new Thread() yourself or use the default thread factory.
So what happened here is the Timer object instantiated their own thread, which then executes the Objectify queries, but since threads instantiated outside ThreadManager does not have the proper App Engine API environment set up for them, it throws an exception.
You need to refactor your code to avoid using the Timer and TimerTask classes and use basic threads instead. For example, instead of using:
import java.util.Timer;
import java.util.TimerTask;
...
Timer timer = new Timer();
timer.schedule( new TimerTask()
{
#Override
public void run()
{
// Objectify query here.
}
}, 5000 );
You could instead use:
import com.google.appengine.api.ThreadManager;
...
final long tScheduleDelay = 5000;
ThreadManager.createThreadForCurrentRequest( new Runnable()
{
#Override
public void run()
{
try
{
Thread.sleep( tScheduleDelay );
}
catch ( InterruptedException ex )
{
// log possible exception
}
// Objectify query here.
}
} ).start();