How To Minimize CPU Usage For Sockets And Threads
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
ADVERTISEMENT
Dec 26, 2014
I have just started learning about sockets and such... and i have created a chat program with a server and a client
server:
public class Server {
private static ServerSocket server;
private static Socket connection;
private static PrintWriter pw;
private static BufferedReader br;
private static JTextField textOutput;
[Code] ....
so, everything is working fine . There is only one thing i would like to do now: make it so that i can run the server from my computer and then others can run the client from theirs and we will be able to chat . So I tried:
In the client code on line 56 is says:
connection = new Socket("localhost",7777);
So I changed "localhost",7777 to "myip",7777)
But when i run the server on my computer and run the client on another computer i get this error:
java.net.ConnectException: Connection refused: connect
Why is the connection getting refused? is it for security reasons? so hackers cant connect to me or something? And is there a way to tell your computer to allow that client to connect?
View Replies
View Related
Mar 13, 2014
I am having a problem passing an int value from one class to the other. The gist of the objective of this program is to compute a local sum at each client, and then once the local sums are computed.. to compute the overall sum from all the clients. My problem is that I'm having trouble figuring out how to pass each sum from each individual client in the class multicastSenderReceiver to the readThread class. I keep getting an error.
I feel that I have to be able to pass the sum value from each client generated in multicastSenderReceiver to the other class, because that is the only way I'll accurately be able to sum up all the values..
Java Code:
package multicastsenderreceiver;
import java.net.*;
import java.io.*;
import java.util.*;
//import static multicastsenderreceiver.multicastSenderReceiver.numProcesses;
class multicastSenderReceiver{
[code]....
View Replies
View Related
Dec 6, 2014
I have all of my code written, but it is not producing any output and i'm not sure why.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
[code]...
View Replies
View Related
Apr 11, 2014
Generally Socket Programming uses HTTP Protocol to send and receive messages in Java. Can we try to exchange HTTP/HTTPS requests instead of TCP?
a Socket constructs a HTTP request to send to another socket from information it has and sends to another one and Server responds with HTTPResponse.
View Replies
View Related
Apr 8, 2014
I have written a java code to transfer files from one server to another using the concept of socket programming. I got the codes from another java forum that meet my requirements. The program is said to transfer large sized files (like .mkv , .mprg movies) from one machine to another and can be used to transfer files of all formats. But after running the codes I found that the program is not able to transfer large sized files such as movies and even pdf of sizes 80mb or 111mb. When i transfer small sized files, it gets transferred and the output shows that. You can run the codes and observe it. But when i try to transfer large sized files, the program goes on running for hours. The large sized files are not getting transferred. The program has used bytebuffer but still this error occurs.
**ClientMain.java**
import java.io.IOException;
import java.net.Socket;
public class ClientMain
[code]....
Note that:-
1. ClientMain.java and DirectoryTxr.java are the two classes under client application.
2. ServerMain.java and DirectoryRcr.java are the two classes under Server application.
3. run the ClientMain.java and ServerMain.java simultaneously
Also specify the source directory, destination directory and host address of the machine in which server is running in the ClientMain.java(as per your computer). Here we are not specifying source file ,instead a source directory or folder is specifying.So the entire files of source directory will be transferred.
View Replies
View Related
Dec 26, 2014
I have been practicing writing java code, my university course is going to cover socket programming and multi-threading.
I am presently just starting to write myself a framework for all multiplayer games I may make in the future, my aim really is simply to practice and understand better and this time, im not using an ide, just sublime text, all new grounds for me, I have a good basic understanding of the subject but I want to be fluent.
import java.net.*;
import java.util.ArrayList;
import java.io.*;
/*SMOOTH THREAD SAFE MULTI CLIENT HANDLING CLASS.
*
*This class will create connection objects when a connection is detected, these connections will run in a separate thread and update an array list in their parent class containing their last sent data
[Code] .....
View Replies
View Related
May 7, 2014
This question has confused me because "Errors" are capitalized and I'm not sure what they mean.
To me this question is false. Sockets can be used to transfers file over a network.
I can't see why this wouldn't work. The code looks fine to me.
I don't think this is true unless you're using the mouseEntered() or mouseExited() method. But again, I'm not sure.
I think this is true, I don't know what else could have listeners.
They're only worth a few marks each so the answer is only suppose to be a line or two. They are all true or false questions that require an explanation.
View Replies
View Related
Apr 7, 2014
I want to get current Computer CPU usage of my computer and display it in Console View of Eclipse? How can I achieve this?
My template code is:
Java Code: public class GetCPUUsage{
public static void main(String[] args){
System.out.println("CPU USAGE IS: ??????");
}
} mh_sh_highlight_all('java');
I added ??? as placeholder for CPU usage because I do not know how to retrieve RAM usage by Java.
View Replies
View Related
Apr 3, 2014
I'm working on an assignment right now which involves passing a variable series of numbers to the Server to be sorted into the correct order and returned to the client.
So far I have it connecting to the server and asking for my numbers, and I am entering each number and pressing return, and it is accepting each number individually.
One (smaller I think) problem i'm having is with the client code, specifically the while loop.. I've tried to code it so that when I enter a full stop ('.') the program will stop asking me for more numbers and move on to sending them to the server.. but instead it just crashes giving an error.. heres an example
"Enter a number: 1
Enter a number: 3
Enter a number: 2
Enter a number: 1.
java.lang.NumberFormatException: For input string: "1."
at java.lang.NumberFormatException.forInputString(Num berFormatException.java:65)
[Code] ....
Here's the client code in full
package numberSortprogram;
import java.io.*;
import java.net.ServerSocket;
public class NumSortClient {
public static void main(String[] args) {
InputStreamReader is = new InputStreamReader(System.in);
[Code] ....
The big problem that I have is figuring out how to send the sorted array back to the client..
So, what im trying to get to happen is-
-Client is asked to enter numbers
-Client enters series of numbers into an array
-Array is converted to a string and sent to the server
-String is then split into an array of strings and sorted using compareTo (don't know if this is the best way?)
-Sorted array is sent back to client and displayed.
fyi this is making use of streamsockets..
All of the rest of my code is below:
package numberSortprogram;
import java.io.IOException;
import java.net.*;
import java.util.regex.PatternSyntaxException;
public class NumSortServer {
public static void main(String[] args) {
int serverPort = 4444; // default port
if (args.length == 1 )
[Code] .....
View Replies
View Related
Oct 6, 2014
I have an application written in Java on the Linux platform. My application will work the following way:
User A will open application. User B will open application.User A will need to send User B a message but without a socket connection.User B will need to send User A a message but without a socket connection.The user should be able to identify the messages sent to each other.If User A reads user B's message the message will no longer be available in the channel of communication.If one user exits their application their message should be removed.User C should not be able to read user A and user B message (This is only via the application design, no real security here).Applications should be able to work on different machines however they will utilize a shared network mount to access files modified by each other.
I do have to note that the messages being sent is rather small and only 1 message is sent from each user, so in that regard I did not want to setup a client/server model to do this using sockets.
Basically I am looking for a similar concept as a message queue but more relevant to my requirements done in Java. What are some good options to use that will address some of my requirements? I have not touched Java in a long time and only have used it for certain usage so I am trying to get an idea of which current technologies are best for what I need.
View Replies
View Related
Jul 17, 2014
I have a class as shown below. This class has a method addFilter with 2 parameters (type String and type Command1 )
public class Command1 {
public StringBuffer addFilter(String query, Command1 dataBase) {
//concrete implementation
return query;
}
}
I have another class Command2. Here I need a similar method. The only difference is in the type of parameters passed. (type String and type Command).
public class Command2 {
//TO DO:
public StringBuffer addFilter(String query, Command2 cmd) {
//concrete implementation
return query;
}
}
I have started by using Interface
public interface Helper {
public StringBuffer addFilter(String query, XXXXX parameter2);
}
I would like the classes Command1 and Command2 to implement the interface Helper and override it these two public classes.
However my problem is in dealing with the 2nd parameter. Am I right in my approach? How do I handle this issue?
View Replies
View Related
May 26, 2014
I am working on a project with client/server relationship and I want the client to be able to transfer their personal music files over the socket. Every time I attempt to do it the file is created but it is empty.
Server code:
Java Code:
public class Server extends JFrame {
//===============================
// FIELDS
//===============================
// connection essentials
private ServerSocket server;
private Socket connection;
[Code] ....
View Replies
View Related
Feb 21, 2014
What is the usage of garbage collector in java.
View Replies
View Related
Mar 18, 2015
I would like to limit my bandwidth usage when accessing/downloading files (similar to the --limit-rate 50K option for curl and wget) as the website has limited bandwidth. I am not exactly sure how to implement this, but I'm guessing it be accomplished via the BufferedReader? I have attached the current code below.
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
[Code]....
View Replies
View Related
Jun 17, 2014
Declaring the method as static precludes one from using any sort of object oriented programming, thus the method cannot access instance fields of the object if it needs to.
I created two short classes to sort of find out what this meant, but I feel I do not understand it well enough.
Test class (main):
package votek;
public class Test {
public static void main(String[] args) {
SomeMethod();
}
public static void SomeMethod() {
Character character = new Character();
character.totalLevel = 50;
System.out.println(character.totalLevel);
}
}
Character class:
package votek;
public class Character {
private int level = 0;
public Character() {
level = 50;
}
}
OR
Does it mean that making a static method in the class with private instances will prevent the method from using the private instances?
View Replies
View Related
Mar 7, 2015
I've spent almost 3 hours on googling about java beans and where it is usable. What I've figured out is that a bean has a public non-arg constructor, properties and getters/setters to manipulate them. I also know that a bean contains no logic, only fields. However, I don't fully understand why I need to use beans instead of normal classes even if a class can do the same things like a bean? Are beans used to store data or what?
View Replies
View Related
May 30, 2014
We have a webservices application that uses Java 1.6.0_43, Spring 3.2.3, CXF 2.6.9 and deployed to Jboss 5.0.1 GA in a LINUX x86_64 centos box. It essentially uses apache httpclient (4.2.2) to call internal services and returns the results back to customers. The application has been running fine for a year or so until early this month when all of sudden, it loaded about 300K classes in a very short time during our regression tests and saturated the CPU usage ever since. Hence the application is no longer responding.
I have been trying to troubleshoot the problem for a while. Tried visualvm, dynatrace. thread dumps. heap dumps... None of them is very effective in capturing what are the classes that are loaded so many times and what path triggered that.
View Replies
View Related
Feb 3, 2015
When it comes to Java EE I see many developers having trouble with the usage of transactions and exceptions and when to use what.
I see a full chapter of RESTful Web Services, but do you also relate these Web Services to their counterparts (SOAP Web Services)?
View Replies
View Related
Jun 27, 2014
I found this method from the same link from which I found the Pandigital method. This method uses the algorithm of sieve of eratosthenes who was a greek mathematician and showed how to find prime numbers by taking an individual number and finding the multiples of it and cut them out for they will not be a prime number. From what I've seen this program gives the results much faster than the traditional way of searching for prime numbers by diving that number by the digits upto half of that number and check for divisiblity.
Well, here's the code
public int[] ESieve(int upperLimit) {
int sieveBound = (int)(upperLimit - 1) / 2;
int upperSqrt = ((int)Math.Sqrt(upperLimit) - 1) / 2;
BitArray PrimeBits = new BitArray(sieveBound + 1, true);
for (int i = 1; i <= upperSqrt; i++) {
if (PrimeBits.Get(i)) {
[Code] .....
As seen from the full program on the site [URL] .... this program was formely writen in C++ and from there I've scrapped out this method as the syntax are corresponding to that of Java, but one problem I faced was in finding the BitArray class in Java. I was unable to understand the approach of this program to find the prime numbers.
View Replies
View Related
Apr 7, 2014
I want to get current RAM usage of my computer and display it in Console View of Eclipse? How can I achieve this?
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
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