Spring-Boot with Swing UI - java

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);

Related

Liferay 7.1 - Kill a thread execution from scheduler jobs

I have my following job in Liferay 7.1 :
#Component(
immediate = true, property = {"cron.expression=0 5 10 * * ? *"},
service = CustomJob.class
)
public class CustomJob extends BaseMessageListener {
....
#Override
protected void doReceive(Message message) throws Exception {
// HERE I CALL A SERVICE FUNCTION TO INACTIVATE USER, SEND MAILS, READ FILES TO IMPORT DATA
RunnableService rs = new RunnableService();
rs.run();
}
....
}
And my RunnableService :
public class RunnableService implements Runnable {
#Override
public synchronized void run() {
// DO MY STUFF
}
}
The job is working great, but another instance of the job can be started even when the service execution from the first call hasn't finished.
Is there any solutions to kill the first process ?
Thanks,
Sounds like there are several options, depending on what you want to achieve with this:
You shouldn't interrupt threads with technical measures. Rather have your long-running task check frequently if it should still be running, otherwise terminate gracefully - with the potential of cleaning up after itself
You can implement your functionality with Liferay's MessageBus - without the need to start a thread (which isn't good behavior in a webapp anyway). The beauty of this is that even in a cluster you end up with only one concurrent execution.
You can implement your functionality outside of the Liferay process and just interact with Liferay's API in order to do anything that needs to have an impact on Liferay. The beauty of this approach is that both can be separated to different machines - e.g. scale.

How to execute activate and deactivate methods of OSGI bundle in a single thread

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
}
}

How do I interrupt Java code that doesnt finish and doesnt throw ThreadInterruptionException

A load of tasks are submitted to my application but it keeps hanging and I track it down to this code:
uk.ac.shef.wit.simmetrics.tokenisers.TokeniserWhitespace.tokenizeToArrayList(TokeniserWhitespace.java:133)
uk.ac.shef.wit.simmetrics.similaritymetrics.CosineSimilarity.getSimilarity(CosineSimilarity.java:142)
com.jthink.songkong.match.Scorer.compareValues(Scorer.java:74)
com.jthink.songkong.match.Scorer.calculateTitle(Scorer.java:704)
com.jthink.songkong.match.Scorer.matchRecordingOrTrackTitle(Scorer.java:652)
com.jthink.songkong.match.Scorer.calculateTrackScoreWithinRelease(Scorer.java:538)
com.jthink.songkong.match.Scorer.scoreMatrix(Scorer.java:396)
com.jthink.songkong.match.Scorer.calculateReleaseScore(Scorer.java:1234)
It is basically an string matching algorithm in a 3rd party library but it does not throw ThreadInterruptedException so does this mean I cannot interrupt it, but is certainly a long running process having run for 30 minutes. I have a reference to the thread monitoring this code but is there any way to stop it.
Of course I am looking to fix the 3rd party library but in the meantime I need a way to stop my application hanging by cancelling these hanging tasks. What makes it worse for me is that I use Hibernate, and a hibernate session is created in this stack and then because this TokeniserWhitespace method never finishes my session (and hence database connection) is never released therefore eventually I ran out of database connections and the application completely hangs.
I would try Thread.interrupt() as even though the interrupted exception isn't thrown it doesn't necessarily mean that the 3rd party library doesn't handle it correctly in some other way. If that doesn't work then I would consider Thread.stop() even though it is depricated in the hopes that the library's design can handle sudden termination and doesn't end up in an inconsistent state (due to the transactional nature in which you are using it, I doubt there are many shared objects to get corrupted). Thread.stop() will cause the event to stop immediately and throw a ThreadDeath exception no matter what it is doing and it was deprecated by Sun due to the chance of leaving shared objects in an unknown and inconsistent state.
You can can use the Akka library to wrap the problematic code - this will let you kill and restart the code if it hangs.
import scala.concurrent.Future;
public interface ProblemCode {
public Future<String> stringMatch(String string);
}
public class ProblemCodeImpl implements ProblemCode {
public Future<String> stringMatch(String string) {
// implementation
}
}
import akka.actor.ActorSystem;
import akka.actor.TypedActor;
import scala.concurrent.Await;
import scala.concurrent.duration.Duration;
import akka.actor.TypedProps;
public class Controller {
private final ActorSystem system = ActorSystem.create("Name");
private ProblemCode problemCodeActor = getProblemCodeActor();
private ProblemCode getProblemCodeActor() {
return TypedActor.get(system).typedActorOf(new TypedProps<ProblemCodeImpl>(ProblemCode.class, ProblemCodeImpl.class));
}
public String controllerStringMatch(String string) {
while(true) {
try {
// wait for a Future to return a String
return Await.result(problemCodeActor.stringMatch(string), Duration.create(5000, TimeUnit.MILLISECONDS));
} catch (TimeoutException e) {
// Await timed out, so stop the actor and create a new one
TypedActor.get(system).stop(problemCodeActor);
problemCodeActor = getProblemCodeActor();
}
}
}
}
In other words, the controller calls stringMatch on the problem code that has been wrapped in an actor; if this times out (5000 milliseconds in my example) you stop and restart the actor and loop through the controller method again.
ProblemCode will only execute one method at a time (it will enqueue subsequent invocations), so if you want to concurrently execute stringMatch you'll need to create multiple actors and create a router out of them / place them in a queue / etc.

