Console Freezes When Working In Different Threads
Jul 22, 2014
I have a console application. One thread allows a user to directly input into a console. Another thread listens on a tcp port, takes input, processes it, and then writes it to the console. The work in different threads, but in tcp thread, one I call a method outside that thread that writes to console, it often gets stuck. here is a mockup of situation:
Java Code:
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
[Code] ......
It often freezes on "Attempt 1". Before I used System.out there, I also tried console.writer() there but both freeze at that point often. Any situation where console or System.out.writeln freeze when working across threads and why it is occurring? It almost feels like one thread has locked the console so the others can't write to it.
View Replies
ADVERTISEMENT
Nov 6, 2014
My console SQL Query app is not giving me the desired output.I am sure its might have something to do with my SQL Query.Its missing the description of the stock items and it prints a new line for each user as per number of stocks an repeats the user details and then prints the stock listed by that user(only want the user listed once with all its stocks). I will add my files and current output and desired out put below.
MakeDB.java:
import java.sql.*;
import java.io.*;
public class MakeDB
{
public static void main(String[]args) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:StockTracker";
[Code] .....
View Replies
View Related
Jan 16, 2015
This code is for a tic tac toe game. I have a action listener set up and if the user entered a move that would win the game of tic tac toe it would call on a restart() method to clear the board, but every time some one wins the GUI freezes.
class ListenerCA implements ActionListener {
public void actionPerformed(ActionEvent event) {
Board.clear();
if (turn == 0) {
start.answer = "CA";
[Code] .....
The code below this is the normal execution flow.
static void start_game(String board[][]){
final int one = 1;
final int two = 2;
int x = 0;
play game = new play();
[Code] .....
In the above code gui == true always, I just kept an option if i ever wanted to run the program in console. The code below is the restart method.
static void restartgui() {
gui = true;
if (gui ==true) {
board[0][0] = " ";
board[0][2] = " ";
[Code] ....
View Replies
View Related
Dec 2, 2014
I don't understand why when I collide into my objects my character freezes. Such as if I collide into collision() I can go left and right but, not up and if I collide into collision2() I freeze in all places but, if I collide into the bounds I made I can still go in all directions without problems. The xa and ya are still being set to 0.
package com.questkings.game;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
[Code] .....
View Replies
View Related
Apr 20, 2014
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.
View Replies
View Related
Apr 28, 2014
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.
View Replies
View Related
Apr 10, 2014
I am developing an application to share my client screen with server, it is working well on swing. But i want to develop as web application, i am trying to using applet. But i am facing the fallowing problem..,
1) The Applet screen also open and project also running well on server mechine. But unable to see the client screen on the server.
2) The problem may be to display the JDesktopPane or JInternalFrame.
My working Server Code extends withe JFrame..Java Code:
package remoteserver;
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JApplet;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
[code]....
View Replies
View Related
Feb 5, 2014
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?
View Replies
View Related
Mar 11, 2015
Here is what I am trying to do:
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
[Code] .....
View Replies
View Related
May 30, 2014
I'm reading the following section of the Oracle docs:
Guarded Blocks (The Java Tutorials > Essential Classes > Concurrency)
We have multiple threads. One of them sets the joy flag to true. The other waits until joy flag is set to true in order to print to the output stream. Rather than squander processer resources with a while loop, we choose to use the wait method of Object which suspends execution of thread. When the other thread throws an exception, we check the loop condition again.
Java Code:
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
} mh_sh_highlight_all('java');
The documentation goes on to state the following:
When a thread invokes d.wait, it must own the intrinsic lock for d - otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock. When wait is invoked, the thread releases the lock and suspends execution.
The statement seems somewhat contradictory. When we invoke wait inside a synchronized method, is the intrinsic lock acquired or released? I thought it was the synchronized keyword itself that acquired the intrinsic lock.
View Replies
View Related
May 21, 2014
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.
View Replies
View Related
Aug 16, 2012
I created an instant messenger using java. When I have the Server that communicates between the clients and one client running on my Computer the CPU Usage is at 100%. It really slows down everything else I'm doing and I figure this might be an issue if I gave this to people to use. I don't want the client taking up a lot of CPU Usage if they're just running it in the background while doing other things on their computer. The program utilizes multithreading. Each thread is constantly being polled for input.
The Server, as seen below, has two threads. I explain what the threads do before the code. There is also another while loop running constantly in the server that is waiting for sockets to connect. The loop does not run constantly at the line socket.accept(); it stops and just waits.
The User, split into a menu and chat window, has two threads as well. I explain what the threads do before the code. After I originally posted I put a 100 ms sleep in all my threads. CPU Usage is still at 100%*
This thread listens for input from the user. The input tells the server what action to take. There is a thread running for every user currently connected to the server.
public void run()
{
try
{
input = new DataInputStream(user.getSocket().getInputStream());
output = new DataOutputStream(user.getSocket().getOutputStream());
[code]....
View Replies
View Related
Mar 24, 2014
I need a small example of an object which is visible to two different threads.
Does saying "an object is visible to two threads" mean that it's fields or methods are being used in both the threads? I am not clear about that.
View Replies
View Related
Nov 30, 2014
I have been working on this program for a while and now i seem to be stump it throws an outof Bound array exception error, this program is a matrix multiplication program and spits out the resulting matrix using multithreading. i have a running one and result is
2 -1 0
1 0 3
-1 1 3
but this program's result is:
2 0 0
1 0 0
-1 0 0
it reads a txt document as an commandline arguement the text file reads just like this below:
3 2 2 3
1 0
0 1
-1 1
2 -1 0
1 0 3
the following is my code:
import java.util.*;
import java.io.*;
public class P3 {
public static int matrix1[][];
public static int matrix2[][];
[code].....
View Replies
View Related
Apr 18, 2014
Actually, i want to create multiple ball using multithreading.I have created a class 'CreateBall' and this class is making ball and second class 'Balls' is a Panel where the ball is display.But only one ball is being displayed.
Here is my code.......
CreateBall.java
import java.awt.*;
public class CreateBall implements Runnable
{
int px,py;
int w=20,h=20;
Graphics g;
public CreateBall(int px,int py)
[Code] .....
View Replies
View Related
Jun 25, 2014
Below are three classes. The first and second create car objects and the third is the main method. My goal is to move two cars across the window. When I compile and run the program both cars are generated however they will not animate. I am moving them with threads but I cannot seem to find why the cars will not move.
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class CarComponent extends JComponent {
private Car car1;
private Car car2;
[Code] ....
View Replies
View Related
Jun 19, 2014
I am very new to threading. I have a program that calls my api and gets data back in json format. Each request returns a row of data in json format. All together I need to retrieve about 2,000,000 rows a day which means 2,000,000 requests (I understand that this is bad design, but the system was not designed for this purpose it is just what I need to do for the next couple of weeks). When I tried running it on a single thread I was processing about 200 requests a minute which is much too slow. As a result I created 12 threads and I was processing 5500 rows a minutes which was a great improvement.
The problem was only about on average 90% of the rows were inserted into the database as I ran it a few times to make sure. Before each insert printed to a file each URL which was sent and then I checked to see if each insert statement was successful (returned 1 when executed ) and it all seems fine. Every time I run it it inserts about 90% but it does varies and it has never been a consistent number.
Essentially the code starts in main by creating 12 threads. Each thread's creates a run method which calls a new instance of MySQLPopulateHistData and passes a start and end integer which are used in the insert statement for ranges. I have done many system.out.println type testing and can see all the threads do start and all the 12 instances (one instance for each thread) called are executing?
MAIN:
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainClass {
public static void main(String[] args) {
[code]....
View Replies
View Related
Jun 4, 2014
Aim : display a serial number using two thread Say (odd numbers)t1=1,3,5,7....99, and (even no) t2=2,4,6,8......100
How to resolve this problem ?
output will be:
1
2
3
:
100
View Replies
View Related
Dec 16, 2014
I've seen examples that don't use a separate Runnable Implementation, but Instead Just make a subclass of Thread and override the Thread's runO method. That way,you call the Thread's no--arg constructor when you make the new thread;
Thread t = new Thread(); 1/no Runnable"
Any simple code that demonstrates the same. I haven't fully understood what is said in the text above. I have a hunch that the last line is wrong and it should be Thread t = new <Whatever class extends Thread class and over rides its run method>()
Am I correct or wrong....
View Replies
View Related
Aug 23, 2014
I have a Swing UI in which on click of Search button, I trigger the Search in 6 different modules in 6 Swing Worker threads. The results are returned by each Swing Worker class to the calling class.
I tried to use the below code to get the values returned from each thread. Now, I want to continue further only after all threads finish their execution. How to achieve this?
thread1.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (StateValue.DONE == thread1.getState()) {
try {
[Code] ....
I got several examples where the UI is updated direstly from multiple threads. I want the values to be returned to calling class because of below reasons:
1) When even one worker thread fails for some reason, I dont want to show the any result in the UI
2) Earlier, I was updating the UI in done() of every worker class. But, UI became inconsistent. E.g When one thread is in progress, other threads were completed and updating the UI which I dont want to do.
View Replies
View Related
Nov 17, 2014
I have two threads, one generates data based on some decision process (A) and another use the data to plot it (B). The problem occurs when there is no data to plot. What is the best way to synchronize these two threads? Using sleep, or wait/notify?
View Replies
View Related
Apr 16, 2014
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)
[code]....
View Replies
View Related
Feb 24, 2014
I am trying to write a program in Java that uses threads.Below is the program requirements:The goal of this assignment is to create a routine which creates multiple threads, has them do work in parallel, and terminates when the last thread has finished.
The Scenario: There are several groups of people in a bar watching the Olympics cheering for their country. Each group will cheer for their country some given number of times, with a random pause (between 2 and 5 seconds) between each cheer. There is enough room at the bar for up to ten different groups to sit (each would be cheering for a different country).
The Program: The task is to write a program that will simulate these cheers using threads. The program should be called cheer.X (X being the language of choice). You may use any language that supports threading. When the program is run it should ask for the number of countries and then the name and how many times it will be cheered for. The main function will then create a thread for each team and each thread is responsible for cheering the specified number of times for the correct team at the random interval. You will submit the proper source code file for me to open and compile myself, not an executable.
An example run would look something like this: How many countries are supported at the bar? 3 Enter the first: China How many cheers? 2 Enter the second: USA How many cheers? 4 Enter the third: Russia
View Replies
View Related
Apr 14, 2014
While analyzing the thread dumps for a performance issue in our java ee web application, I see many thread dumps stuck on a closing brace of a while loop. Here is the code block of a third party library bitronix (version 1.3.3 SNAPSHOT)
public XAResourceHolderState findXAResourceHolderState(XAResource xaResource) throws BitronixSystemException {
Iterator it = resources.iterator();
while (it.hasNext()) {
XAResourceHolderState xaResourceHolderState = (XAResourceHolderState) it.next();
if (xaResourceHolderState.getXAResource() == xaResource)
return xaResourceHolderState;
}
return null;
}
The thread dumps indicate that many threads are stuck in RUNNABLE state on line number 07. What could be the possible reasons on why a thread could get stuck on a closing brace of a while loop? The iterator of the while loop is a custom implementation.
View Replies
View Related
Jun 30, 2014
I have a multithreaded application. I have a Logger class with static methods that I use across threads. Would it behoove me to add the synchronized keyword to the static methods of the Logger class since I use this class statically in different threads?
View Replies
View Related
Mar 21, 2014
When a thread completes its execution, it will be destroyed.In Java thread pool implemenation, how does threads come back to ready state after executing the task.?
View Replies
View Related