Thread Priority Management
Hi All,
In my Solaris(4 CPU) box there are multiple JVMs are running to serve different components of the application. Due to several design holes most of these components are consuming max CPU. Now I am planning to reduce the priority of thread execution in one of the least used component to release CPU for those other JVMs/Components to process faster. Since they are running in different JVMs how setting priority of task A in JVM � X will help task � B in JVM � Y? If that won�t help, can you please suggest me the best way to solve this issue??
Thanks in advance,
-Cheenath
Thanks for your comments and I agree 100% with you, but the situation is to provide work around rather than changing the whole system design as there is no much time in hand.
Basic question is how Java handles setting thread priority? � If it involves a map of threads with priority information to get executed whether JVM checks the system parameters like CPU utilization before commanding OS to execute or OS decides how to execute the threads which JVM instructed?
Is there a way we can restrict Java to suspend processing once the CPU usage is higher than say 80% ? like a parameter set while running the application saying if the CPU is less than 80% then only execute the process?
Similar Messages
-
How to set main thread Priority?
i have set:
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
// and the other thread ( )
thread_load = new Thread();
thread_load.setPriority(Thread.MIN_PRIORITY);
thread_load.start();but it doesn't make any diffrent,
i mean diffent the CPU usage for the thread.
i want the main thread has a MAX PRIORITY CPU usage , then the other thread.
is this true to set the thread priority use setPriority(..) ?
thx..Thread is a Runnable within java (or javaw) process: his priority has no meaning outside the JVM, if you wanna impact on CPU usage you should set this process priority, i.e. (for windows):
instead of starting as
javaw ....try
start/min javaw ...You could need to quote the javaw command, to see all possible priorities see start help by typing start/? in cmd.
Bye. -
Help-- build a Thread to manage Client
Login: it sends to Server a string= "CONNECTING" and Server will send a string = "CONNECTED" then EchoClient (is a thread which manage a connection from the outside) will call a new thread(ManageClient) with a new port to make a seperate connection.
Problem... while running Login and click the button after run EchoClient, there is no respond
Maybe it's too long.. Sorry and thanks for running my code and helping me
Login class
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Login extends JFrame {
public ChatFrame chatFrame;
private final int CONNECTED = 1;
private final int CONNECTING = 11;
private Socket connectSocket = null;
BufferedReader in = null;
PrintWriter out = null;
* @param args
public Login() {
// TODO Auto-generated method stub
setSize(50, 150);
JButton loginButton = new JButton("Login");
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.add(loginButton);
add(p);
//Wait and listen the line from server
Thread t = new Thread() {
public void run() {
try {
Socket connectSocket = new Socket("localhost", 903);
in = new BufferedReader(new InputStreamReader(connectSocket
.getInputStream()));
out = new PrintWriter(connectSocket.getOutputStream());
String stringLine = in.readLine();
if (stringLine == "CONNECTED") {
int port = in.read();
chatFrame = new ChatFrame(port);
chatFrame
.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chatFrame.show();
connectSocket.close();
} catch (Exception e) {
t.start();
//click Login button and send "CONNECTING"
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
out.print("CONNECTING");
System.out.print("send ");
} catch (Exception exp) {
exp.printStackTrace();
public static void main(String[] args) {
Login login = new Login();
login.show();
login.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EchoClient class
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class EchoClient extends Thread {
private ServerSocket listenSocket = null;
private Socket manageSocket = null;
private int[] port = new int[9999];
private BufferedReader in;
private PrintWriter out;
private int line;
private int count;
//private ClientNode[] clientArray = new ClientNode[9999];
private ManageClient[] manageClient;
private final int CONNECTED = 1;
private final int CONNECTING = 11;
private final int DISCONECTED = 2;
public void run() {
try {
//manageClient = new ManageClient[9999];
listenSocket = new ServerSocket(903);
manageSocket = listenSocket.accept();
while (true) {
in = new BufferedReader(new InputStreamReader(manageSocket
.getInputStream()));
out = new PrintWriter(manageSocket.getOutputStream());
String stringLine = in.readLine();
System.out.print(in.readLine());
//wait and listen from client
if (stringLine != null) {
//if recieve a string send "CONNECTED"
out.print("CONNECTED");
//"Creat a port for ChatFrame"
port[count] = (int) Math.ceil(Math.random() * 9999);
manageClient[count] = new ManageClient(port[count]);
manageClient[count].start();
out.print(port[count]);
count++;
listenSocket.close();
} catch (Exception e) {
e.printStackTrace();
public static void main(String[] args) {
EchoClient e = new EchoClient();
e.start();
ManageClient class
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ManageClient extends Thread {
private ServerSocket ssClient;
private Socket sClient;
private int port;
public ManageClient(int port) {
this.port = port;
public int getPort() {
return port;
public void run() {
try {
ssClient = new ServerSocket(getPort());
sClient = ssClient.accept();
while (true) {
BufferedReader in = new BufferedReader(new InputStreamReader(
sClient.getInputStream()));
PrintWriter out = new PrintWriter(sClient.getOutputStream());
String s = in.readLine();
if (s != null)
out.print("have recieved");
} catch (Exception e) {
e.printStackTrace();
ChatFrame class need for running
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class ChatFrame extends JFrame {
private JTree tree = null;
private ClientNode[] clientArray = new ClientNode[9999];
private JTextArea textChat = null;
private JTextField[] textBox = new JTextField[9999];
private Socket connection = null;
private BufferedReader in = null;
private PrintWriter out = null;
private int port;
private JTabbedPane communicationTab;
private JButton sendButton;
public ChatFrame(int port) {
setSize(300, 300);
this.port = port;
DefaultMutableTreeNode user = new DefaultMutableTreeNode(
"Another users");
DefaultMutableTreeNode Client1 = new DefaultMutableTreeNode("Client 1");
user.add(Client1);
tree = new JTree(user);
JScrollPane treeScrollPane = new JScrollPane(tree);
JPanel p = new JPanel();
p.add(treeScrollPane);
communicationTab = new JTabbedPane();
JSplitPane upperSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
communicationTab, p);
upperSplitPane.setContinuousLayout(true);
upperSplitPane.setOneTouchExpandable(true);
upperSplitPane.setResizeWeight(1);
textChat = new JTextArea();
textChat.setLineWrap(true);
textChat.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(textChat);
JPanel q = new JPanel();
sendButton = new JButton("Send");
sendButton.setSize(2, 2);
q.setLayout(new FlowLayout());
q.add(sendButton);
JPanel tc = new JPanel();
tc.setLayout(new BorderLayout());
tc.add(scroll, BorderLayout.CENTER);
tc.add(q, BorderLayout.EAST);
JSplitPane underSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
upperSplitPane, tc);
underSplitPane.setLastDividerLocation(1);
underSplitPane.setResizeWeight(1);
connectToServer();
getContentPane().add(underSplitPane, "Center");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if (textChat.getText() != "")
send(textChat.getText());
textChat.setText("");
public void connectToServer() {
try {
connection = new Socket("serverName", getPort());
while (true) {
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
out = new PrintWriter(connection.getOutputStream());
String s = in.readLine();
if (s != null) {
textChat.append(s);
} catch (Exception e) {
public int getPort() {
return port;
public static void main(String[] args) {
ChatFrame c = new ChatFrame(903);
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.show();
public void send(String s) {
try {
out.print(s);
out.print("\r\n");
out.flush();
} catch (Exception e) {
e.printStackTrace();
}Edited by: rockfanskid on Oct 17, 2007 9:47 AMI agree with DrClap.
Another thing: do NOT compare Strings with == unless you want to check for identity equals (as in the same object). Use String.equals() instead for equality.
Example:
String a = "test";
String b = "test";
String c = new String("test".getBytes());
System.out.println(a.equals(b)); // true
System.out.println(a == b); // true
System.out.println(b.equals(c)); // true
System.out.println(b == c); // falseThis is just a trick from Sun to confuse you ;) String's are internally pooled by the String class. Look at the javadoc of String.intern() for instance for more information. But use String.equals() in your code... -
I am working on a system where I have a couple of background threads processing some non-time critical tasks. The desired behaviour of the system is that the background threads would adapt itself when the load of the system is increasing/descreasing... So as to ensure the normal operation of the system performing the main tasks.
How reliable is with the use of java thread priority... I thought of something like lowering the priority of the background threads gradually when the load increases and then boosting the priority to a max of NORMAL_PRIORITY when the load descreases... what about the use of yield()? I am using some application facts to predicts the load of the system... Does anybody has a clue whether it is possible to query general information about the system load through some java APIs (without using native libs)?
Your advice and help is much appreciated...It is very platform dependant. Windows screws
everything up when it comes to threads. They favor
GUI threads natively over non GUI threads. So instead
of letting the programmer setup thread priorities
Microsoft figures your a moron and adjusts it for
you... Plus the 10 levels of priorities doesn't map
well at all between unix and Windows. If you look
even deeper inside you will see just what a joke
Windows threads are.I don't think I can just rely on the reliability of Java Thread Scheduling... I need something more than that. I need to reach a confidence level that the background threads will not affect the operation of the main worker threads. Though "sleeping" to give up control may not have result in good utilization, but it indirectly create more chances for the worker threads to run. I need to play around with a good sleep time, or best, sleep longer when the load is high/increasing and shorter when the load is low/decreasing... By the way, do u think the context switches incurred when will be significant? -
Changing Thread Priority for TimerTask
I am scheduling two different tasks which will run as part of a larger appln.
I am scheduling with the help of TimerTask and Timer class.
Now i want to reduce the thread priority for these one task say inside the run method.
Do I have access to reduce the thread priority for this If YEs How?
Thanks
MumThis technique may be appropriate. But a word of caution - Java thread priorities do not necessarily affect the behavior of the OS in scheduling threads across processes. That is outside of the scope of the language and JVM specifications.
Also, if your delete task tends to use little CPU time itself (just issues a lot of SQL commands for instance) but causes the database server to consume a lot of CPU and/or I/O capacity, then adjusting the priority of the thread running that task will have little if any affect on the degree to which the delete task interferes with the other application.
Chuck -
Go through this code :
public class threadtwo extends Thread
public void run()
System.out.println ("New Thread");
public static void main(String[] args) {
threadtwo two = new threadtwo();
two.setPriority(10);
two.start();
System.out.println ("xyz");
The output is :
New Thread
xyz
and sometimes :
xyz
New Thread
shudn't " two " run first always because it has higher priority ??No. There are no guarantees about the order that threads run especially with regards to the assigned priority. The thread priority should be treated as a hint only which, depending on the platform and OS, the JVM may choose to ignore.
In your example, the 'threadtwo' may not even have started running before System.out.println ("xyz") is reached and executed.
P.S. Please use the Java naming conventions. -
Increase of Threads in Managed Nodes
Hi,
I have the following question.
I am analyzing the performance of an Weblogic OSB Cluster in a Production Environment witch is compose by 4 managed servers, with 4 GB of memory each.}
This is the Server Start of each one:
-server -Xms4096m -Xmx4096m -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:NewSize=512m -XX:MaxNewSize=1536m -XX:PermSize=512m -XX:MaxPermSize=512m -verbose:gc -XX:+PrintGCDetails -Xloggc:/export/home/applsoap/gc_ap1.log -Dweblogic.threadpool.MinPoolSize=150 -Dweblogic.threadpool.MaxPoolSize=340
Nowadays the requests peek during the day is of 15000 Request per minute.
During the day, the Memory of each managed server is around 3GB, and the Threads are around 230 and 280.
I have seen that when threads are increased over 4000 the performance of the system decrease significantly.
We are facing in the following weeks an increase in the request per minute in at least 2 times.
My question is, the parameters of the node that I can see in the Jconsole or in the Oracle Enterprise Manager will be duplicated linearly with this increase?
I mean, I have now 280 Threads with 1500 request per minute?
If I have 3000 request per minute, will I have 560 threads ?
Since I have seen that Up to 400 threads the system is Instable.
I can imagine that the increase will not be linear, but some advice regarding how to measure the performance in the installation will have with
and increase of 2 times the load will be thanked!!!
Thanks you in Advance!As the name of the method implies the Pool returned by that method supports only a fixed number of threads.
If you want to be able to modify the number of threads after instantiation, then you could use a ThreadPoolExecutor. This class supports changing the number of threads it uses. -
Help needed about thread priority
Hello, could someone help me with the priorities in java? I got 10 levels in total(1-10), but I do need at least 20 levels for my multiple threads program.
Thank you for your kind help in advance.First, let me apologize if I am incorrect, but it seems that the native Thread implementation restricts you to 10 priorities regardless.
However, you can do just about anything you envision, but it will require some implementation on your part.
You could implement a subclass of thread that contains your priority (which could be from 1-20). You could then maintain a ThreadManager that would store all running threads, and would accept requests to start and stop threads. The ThreadManager could make decisions about which threads to run, which to interrupt, which to sleep, etc., based on your priority value.
This sounds like alot to swallow, but I'm sure it's doable if you understand threads. -
Questions about thread priority...
Situation 1) setPriority(int adsa)
public class ThreadPrioDemo1 {
static class Demo1 implements Runnable{
public void run(){ //blablabla}
public static void main(String[] asdf){
Runnable r = new Demo1();
Thread myThread = new Thread(r);
Thread mainT = Thread.currentThread();
//mainT's priority is 5, so as myThread.
mainT.setPriority(10);
//mainT's priority to MAX, this simultaneously changes myThread to 10 as well.
//or
myThread.setPriority(10);
//myThread priority to MAX, however, this does not change mainT to 10
}Question 1), why if main Thread is set to a certain priority, the thread it creates automatically change its priority to the same as well, but the reverse is different??
Situation 2) this is slightly more complex
public class ImplementingRunnable {
public static void main(String[] args) {
Thread mainT = Thread.currentThread();
for(int ii=0 ; ii<args.length ; ii++) {
Runnable r = new MyRunnable(args[ii]);
Thread t = new Thread(r);
t.setDaemon(true);
//t.setPriority(Thread.MAX_PRIORITY);
t.start();
}and
public class MyRunnable implements Runnable {
public void test(){
System.out.println("test");
String message;
public MyRunnable(String msg) {
message = msg;
public void run() {
Thread me = Thread.currentThread();
try {
for(int ii=0 ; ii<10 ; ii++) {
//case (1) me.setPriority(Thread.MIN_PRIORITY);
me.sleep(3);
System.out.println(message);
//case (2) me.setPriority(Thread.MIN_PRIORITY);
} catch (InterruptedException ie) {
}In class ImplementingRunnable, how is the commented code line related or counter-related with the commented case 1 code line in MyRunnable??
Please help
thanksLet me speak my question again very simply:
1)
Say I have two threads, 1 is main() thread, the program entry point, 2 is another thread created by main().
Now, the default priority for both two is 5. If I change the priority for main() to a certain level, the other thread created by it automatically change its priority to the same level? why? and however, the reverse (in this case, if I change the priority for the thread created by main()) is not.
2)
public class Demo{
static class MyThread implements Runnable{
public void run(){//some thing}
Thread t = new Thread(this);
t.setPriority(10);
public static void main(String[] afd){
Runnable r = new MyThread();
Thread t1 = new Thread(r);
t1.setPriority(1);
}What can you say about both bold code lines?
If I use println() to track the Priority, the final priority, that is, t1, is 1. It is logical, however, the program behaves differently without the bold code line in the static class MyThread, despite the final priority for t1, is the same, 1.
Any help by now??
thanks alot -
The WMFS Thread (Window Manager From Scratch)
As the wmfs user community is growing, jasonwryan and myself though about the creation of a special thread for that tiling manager. The aim of this thread is to share informations and config files of wmfs to help new user to start with it,
So just ask whatever and enjoy using wmfs !One wmfs fellow (Alm) wrote a nice python script for the status, here it is :
#!/usr/bin/python2
# -*- coding: UTF-8 -*-
import urllib
import imaplib
import os
import signal
import time
import re
import math
from datetime import datetime, timedelta
from mpd import MPDClient, ConnectionError
from subprocess import Popen, PIPE
### configuration
g_users = [ ['[email protected]', 'PASSWD'] ]
g_weather = 'chvs0003'
g_cores = 2
g_iface = 'wlan0'
g_wm = 'wmfs'
### formatting for wmfs
g_fmt_weather = '\\#4A4A4A\\C\\#0081DE\\{0}'
g_fmt_gmail = '\\#4A4A4A\\@\\#AA4499\\{0}'
g_fmt_mpd = '\\#FFC400\\{0}'
g_fmt_mixer = '\\#0081DE\\{0}'
g_fmt_cpu = '\\#4A4A4A\\{0:d}\\#FFCC00\\{1:d}'
g_fmt_mem = '\\#AA2233\\{0:d}M'
g_fmt_eth = '\\#4A4A4A\\wlan\\#FFCC00\\{0:d}/{1:d}'
### classes ###
class Wi(object):
def __init__(self, format = ''):
self._val = ''
self._fval = ''
self._fmt = format
def format(self):
self._fval = self._fmt.format(self._val)
return self._fval
class WiWeather(Wi):
_url = 'http://www.meteomedia.com/weather/{0}'
def __init__(self, area_code, format = ''):
Wi.__init__(self, format)
self._url = self._url.format(area_code)
self._fmt = format
def update(self):
contents = urllib.urlopen(self._url).read()
temp = re.search("<p>([-0-9]*)<\/p>", contents).group(1)
felt = re.search("</strong>: ([-0-9]*).*</li>", contents).group(1)
if felt == '-':
out = temp
else:
out = temp + '/' + felt
if len(out) >= 1:
self._val = out
self.format()
return 0
else:
return 61 # if failed, wait ~1min before retrying
class WiGmail(Wi):
_delimiter = '/'
_mailbox = 'INBOX'
_mailserver = 'imap.gmail.com'
_port = 993
def __init__(self, users, format = ''):
Wi.__init__(self, format)
self._users = users
def fetch(self, username, password):
# set up connection
server = imaplib.IMAP4_SSL(self._mailserver, self._port)
server.login(username, password)
server.select(self._mailbox)
# get + clean
data = str(server.status(self._mailbox, '(MESSAGES UNSEEN)'))
count = data.split()[5].replace(')\'])','')
server.close()
server.logout()
return count
def update(self):
out = ''
for u, p in self._users:
s = self.fetch(u, p)
if s == '':
return 31 # if failed wait ~30 seconds before retrying
if out == '':
out += s
else:
out += self._delimiter + s
self._val = out
self.format()
return 0
class WiMpd(Wi):
def __init__(self, host = 'localhost', port = '6600', format = ''):
Wi.__init__(self, format)
self._host = host
self._port = port
self._con_id = {'host':host, 'port':port}
self._client = MPDClient()
self._connected = False
self.connect()
def connect(self):
try:
self._client.connect(**self._con_id)
except IOError as e:
print(e)
return False
except ConnectionError as e:
print(e)
return False
else:
self._connected = True
return True
def update(self):
if not self._connected:
if not self.connect():
return 1
st = self._client.status()
if st['state'] == 'play' or st['state'] == 'pause':
so = self._client.currentsong()
self._val = "%s - %s" % (so['artist'], so['title'])
else:
self._val = ''
self.format()
return 0
class WiMixer(Wi):
def __init__(self, args = ["amixer","sget","Master"], format = ''):
Wi.__init__(self, format)
self._args = args
pass
def update(self):
p = Popen(self._args, stdout=PIPE).communicate()[0]
out = re.search("([0-9]*%)",p).group(1)
mute = re.search("(\[[onf]*\])",p).group(1)
if mute == "[off]":
self._val = 'mute'
else:
self._val = out
self.format()
return 0
class WiCpu(Wi):
def __init__(self, cores = 2, format = ''):
Wi.__init__(self, format)
self._cores = cores
self._total = [0]*cores
self._active = [0]*cores
def format(self):
self._fval = ''
for i in list(range(self._cores)):
self._fval += self._fmt.format(i+1, int(self._val[i]))
return self._fval
def update(self):
usage = [0]*self._cores
for line in open("/proc/stat"):
r = re.search("^cpu([0-9])",line)
if r is None:
continue
n = int(r.group(1))
#space to avoid matching the first digit (cpuN)
s = re.findall(" ([0-9]+)",line)
total_new = 0
for i in s:
total_new += float(i)
active_new = float(s[0]) + float(s[1]) + float(s[2])
diff_total = total_new - self._total[n]
diff_active = active_new - self._active[n]
usage[n] = math.floor(diff_active / diff_total * 100)
#store totals
self._total[n] = total_new
self._active[n] = active_new
self._val = usage
self.format()
return 0
class WiMem(Wi):
def __init__(self, format = ''):
Wi.__init__(self, format)
def update(self):
for line in open("/proc/meminfo"):
r = re.search("([a-zA-Z]+):[^0-9]+([0-9]+).+",line)
if r is None:
continue
m = r.group(1)
n = int(r.group(2))
if m == "MemTotal":
total = n
elif m == "MemFree":
free = n
elif m == "Buffers":
buf = n
elif m == "Cached":
cached = n
break
self._val = int((total - free - buf - cached)/1024)
self.format()
return 0
class WiEth(Wi):
def __init__(self, iface = 'wlan0', format = ''):
Wi.__init__(self, format)
self._iface = iface
self._rx = 0
self._tx = 0
self._time = 0
def format(self):
self._fval = self._fmt.format(int(self._val[0]),int(self._val[1]))
return self._fval
def update(self):
for line in open("/proc/net/dev"):
r = re.search("wlan0", line)
if r is None:
continue
s = re.findall(" ([0-9]+)", line)
rx = int(s[0])
tx = int(s[8])
now = time.time()
interval = now - self._time
rx_rate = (rx - self._rx) / interval / 1024
tx_rate = (tx - self._tx) / interval / 1024
self._val = [rx_rate, tx_rate]
#store results
self._rx = rx
self._tx = tx
self._time = now
self.format()
return 0
class Task(object):
def __init__(self, func, name, delay, args=()):
self._args = args
self._function = func
self._name = name
micro = int((delay - math.floor(delay)) * 1000000)
self._delay = timedelta(seconds=int(delay), microseconds=micro)
self._next_run = datetime.now() #to force first run now
def should_run(self):
return datetime.now() >= self._next_run
def run(self):
delay = self._function(*(self._args))
if delay == 0:
self._next_run = datetime.now() + self._delay
else:
self._next_run = datetime.now() + timedelta(seconds=delay)
### signals ###
# to print stats
def sig_usr1(signum, frame):
global tasks
now = datetime.now()
for t in tasks:
print(t._name + " will run in " + str(t._next_run - now))
return
# to force execution
def sig_usr2(signum, frame):
global tasks
for t in tasks:
t.run()
return
signal.signal(signal.SIGUSR1, sig_usr1)
signal.signal(signal.SIGUSR2, sig_usr2)
### main ###
gm = WiGmail(g_users, format=g_fmt_gmail)
we = WiWeather(g_weather, format=g_fmt_weather)
mp = WiMpd(format=g_fmt_mpd)
mi = WiMixer(format=g_fmt_mixer)
cp = WiCpu(g_cores, format=g_fmt_cpu);
me = WiMem(format=g_fmt_mem);
et = WiEth(g_iface, format=g_fmt_eth);
tasks = [ Task(gm.update,'gmail',91), Task(we.update,'weather',1801), Task(mp.update,'mpd',1), Task(mi.update,'mixer',1), Task(cp.update,'cpu',2), Task(me.update,'mem',13), Task(et.update,'net',2) ]
while True:
try:
for t in tasks:
if t.should_run():
t.run()
now = datetime.now().strftime("%e/%m %H:%M")
os.system('wmfs -s "%s %s %s %s %s %s %s \\#AA4499\\ %s"' % (cp._fval,me._fval,et._fval,gm._fval,we._fval,mp._fval,mi._fval,now) )
except IOError as e:
print(e)
except Exception as e:
print(e)
finally:
time.sleep(1)
Last edited by aleks223 (2010-12-30 18:00:35) -
Hi,
I would like to implement a server code and change the priority value for each type of messages that receive from each client, simply I have two type of messages send it by the client the client will send multiple messages say 10 messages and receive the answer from the server OK or NO, each message will take 100 millisecond to process. I identify timer for low priority message that will increase the priority by one each second if that message still not process. My code as the following
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.lang.Object;
import java.io.Serializable;
import javax.swing.Timer;
class Serve extends Thread {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
private static int p1;
private Timer t ;
public Serve(Socket ss,ObjectInputStream objin, ObjectOutputStream objout
)throws IOException
in =objin ;
out = objout;
socket =ss;
start();
}//end constructor
public synchronized void run() {
final int DELAY = 1000;
try {
while (true) {
try{
Object str = in.readObject();
if (str.equals("END")){
break;
if ( str.equals("message1"))
try{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Thread.sleep((int) (Math.random() * 100 + 1));//time to process
out.writeObject("OK");
out.flush();
}catch(Exception ioEx1){}
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);//return to norm priority after process
} //end if payment requests
else if(str.equals("message2"))
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
p1=Thread.currentThread().getPriority();
//give chance to increase the priority every second if still not process
ActionListener listener = new ActionListener()
public void actionPerformed(ActionEvent event)
System.out.println("increase priority ");
Thread.currentThread().setPriority(p1+1);
t = new Timer(DELAY, listener);
t.start();
try{
Thread.sleep((int) (Math.random() * 100 + 1));
out.writeObject("NO");
}catch(Exception ioEx1){}
}catch(Exception e) {}
}//end while
System.out.println("closing...");
}//end try
catch(Exception e) {}
finally {
try {
socket.close();
t.stop();
System.out.println(",,,,,,Socket closed...");
} catch(IOException e) {
System.err.println("Socket not closed");
public class s {
public static Thread t;
public static int x=0;//number of client
public static void main(String[] args) throws IOException {
ObjectOutputStream out;
ObjectInputStream in;
ServerSocket s = new ServerSocket(3555);
System.out.println("Server Started");
try{
while(true) {
// Blocks until a connection occurs:
Socket socket = s.accept();
x++;
System.out.println("after s.accept");
try {
out= new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
t= new Serve (socket, in, out);
System.out.println("new ServerOne ");
} catch(IOException e) {
// If it fails, close the socket,
// otherwise the thread will close it:
socket.close();
}//end catch
}//end while
finally {
s.close();
} The priority here will not become more than 5 even I put static in p1 definition ,and the timer will continue although I stop him after I close the socket. please any help???Doubly posted [On this site|http://forums.sun.com/thread.jspa?threadID=5390894] and cross posted [On another site|http://en.allexperts.com/q/Adobe-Framemaker-1523/2009/6/Timer-mulltiple-threads.htm].
We asked you to be clear and open when multi-posting. We told you why. Yet you still do it without being forthright. -
Hi,
I have some JNI code that spawns a win32 thread using CreateThread and then sets it priority using SetThreadPriority.
If i set priority higher than ABOVE_NORMAL ( i would prefer time critical), it seems the JVM crashes on exit.
I've commented everything out in the thread method itself except to let it do a while(true){Sleep(1);}.
If i remove the SetThreadPriority or set it to ABOVE_NORMAL or less the JVM doesnt crash when the java code calls System.exit but otherwise it does.
Any ideas concerning this?Hmm..
I was using System.runFinalizersOnExit(true), when i removed that from the java side the problem disappeared. I dont really need to make that call anyway, but i dont like when errors disappears and i dont understand why, so i would like to know how that call in conjunction with a high priority native thread can cause a jvm crash? -
A good design for a single thread pool manager using java.util.concurrent
Hi,
I am developing a client side project which in distinct subparts will execute some tasks in parallel.
So, just to be logorroic, something like that:
program\
\--flow A\
\task A1
\task A2
\--flow B\
\task B1
\task B2
\...I would like both flow A and flow B (and all their launched sub tasks) to be executed by the same thread pool, because I want to set a fixed amount of threads that my program can globally run.
My idea would be something like:
public class ThreadPoolManager {
private static ExecutorService executor;
private static final Object classLock = ThreadPoolManager.class;
* Returns the single instance of the ExecutorService by means of
* lazy-initialization
* @return the single instance of ThreadPoolManager
public static ExecutorService getExecutorService() {
synchronized (classLock) {
if (executor != null) {
return executor;
} else {
// TODO: put the dimension of the FixedThreadPool in a property
executor = Executors.newFixedThreadPool(50);
return executor;
* Private constructor: deny creating a new object
private ThreadPoolManager() {
}The tasks I have to execute will be of type Callable, since I expect some results, so you see an ExecutorService interface above.
The flaws with this design is that I don't prevent the use (for example) of executor.shutdownNow(), which would cause problems.
The alternative solution I have in mind would be something like having ThreadPoolManager to be a Singleton which implements ExecutorService, implementing all the methods with Delegation to an ExecutorService object created when the ThreadPoolManager object is instantiated for the first time and returned to client:
public class ThreadPoolManager implements ExecutorService {
private static ThreadPoolManager pool;
private static final Object classLock = ThreadPoolManager.class;
private ExecutorService executor;
* Returns the single instance of the ThreadPoolManager by means of
* lazy-initialization
* @return the single instance of ThreadPoolManager
public static ExecutorService getThreadPoolManager() {
synchronized (classLock) {
if (pool !=null) {
return pool;
} else {
// create the real thread pool
// TODO: put the dimension of the FixedThreadPool in a property
// file
pool = new ThreadPoolManager();
pool.executor = Executors.newFixedThreadPool(50);
// executor = Executors.newCachedThreadPool();
return pool;
* Private constructor: deny creating a new object
private ThreadPoolManager() {
/* ======================================== */
/* implement ExecutorService interface methods via delegation to executor
* (forbidden method calls, like shutdownNow() , will be "ignored")
// .....I hope to have expressed all the things, and hope to receive an answer that clarifies my doubts or gives me an hint for an alternative solution or an already made solution.
ciao
AlessioTwo things. Firstly, it's better to use private static final Object classLock = new Object();because that saves you worrying about whether any other code synchronises on it. Secondly, if you do decide to go for the delegation route then java.lang.reflect.Proxy may be a good way forward.
-
Assigning Thread priority according to CPU Usage
I have a solaris server with several Applications running on different JREs
As most of the time the CPU utilization is high, I am planning to change the priority of some of the tasks to lower from default, so that the High priority tasks can go ahead and finish their task execution.
Please let me know using in Java how can I achieve that? Is it possible for Java to determine the priority of execution even though several JREs are involved?
Thanks in advance,
-AjayFirst thanks to everyone providing me lots of information regarding OS & Java internals
The problem that I am facing is,
There are multiple applications running on one Solaris box say Application-1 and Application-2. Now due several design holes Application-1 eating up most of the CPU cycles(Not all the time but during upgrades, reporting etc) Please note Application-1 need to run no matter whether it is eating CPU or not.
Now Application-2 is having two sub component
1. Reading binary data from several clients (High priority task)
2. Parsing those data(well performance tuned java code with high CPU utilization)
In this above scenario if Application-2 sub component (2) runs along with Application-1 which consumes most of the CPU cycle then the whole system will be state to function.
I know the answer will be to tune the code which eats the max CPU and fix the problem, but you need to consider this is one application of 7 years age and still the development is happening on top it.
So only possible solution from my side to isolate the component I can reduce the priority of execution and wait till the component which can not be get delayed processing. Means yield Application-2 sub component – 2 for Application-1 to complete its processing.
Sounds strange right? But I am not finding any other ways to solve this issue immediately
So the solution I figured out is to have a component to check the System recourse Utilization and yield Application-2 sub component-2 till have enough CPU to proceed(Again I know it really a bad way to solve an issue) -
Unable to change the thread's priority at linux jdk6
i try to set the thread's priority to value like Thread.MIN_PRIORITY
i observe the thread's priority by "threadump"
the setting is ok at windows (XP + jdk5 build 1.5.0_12-b04)
but not at linux jdk6 (build 1.6.0_04-b12)
at linux, i see all threads at my server are with priority "10"
(e.g. gc, finalizer, http listener etc)
i am using tomcat (running as root), i have tried to set the "default thread priority", but still can't change the thread's priority
and i have tried to add jvm options to "turn on" thread priority:
-XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=1
but still no use
so i guess this should be a problem of "linux" or jvm
is there any hint if it is about jvm problem?
thanksHi David,
>
> > #com.sapportals.wcm.repository.manager.reporting.RPRepositoryManager#sap.com/irj#com.sapportals.wcm.repository.manager.reporting.RPRepositoryManager#Guest#0##n/a##9056c970715111de8591000c2942fce3#SAPEngine_Application_Thread[impl:3]_14##0#0#Error##Plain###setting initial ACL on /reporting_backend/reports/Content Administration/User related Cleanup/actioninbox.cleanup - com.sap.security.api.NoSuchRoleException: Role with uniqueName content_admin_role not found!
> at com.sap.security.core.imp.RoleFactory.getRoleByUniqueName(RoleFactory.java:1783)
> at com.sapportals.wcm.repository.RMAdapter.getResource(RMAdapter.java:228)
> at com.sapportals.wcm.repository.runtime.CmAdapter.findResource(CmAdapter.java:1349)
> at com.sapportals.portal.prt.dispatcher.Dispatcher.initDispatcher(Dispatcher.java:361)
>
Have you check this content_admin_role not found ?
Thanks
Sunny
Maybe you are looking for
-
How to convert String (dd-MMM-yyyy) to oracle.jbo.domain.Date
Hi Could you please tell how do I convert String of date in format dd-MM-yyyy to ADF date? Please show me some sample. Thanks
-
Hi all, we have a customer with UCCE 8.0.2, we are facing an issue that at Side-B Router Ccagnet process it shows "inservice" status but doesn't show any PG out of 3 configured and when we check the CCM PG and VRUPG status it shows "Not Active". Eve
-
My computer died and I had to reset it with factory presets. Downloaded Itunes But now I have music on iphone and if I sync it with itunes it will delete all my music. How can I get my music back on itunes.
-
High CPU usage for Mail/Address Book with Exchange/GMail
I reinstalled 10.6 on my MacBook Pro because it since the upgrade from 10.5 performance has been generally lousy and I wanted to make a fresh start. I am finding that my performance problems with Mail (which connects to both Gmail and Exchange) is st
-
I have a wierd problem, when I use aperture now, I can't see the main window. If I use expose to see all windows, I can see the aperture main window, but when I click on it the window goes away. Its kind of like a reverse expose. Totally wierd. This