Assume I have a class written as below
public MyClass{
public void method2(){
}
public void method1(){
}
}
but I would like to see method1() appearing first and method2() appearing second.
Is there anyway to do that with intellij without manually copy pasting? I cant find any tool inside method summary window.
If you only want to move the method up/down you can simply select it and usectrl + shift + (up/down) in order to move it as wished.
Related
I am experiencing some sort of thread issue with the #Async method annotation where one argument contains a List of enum and is dropping items. The list is very small, 2 items. The dropping of items is not immediate, but sometimes takes hours or days to appear.
This is the general flow of our program:
A Controller generates the said List in its #RequestMapping method, passes the list to a Service class, which makes a call to a database for batching and triggers an event for each item from the database, passing the list. This list eventually gets passed into an #Async method which then drops either the first item or both items.
Controller.methodA()
-> Creates list with two items in it
-> Calls void Service.methodX(list)
-> Load batch from database
-> Iterate over batch
-> Print items from list --- list in tact
-> Calls void AsyncService.asyncMethod(list)
-> Print items from list --- eventually drops items here always the first item, sometimes both.
Code configuration and bare-bones sample:
We configured it to have 2 threads:
#Configuration
#EnableAsync
public class AsyncConfig implements AsyncConfigurer {
#Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setMaxPoolSize(5); // Never actually creates 5 threads
threadPoolTaskExecutor.setCorePoolSize(2); // Only 2 threads are ever created
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
This is a local replica to try to trigger the core issue, but no luck:
#RestController
public class ThreadingController {
private final ThreadingService threadingService;
public ThreadingController(ThreadingService threadingService) {
this.threadingService = threadingService;
}
#GetMapping("/test")
public void testThreads() {
List<SomeEnum> list = new ArrayList<>();
list.add(SomeEnum.FIRST_ENUM);
list.add(SomeEnum.SECOND_ENUM);
for (int i = 0; i < 1000; i++) {
this.threadingService.workSomeThreads(i, list);
}
}
}
public enum SomeEnum {
FIRST_ENUM("FIRST_ENUM"),
SECOND_ENUM("SECOND_ENUM");
#Getter
private String name;
SomeEnum(String name) {
this.name = name;
}
}
#Slf4j
#Service
public class ThreadingService {
#Async
public void workSomeThreads(int i, List<SomeEnum> list) {
try {
Thread.sleep(100L); // Add some delay to slow things down to trigger GC or other tests during processing
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("Count {} ; Here are the list items: {}", i, list.toString());
assert(list.size() == 2);
}
}
If we look through this, I have one controller simulating both the Controller and Service mentioned earlier. It spins through a batch of data, sending the same list over and over. There's an aync method in another class to test that the list is the same. I was not able to replicate the issue locally, but this is the core problem.
To my knowledge, Java is pass-by-reference and every variable passed into a method gets its own pointer in the stack to that reference in memory, but don't think it would cause us to run out of memory. We are running in PCF and don't see any memory spikes or anything during this time. Memory is constant around 50%. I also tried using a CopyOnWriteArrayList (thread safe) instead of ArrayList and still the problem exists.
Questions:
Any idea why the #Async method would drop items in the method argument? The list is never modified after construction, so why would items disappear? Why would the first item always disappear? Why not the second item? Why would both disappear?
Edit: So this question had little to do with #Async in the end. I found deeply nested code that removed items from the list, causing items to go missing.
What you said is correct, Java is indeed pass-by-reference. The change in your list must be definitely due to some other code that is modifying this list while the threads are executing. There is no other way the object would change its values.
You must investigate the code in the below section to identify if there is something that is modifying the list.
-> Print items from list --- eventually drops items here always the first item, sometimes both.
-> code following this might be changing the list.
As the AsyncService would execute its code asynchronously and in the mean time, some other code modifies the list.
You may as well make the method params to be final.
I understood what #Around Advice does, and when we need to share Before and after state then we can use it, and we call also skip method execution. My question is why Spring given us this power to skip method execution and what is the use case of skipping method?
Side effects as NĂ¡ndor said are one thing. Maybe you even want to replace the return value altogether, possibly because there is a bug in a class you do not have the source code of or for other reasons:
Buggy Java class:
package de.scrum_master.app;
public class Earth {
public String getShape() {
return "disc";
}
}
Driver application:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
System.out.println("The Earth is a " + new Earth().getShape() + ".");
}
}
Console log:
The Earth is a disc.
Bugfix aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Earth;
public aspect BugfixAspect {
String around() : execution(* Earth.getShape()) {
return "sphere";
}
}
Console log with aspect applied:
The Earth is a sphere.
Method calls usually have side effects. Whenever you decide in your aspect that those side effects are undesirable for whatever reason, it's a valid use case to skip executing the original execution. This includes use cases for caching for example, when the side effects are not in terms of data, but execution time.
Thanks to the help I got with my other problems on this forum, I managed to advance my project, but yet another obstacle appears in my way.
I am having trouble implementing multiple Screens in libgdx for java. I would like to know how can I implement multiple screens (one for the main menu, one for play, one for loading screen, ...).
An example or some explanations of how should I structure my screen classes would be really helpful. I tried implementing my own screen manager but that didn't go very well... Also some pointers on how should I dispose screens, since creating screens every time you go from main menu to play or to options menu isn't a very good idea. Any ideas or code example or advice is much appreciated.
What I have now are some classes of game screens which when you render them they will draw some GUI on the screen, but functions like the back button don't work since I don't know how to make the link between them.
Let's say you got 3 screens, MainMenuScreen, OptionsScreen, GameScreen.
First you need to declare them in your main class.
It will look like this
public class MainClass extends Game implements ApplicationListener {
private GameScreen gameScreen;
private MenuScreen menuScreen;
private OptionsScreen optionsScreen;
#Override
public void create() {
}
setGameScreen()
{
gameScreen=new GameScreen(this);
setScreen(gameScreen);
}
setMenuScreen()
{
menuScreen=new menuScreen(this);
setScreen(menuScreen);
}
setOptionsScreen()
{
optionsScreen=new OptionsScreen(this);
setScreen(gameScreen);
}
#Override
public void dispose() {
super.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
super.render();
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
}
Now every screen you got, needs to have a MainClass variable and a constructor of it.
Lets say for the GameScreen class, it will be like
public class GameScreen implements Screen{
private MainClass mainClass;
public GameScreen(MainClass mc)
{
mainClass=mc;
}
// your methods (show,render, pause, etc)
}
Now when you want to change the screen just use in your screen
mainClass.setMenuScreen();
I'm trying prevent the close of my application, but looking at JavaFX docs (and after some implementations) I noticed that setOnCloseRequest() is efficient only when the user try to close the window using close button or ALT+F4 shortcut. As I need intercept internal tries of close, I'm using setOnHiding(), this way I can catch all tries of close the main dialog of the application, however I still can't prevent the closing:
public abstract class AppBase extends Application {
public void init(){
dialogoPrincipal.getPainel().getScene().getWindow().setOnHiding(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
event.consume();
}
});
}
}
Is there something I'm doing wrong? Is there another approach to solve this problem?
CloseRequest events are fired by the GUI user and Hide events are called programmatically. So you can control the flow of code for hide event calls. Implement some wrapper util class like StageUtil.hideRequest(stage) or extend your own as stage.myHide() etc. The hiding event seems cannot be consumed and I think it is a right decision by design. The purpose of hiding and hidden events are described in their javadocs and there is no mention about consuming of them.
Try implementing a window event handler on your controller:
public class XYZ implements EventHandler<WindowEvent>
{
#Override
public void handle( WindowEvent closeEvent )
{
closeEvent.consume();
}
}
Or try implementing it on your AppBase class.
So I've been practising with JavaFX for a while now and while I love it, I find that my application is growing in size- especially in terms of the number of lines of codes for my FXML Controllers.
Right now a typical package for each scene in my application looks like this:
MyFXML.fxml
MyFXMLController.java
MyDataModel.java
For example, I have a form that takes in some information from textfields, comboboxes and radio buttons. When a button is pressed the form information is saved to a database and is also updated immediately in the tableview.
The tableview also allows deleting and updating of the information displayed.
With only a few components (approx. 10) I have a Controller class file that is about 550 lines long with about a 100 of it taken up by the injections (#FXML) and imports and growing!
My application would ideally have multiple of these different kinds of forms and a controller for each. The database queries are all different so it's not quote possible to abstract them out yet. Also, event listeners for the tableview generally require longer code in javafx than other components.
I just feel like there's a better approach to GUI building in javafx than what I'm doing and was wondering if there was some kind of reference I could look up?
I've read up on other stackoverflow answers on the Single Responsibility Principle. If the code below is any hint, my application simply creates a new staff member and allows updating the information. So I'm confused as to whether my class is too file or is this normal for GUI programming?
I'm not asking for coding help, I'm looking for recommendations on how I can improve GUI programming in javafx.
Thank you!
--
FWIW, here's what a sample controller file looks like
package myApp.staff;
//30 something lines of imports...
public class NewStaffMemberController implements Initializable {
//80 something lines of private variables and #FXML injections
public void setConn(Connection aConn) {
conn = aConn;
wrapGenderRadioButtons();
populateDates();
populateStaffTypeComboBox();
populateDepartmentComboBox();
populateStaffTable();
}
private void wrapGenderRadioButtons() {
//4 lines
}
private void populateDates() {
//25 lines
}
private void populateStaffTypeComboBox() {
//20 lines
}
private void populateDepartmentComboBox() {
//22 lines
}
private void populateStaffTable(){
//longest at 100 lines. This code also adds the event listener for the tableview- makes it quite long!
}
private void editSelectedTableRow(Staff selectedstaff){
//4 lines
}
#FXML
private void selectedRadioBtnAction() {
//1 lines
}
#FXML
private void handleYearComboBoxAction() {
//1 lines
}
#FXML
private void handleMonthComboBoxAction() {
//1 lines
}
#FXML
private void handleDayComboBoxAction() {
//1 lines
}
#FXML
private void staffTypeComboBoxAction() {
//1 lines
}
#FXML
private void departmentComboBoxAction() {
//1 lines
}
#FXML
private void btnGenerateStaffId() {
//36 lines
}
#FXML
private void btnSaveInformation(){
13 lines
}
private Boolean validateData() {
//43 lines
}
private void assignStaffId() {
//12 lines
}
private void insertIntoDatabase() {
//35 lines
}
private void updateDatabase(){
//35 lines
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
}
Well, I think you don't have choice to inject your fxml fields you need. But maybe if you have number of injections like that just in one controller, you should maybe do a better conception of your app, by doing sub controllers working each other together and don't have everything in just one controller. One view doesn't mean one controller. You can have one view and multiple controller with there own view