I have a task of returning US holiday based on the given date and this utility will be used in a multi thread environment. I have written as below, how to know if my code breaks at any given point by multiple threads
I tried to test this with few concurrent threads, and noticed that the DB call is made for the very first time or when the year being requested is not same as the cached year. But I wanted to see, if this is properly synchronizing and would not fail in any case. My intention is to make a singleton HolidayCalendar, and also synchronized well enough so that every thread using this class gets the required data without blocking each other.
I' currently wrking on BeatBox application from Head First Java. I made a jpanel the pane of the frame & when i try to add a JMenuBar object to that it is not getting displayed when i run the code. When i add a menuBar directly to the JFrame object it is visible & working fine but not incase when added to JPanel.
My multi threaded application processes and loads records into an ECM repository. For reconcliation purposes , I am trying to build an XML format report with the results of the processing per record, while processing is underway per thread. The method below is called from every thread wvery time its ready to append an element to the DOM with the status.
public void writeReportLine(Element rptLine) { // Write output to report file synchronized (XMLReportHandler.class) { reportOutput.getDocumentElement().appendChild(rptLine); } }
After all processing completes, the below method is called only once by every thread to write to the File on the file system:
public void writeToReportFile() { synchronized (XMLReportHandler.class) { try{ //write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(reportOutput);
[Code] ....
The problem is that when under load, the threads just seem to hang while the transformer.transform(source, result) call keeps getting executed until there is an interrupt of some sort. I was able to examine a section of what was appended and it was status for records that had finished processing very early in the process based on my application logs. Once an interrupt is recieved , it looks like the threads recover.
I know that below code would put a lock on current instance of DemoClass, What I am not sure of is the role of lock on Object Class in second example. How does below works - Is it putting a lock on Object Class? If yes how will putting a lock on Object? I mean, locking DemoClass ensure no two threads access it concurrently, how does this apply to Object class?
private final Object lock = new Object(); synchronized (lock) public class DemoClass { public void demoMethod(){ synchronized (this)
I am working on a program that will allow a user to input grades for a class of four students who have taken two tests. Based on the grades entered, the program will calculate the averages of the two tests for each student and display it along with their respected letter grades.
Now I can get the program to compile successfully, but after inputting the grades in, I get the error message saying that it cannot format given object as a number. I am using 4 arrays to execute this program and maybe that's why I'm having the trouble? I'm not sure because I am still fairly new at this stuff and can't sen to resolve it.
I was having problems for a while and then finally got excited when I got it to compile without any errors and now I'm getting an error inside my program. All I need to do is format the numbers of the grades into something like: 000, and each of the averages as 000.0. I understand how to do it because I have done it in another program I've done in the past. I just don't know how to fix this error that is coming up.
here is my code:
import java.util.Scanner; import java.text.DecimalFormat; public class TestAverage { /** * A program that will store and process 2 test scores for a class of 4 students. * The program will prompt for the test scores as shown above in the sample run. * After all the data is entered,the program will display the score for test 1, test 2 . * The average of the 2 tests and the letter grade for the class for each student in a tabular format. * *
I'm currently learning about Swing but I can't get my head round this piece of the code. Here is a simplified gui (not interested in the gui part but the execution)
public class SwingDemo implements ActionListener { SwingDemo(){ JFrame jfrm = new JFrame("Simple gui pro"); //rest of code public static void main(String[] args) { new SwingDemo(); }
I get the above, create a new instance of SwingDemo in the main thread which starts up the gui through the constructor. However, then the tutorial says that I should avoid doing the above but do this instead:
public class SwingDemo implements ActionListener { SwingDemo(){ JFrame jfrm = new JFrame("Simple gui pro"); //rest of code public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { //why do this instead? public void run(){ new SwingDemo(); } }); } }
Reading, it talks about an event-dispatching thread which has completely lost me... Why not just instantiate the object directly instead of creating another thread?
im having an issue with the 3rd thread that are supposed to merge the two sorted sub arrays , i pass the 2 subarrays to my runnable function sortlist and they are renamed IntSortList 1 and 2 and th1.start() and th1.join() are called and it works fine, but then i have another runnable constructor that takes IntSortList 1 and 2 but it does take a runnable. below is the code in my main,
Runnable InSortlist1 = new sortList(data2p1); Runnable InSortlist1 = new sortList(data2p1); Thread th1 = new Thread (IntSortlist1); Thread th2 = new Thread (IntSortlist2); try { th1.start(); th1.join();
I'm having an issue when I try to define a variable in a JSP scriptlet, and then in a separate scriptlet on the same page attempt to use the variable. It looks like it goes out of scope.
I also cannot reference a variable from a servlet in a JSP expression tag. So I've had to write the entire page basically in one scriptlet.
JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new File(currentDirectory));
File f = new File(currentDirectory); ArrayList<String> names = new ArrayList<>(Arrays.asList(f.list())); for (String s : names) if (s.startsWith(yearofIssueTXT.getText())) { fileChooser.setSelectedFile(new File(s));
int result = fileChooser.showOpenDialog(addNewCoinBody);
The file is not visible because it is at almost the end of the files in the directory. I want the filechooser to automatically scroll so that the file is seen in the list.
I've been creating a digital clock using Java, and have made the mouse cursor invisible after a set period of time (40-seconds) and had the thought to make it visible again if mouse was moved.
Here's the code that makes it invisible:
ActionListener mouseTimeout = new ActionListener() { public void actionPerformed(ActionEvent e) { setCursor(blankCursor); } }; /* Make mouse cursor disappear after 40 seconds */ Timer mTimeout = new Timer(40000, mouseTimeout); mTimeout.start();
And here is what I have so far for making it visible again:
MouseMotionListener mouse = new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { } };
I have tried using "setCursor(DEFAULT_CURSOR)" but NetBeans says that it "cannot find symbol" .....
I'm trying to make a simple table with JTable class by reading the following tutorial but when try to see my JTable my program doesn't show me nothing! What i'm doing wrong?
[Code] .....
import javax.swing.JScrollPane; import javax.swing.JTable; public class MyFirstTable { public static void main( String[] args ) { String[] columnNames = {"First Name", "Last Name",
I'm trying to make a button that will make a panel not visible and then will make another panel visible but i keep getting this error...
test.java:19: error: local variable panel is accessed from within inner class; needs to be declared final
panel.setVisible(false); ^ 1 error
Java Code:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class test{ public static void main(String[] args){ JFrame test = new JFrame("Test"); test.setSize(600,400);
I found the following inheritance and encapsulation issue . Suppose you have a parent class with a non-static protected attribute.
package package1; public class Parent{ protected int a = 10; // this is the non-static protected attribute in question public static void main(String args[]){ // whatever logic }// end Parent class }// end main()
Now suppose you have a child class in another package and you have imported in the parent class.
package package2; import package1.Parent; public class Child extends Parent{ public static void main(String[] args){ Parent p = new Parent(); Child c = new Child();
System.out.println(p.a); //should print out 10 BUT DOES NOT System.out.println(c.a); //should print out 10 }// end main() }// end Child class
My observation is that p.a produces an error even though, to the best of my knowledge, it should not. I believe the statement "System.out.println(p.a);" should print out a 10.
Am I misunderstanding something about inheritance and encapsulation?
I am building a little application for personal use where I can track my finance. Now, what I would like to get is an always visible JTable "footer" OR horizontal space field attached to the bottom of the window. The idea is that scrolling down/up wouldn't affect it's visibility(like JTable header). Might a picture tell a thousand words: see attachment.
I am wondering, maybe JTable OR TableModel class has a property to solve this problem(I haven't found any)? Or shall I make another ScrollPane/JPanel? Which path of search shall I pursue?
In my code where the Button Action Performed is created, I have done the following to ensure that the visibility of the JTable and JScrollPane have been set to true. But it does not work?
I have noticed a strange behavior of Combobox element. The number of visible rows is not the same established by setVisibleRowCount() method. It happens when changing the items list dynamically. The following example reproduces it. I think it is Javafx 8 bug. I have tried unsuccessfully to trigger some event indirectly to refresh the combobox drop down.
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class TestComboBox extends Application { private int count;
I am building an application that shows tables with large amounts of data containing columns that should display a thumbnail. However, this thumbnail is supposed to be loaded in the background lazily, when a row becomes visible because it is computationally too expensive to to this when the model data is loaded and typically not necessary to retrieve the thumbnail for all data that is in the table.
I have done the exact same thing in the past in a Swing application by doing this:
Whenever the model has changed or the vertical scrollbar has moved:
- Render a placeholder image in the custom cell renderer for this JTable if no image is available in the model object representing the corresponding row - Compute the visible rows by using getVisibleRect and rowAtPoint methods in JTable - Start a background thread that retrieves the image for the given rows and sets the resulting BufferedImage in a custom Model Object that was used in the TableModel (if not already there because of an earlier run) - Fire a corresponding model change event in the EDT whenever an image has been retrieved in the background thread so the row is rendered again
Btw. the field in the model class holding the BufferedImage was a weak reference in this case so the memory can be reclaimed as needed by the application.
What is the best way to achieve this behaviour using a JFX TableView? I have so far failed to find anything in the API to retrieve the visible items/rows. Is there a completely different approach available/required that uses the Cell API? I fail to see it so far.
I'm new to Java and trying to write code a Java program on Mac OS X using IntelliJ. My program uses the SWT library and contains two class's; the first called "view" and the second called "main". The "view" class defines the SWT objects, extends the "Thread" class and contains a "run" method;
public void run() { initComponents(); while (!display.isDisposed()) { if (!display.readAndDispatch()) {
display.sleep();
[code]....
I searched for a solution and saw that I have to use the "-XstartOnFirstThread" parameter to JVM. I'm trying it with no success.
I making a program that a client connect to a server, then it's starts changing information throw the socket. The info is String. When connection with one open client everything is working great. The problem starts when I connect 2 or more clients simultaneously.
The server doesn't know how to handle each request so it's send info to both the client info that is wrong. If I run several clients and then execute the last client that opens he will work fine the others will crush. On the server I'm getting connection reset. The problem i believe is with the closing socket and thread holding.
I have this web app in Glassfish which, among other things, monitors consultations in some DB. It's a JEE-EAR app, three layers. Pretty boring until now. Now, there's another WAR-app on Tomcat that processes files through threads. These threads represent an Excel file processed one row at a time.
I need to know when one of those threads are created, when they're alive and when they're terminated, from the Glassfish app.
I need to monitor these batch processes.
I think I could insert the thread ID from the tomcat app in some DB and when it dies, delete it. The glassfish app would query that BD and see if there is one of those batch processes running.
I understand that a thread ID can be recycled but I can find a way to make every process unique.
My first question, would this be viable?
My second question is, could I uniquely set the thread name and then ask for it from the glassfish app to the tomcat-app process thread set? I mean, without a DB in the middle?
Write a program to print the even numbers and the odd numbers between 0 and 30 using a single thread and then again using multiple threads.
I already finished the single-threaded program but am having trouble with the multi-threaded one. I have three classes; one class for odd numbers, one for even numbers, and one to execute the code. Here is my code so far:
Even Numbers:
Java Code:
public class EvenNumbers extends Thread { public void run() { for (int i=1; i<=30; i++) { if (i%2 == 0) { System.out.println("Even number " + i);
[Code] ....
Unfortunately, my output ends up looking a little weird:
Java Code:
C:UsersREDACTEDDropboxSchoolworkREDACTEDJava ProgrammingUnit 5 - Exception Handling, AssertionsProgram - Thread>java MultiThread Even Numbers: Odd Numbers: Even number 2