Is there a way to pause a unit test without blocking the thread

I'm using play 1.2.4 and I'm trying to set up a unit test to test a job.
My job runs at every 2 second and changes the status of certain objects based on some conditions. This is what I use to do this.
#Every("2s")
public class GameScheduler extends Job {
public void doJob(){
//Fetch of object from db and status change based on conditions happens here
}
}
Now in my unit test, I setup those conditions but I want the test to wait say 3 seconds before fetching one of the setup objects and do an assert Equals on its status to see if the job... well did it's job.
If I use
pause(3000);
or something like
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
The test stops but the job also stops. It seems like the job and the test are on the same thread. Is there a way to pause the test without stopping the job? Something like the await() method in the controller
You don't need to test the scheduler because it is supposed to work (since the framework is handling it). What you need is just test if the doJob method is doing its work. So, just write a test like this:
GameScheduler job = new GameScheduler();
job.doJob();
// assert whatever you want here
Though simply testing the job (without waiting for the scheduler to run it for you) would do the trick in most (read this as: probably all) situations, there are some in which it might be interesting to not have to trigger it manually.
For instance, you have a cluster of play apps that share a common configuration set. Change one config in one slave, all the others take note and do the same. Let's say the configuration is kept in memcached. One useful unit test is to manually change some setting using Cache.set, wait for the amount of time it takes for the configurationObserver job to run, then check that the internal config has been updated. This would be even more helpful if there would be a series of jobs updating the configuration, etc.
To do that, you must remember that play in DEV mode uses one thread (this helps debugging a lot, btw). You can simply add this line to your application.conf: %test.application.mode=prod and you'll have multiple threads.
Later edit: It appears that setting the mode to prod doesn't really help in this case. What does help is this: use some "await" magic.
#Test
public void myTest() {
final Lock lock = new ReentrantLock();
final Condition goAhead = lock.newCondition();
/* Here goes everything you need to do before "pausing" */
lock.lock();
try {
/**
* Set whatever time limit you want/need
* You can also use notifiers like goAhead.signal(), from within another thread
*/
goAhead.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
assertTrue(whateverINeedToTest);
} finally {
lock.unlock();
}
}

How do I write a JUnit test case to test threads and events

I have a java code which works in one (main) thread. From the main thread, i spawn a new thread in which I make a server call. After the server call is done, I am doing some work in the new thread and after that the code joins the main thread.
I am using eclipse Jobs to do the server call.
I want to know, how do I write a JUnit test case for this.
You may need to restructure your code so that it can be easily tested.
I can see several distinct areas for testing:
Thread Management code: the code that launches the thread(s) and perhaps waits for results
The "worker" code run in the thread
The concurrency issues that may result when multiple threads are active
Structure your implementation so that Your Thread Management code is agnostic as to the details of the Worker. Then you can use Mock Workers to enable testing of Thread Management - for example a Mock Worker that fails in certain ways allows you to test certain paths in the management code.
Implement the Worker code so that it can be run in isolation. You can then unit test this independently, using mocks for the server.
For concurrency testing the links provided by Abhijeet Kashnia will help.
This is what I created ConcurrentUnit for. The general usage is:
Spawn some threads
Have the main thread wait or sleep
Perform assertions from within the worker threads (which via ConcurrentUnit, are reported back to the main thread)
Resume the main thread from one of the worker threads once all assertions are complete
See the ConcurrentUnit page for more info.
I'm guessing that you may have done your mocking code and may want a simple integration test to ensure that that your server call works.
One of the difficulties in testing threads comes from their very nature - they're concurrent. This means that you're force into writing JUnit test code that is forced to wait until your thread has finished its job before testing your code's results. This isn't a very good way of testing code, and can be unreliable, but usually means that you have some idea about whether you code is working.
As an example, your code may look something like:
#Test
public void myIntegrationTest() throws Exception {
// Setup your test
// call your threading code
Results result = myServerClient.doThreadedCode();
// Wait for your code to complete
sleep(5);
// Test the results
assertEquals("some value",result.getSomeValue());
}
private void sleep(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I really don't like doing this and prefer mocks and agree with the other answers. But, if you need to test your threads, then this is one approach that I find works.
When your only problem is waiting for the result, use ExecutorService for spawning your threads. It can accept work jobs both as Runnable and Callable. When you use the latter, then you are given a Future object in return, that can be used to wait for the result. You should consider using ExecutorService anyway, as from what I understand, you create many threads, and this is a perfect use case for executor services.
class AnyClass {
private ExecutorService threadPool = Executors.newFixedThreadPool(5);
public List<Future<Integer>> anyMethod() {
List<Future> futures = new ArrayList<>();
futures.add(threadPool.submit(() -> {
// Do your job here
return anyStatusCode;
}));
futures.add(threadPool.submit(() -> {
// Do your other job here
return anyStatusCode;
}));
return futures;
}
}
And the test class:
class TestAnyClass {
#Test
public void testAnyMethod() {
AnyClass anyObject = new AnyClass();
List<Future<Integer>> futures = anyObject.anyMethod();
CompletableFuture[] completable = futures.toArray(new CompletableFuture[futures.size()]);
// Wait for all
CompletableFuture.allOf(completable).join();
}
}
I suggest you use a mocking framework, to confirm that the server call was indeed made. As for the thread unit testing: Unit testing multithreaded applications
The resources provided by Abhijeet Kashnia may help, but I am not sure what you are trying to achieve.
You can do unit testing with mocks to verify your code, that won't test concurrency but will provide coverage.
You can write an integration test to verify that the threads are being created and joined in the fashion you expect.However this will not guarantee against concurrency problems. Most concurrent problems are caused by timing bugs which are not predictable and thus can't be tested for accurately.
Here is my solution to test asynchrone method which used thread.start:
public class MyClass {
public void doSomthingAsynchrone() {
new Thread(() -> {
doSomthing();
}).start();
}
private void doSomthing() {
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClass.class)
public class MyClassTest {
ArgumentCaptor<Runnable> runnables = ArgumentCaptor.forClass(Runnable.class);
#InjectMocks
private MyClass myClass;
#Test
public void shouldDoSomthingAsynchrone() throws Exception {
// create a mock for Thread.class
Thread mock = Mockito.mock(Thread.class);
// mock the 'new Thread', return the mock and capture the given runnable
whenNew(Thread.class).withParameterTypes(Runnable.class)
.withArguments(runnables.capture()).thenReturn(mock);
myClass.doSomthingAsynchrone();
runnables.getValue().run();
/**
* instead of 'runnables.getValue().run();' you can use a real thread.start
*
* MockRepository.remove(Thread.class);
* Thread thread = new Thread(runnables.getValue());
* thread.start();
* thread.join();
**/
verify(myClass, times(1)).doSomthing();
}
}

Categories