Blocking I/O thread

I know that a thread can be blocked on an I/O operation? I/O can block a thread for a considerable amount of time, particularly if network communication is involved. For example, a server may be waiting for a request, or a network application may be waiting for an answer from a remote host.
Now my question is that while the thread is blocked, the processor is still doing some work, so on a single processor machine, during the I/O block would another thread start working or would it be a more sequential env still.

I'm not entirely sure if I understand your question, but I give it a try:
It's entirely possible and quite common that one thread is waiting for I/O and other threads of the same (or another) JVM keep running. That's one of the reasons why many servers use one thread per client. It doesn't matter if the machine has only a single CPU or multiple in this context.

Similar Messages

  • How to blocks the main thread

    Hello,
    I have a multi-threaded application but the main thread doesnt blocks the application so the application quits just after started. Im using this code to block the main thread:
    /*BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    for(;;) {
    try {
    r.readLine();
    catch (IOException e) {
    I tryed to just use for(;;){} but it causes 100% of CPU using. This code above its very dangerous because sometimes System.in blocks the entire application (all threads)
    Thanks a lot

    This application its a socket server, Im doing:
    main {
    Thread1 - createServer();
    Thread2 - createLogging();
    waitForServerShutDown();
    the createServer method must be placed in a thread, its must not blocks the application because createLogging(); must be executed just after the server was created and createLogging(); doesnt blocks the application then... I must block the main{} to keeps application running

  • HttpConnection blocking ALL MIDlet threads?

    Hi there,
    Geez, I am pretty depressed as I seem to be too incompetent to implement the most basic HttpConnection use case. My MIDlet needs to issue a single HTTP POST request during the complete MIDlet lifetime. Pretty basic, one should think. I spawn a main thread for the MIDlet, from the main thread I spawn a thread for the HTTP connection. However, once the connection thread blocks, the main thread seems to block, too. Let me give you some minimal code that reproduces this behaviour.
    Here's the MIDlet. It simply creates the main thread in startApp().
    import javax.microedition.midlet.MIDlet;
    public class Connection extends MIDlet
         protected void destroyApp(boolean force)
         protected void pauseApp()
         protected void startApp()
              System.out.println("Starting main thread");
              new Thread(new MainThread()).start();
    }Here's the main thread. It just creates the connection thread and then either sleep()s for 5000 ms or wait()s for 5000 ms. It also measures how long the sleep() or wait() actually took. The idea is to go back to the user after the timeout and tell him/her, sorry, it did not work out. That's enough for me. I don't even have to shut down the connection thread.
    public class MainThread implements Runnable
         private synchronized void waitFor5000ms()
              try
                   wait(5000);
              catch (InterruptedException ex)
                   ex.printStackTrace();
         private void sleepFor5000ms()
              try
                   Thread.sleep(5000);
              catch (InterruptedException ex)
                   ex.printStackTrace();
         public void run()
              System.out.println("Main thread method entered, now starting HTTP thread");
              new Thread(new HttpThread()).start();
              System.out.println("HTTP thread started, now waiting for 5000 ms");
              long startTime = System.currentTimeMillis();
              if (true)
                   waitFor5000ms();
              else
                   sleepFor5000ms();
              long duration = System.currentTimeMillis() - startTime;
              System.out.println("Waited for 5000 ms, which took us " + duration + " ms");
    }And here's the code for the connection thread. For the sake of brevity it only contains the statements that are required to reproduce the problem. I am deliberately using an IP address that does not exist in my test network to see how my code behaves under this error condition.
    import java.io.IOException;
    import java.io.OutputStream;
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    import javax.microedition.io.StreamConnection;
    public class HttpThread implements Runnable
         public void run()
              try
                   System.out.println("Connection thread method entered, now opening connection");
                   StreamConnection streamConnection = (HttpConnection)Connector.open("http://192.168.123.234/blah.html");
                   System.out.println("Connection opened, now setting request method");               
                   ((HttpConnection)streamConnection).setRequestMethod(HttpConnection.POST);
                   System.out.println("Request method set, now opening output stream");
                   OutputStream out = streamConnection.openOutputStream();
                   System.out.println("Opened output stream, now writing byte");
                   out.write(0);
                   System.out.println("Wrote byte, now flushing output stream");
                   out.flush();
              catch (IOException ex)
                   ex.printStackTrace();
    }So, here's how the code behaves. The out.flush() method invocation in the connection thread blocks, as it causes the HTTP connection to get established. HOWEVER, the main thread blocks, too. So, the sleep() or wait() does not take about 5000 ms, but more than 20000 ms. The main thread seems to only continue executing once out.flush() returns. Bizarre. Here's the output of the MIDlet. It is basically the same for WTK 2.2 (Windows and Linux), WTK 2.5.1 (Windows), and the SonyEricsson SDK 2.2.4 (Windows).
    Running with storage root temp.DefaultColorPhone44
    Running with locale: English_United States.1252
    Running in the maximum security domain
    Starting main thread
    Main thread method entered, now starting HTTP thread
    HTTP thread started, now waiting for 5000 ms
    Connection thread method entered, now opening connection
    Connection opened, now setting request method
    Request method set, now opening output stream
    Opened output stream, now writing byte
    Wrote byte, now flushing output stream
    javax.microedition.io.ConnectionNotFoundException: TCP open
         at com.sun.midp.io.j2me.socket.Protocol.connect(+99)
         at com.sun.midp.io.ConnectionBaseAdapter.openPrim(+52)
         at com.sun.midp.io.j2me.socket.Protocol.openPrim(+108)
         at com.sun.midp.io.ConnectionBaseAdapter.openPrim(+14)
         at com.sun.midp.io.ConnectionBaseAdapter.openPrim(+8)
         at com.sun.midp.io.j2me.http.Protocol.connect(+73)
         at com.sun.midp.io.j2me.http.Protocol.streamConnect(+57)
         at com.sun.midp.io.j2me.http.Protocol.startRequest(+12)
         at com.sun.midp.io.j2me.http.Protocol.sendRequest(+38)
         at com.sun.midp.io.j2me.http.Protocol.flush(+36)
         at com.sun.midp.io.BaseOutputStream.flush(+11)
         at HttpThread.run(+76)
    Waited for 5000 ms, which took us 21000 ms
    Execution completed.
    3423649 bytecodes executed
    354 thread switches
    1669 classes in the system (including system classes)
    17953 dynamic objects allocated (546852 bytes)
    3 garbage collections (465956 bytes collected)
    I must be missing something pretty obvious as this is really pretty basic, isn't it? Any thoughts?
    Thanks,
    Thomas

    Hey sailesh_dit,
    Thanks for confirming this problem. So, it seems more and more to me that this is a general problem with at least some VMs and/or WTKs and not my fault. My current guess is that a blocking native call messes up the VM. Maybe I should open another thread with this as a subject.
    I was just a bit surprised that this wasn't discussed anywhere. Everywhere I read "Run your networking code in a separate thread!" and nobody seemed to have run into problems with this approach, which left me a little confused. So, it is good to hear that you've also experience this problem.
    Thomas

  • Db- put blocks sometimes, mulit-thread uses Db- put to write DB file

    My environment : redhat Linux 5, gcc version 4.1.2
    BDB version: 4.8.24
    Hi Guys
    I used multi-thread application to write DB file. The application used Transactional Data Store and I used flags DB_TXN_NOSYNC . The DB file type is BTREE. I give 180M for the buffer cache and 8M for the log cache. And I used Db->put to write DB file ; five threads is used.
    But the Db->put will block for one or two seconds sometimes.
    Now I have found that the problem is in the  lock/lock.c :: __lock_get_internal , line 953 :  MUTEX_LOCK(env, newl->mtx_lock);. My application blocks here .+_
    Could anyone give me some advice to avoid these blocks as possible as we can?
    By the way, I have tried many of the lock set APIs which BDB offered. No effect -_- .
    Thanks

    Hi,
    You should have posted this new piece of information in the original thread you opened:
    Db->put block sometimes , when mulit-thread uses Db->put to write DB file
    In the future please do not open a new thread for a problem you already reported.
    Now I have found that the problem is in the  lock/lock.c :: __lock_get_internal , line 953 :  MUTEX_LOCK(env, newl->mtx_lock);. My application blocks here .+_This only confirms that one of your threads is blocked waiting for a requested lock, which is already held by another thread. Until the thread that holds the lock will not have released it, your thread waiting on it will not make progress.
    You can collect the locking statistics at the moment you observe the slowness using either the db_stat utility with the -CA or -Co options (if the environment is not opened with DB_PRIVATE, that is, backing its region files into per-process private/heap memory) or programmatically using DB_ENV->lock_stat_print():
    [http://www.oracle.com/technology/documentation/berkeley-db/db/api_reference/C/db_stat.html]
    [http://www.oracle.com/technology/documentation/berkeley-db/db/api_reference/C/lockstat_print.html]
    Examining the locking statistics will help determine what is the problematic lock, what is the locked object and which thread is holding it.
    In addition to standard deadlock detection you can look into configuring lock timeouts. If your lock request is not satisfied within a given time it will time out and return DB_LOCK_DEADLOCK or DB_LOCK_NOTGRANTED. Lock timeouts may be configured per environment wide basis or per-lock or per-transaction basis:
    [http://www.oracle.com/technology/documentation/berkeley-db/db/programmer_reference/lock_timeout.html]
    [http://www.oracle.com/technology/documentation/berkeley-db/db/gsg_txn/C/lockingsubsystem.html#configdeadlkdetect]
    As Mike already suggested it would help if you could put together a test case program to demonstrate this issue.
    Regards,
    Andrei

  • Multiple non-blocking selectors in threads

    About networking in java and sockets i read alot. I know about the 2 implementations witk thread per client and non-blocking IO (usage of select()). I ran a few tests of my own and i could't decide. So I wrote a server that uses them both. The Ideea is to have no more than 100 clients per each selector and each selector runs in a thread. so when you have 4000 clients you actualy have 40 threads running each 100 clients:D
    However I'm stuck. I wrote this piece of code that has 2 objects one work thread with his own selector and a main thread with an accepting selector. The problem is that when I connect to it via telnet it only works when there is an even number of clients:(( when client nr 1 connects it blocks on channel.register(workSelector,SelectionKey.OP_READ);when client 2 gets connected it works:((
    HELP!!!
    here is the
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.charset.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    //work thread with own selector
    class workThread implements Runnable{
         public int userCount=0;
         public int ID=0;
         private Charset charset;
         private CharsetEncoder encoder;
         private CharsetDecoder decoder;
         private ByteBuffer buffer;
         private ConcurrentHashMap userMap;
         public Selector workSelector = null;
         public void addClient(SelectableChannel channel, int ops) throws IOException{
              if (channel == null) return;
              //channel.configureBlocking(false);
              System.out.println("Channel was added in workSelector : "+channel);
              channel.register(workSelector,SelectionKey.OP_READ);
              System.out.println("Client was added in work selector : " + ID);
              userCount++;
              System.out.println("Client nr : "+userCount);
         public boolean find(String name){
              return true;
         public workThread() throws IOException{
              charset = Charset.forName("ISO-8859-1");
              encoder = charset.newEncoder();
              decoder     = charset.newDecoder();     
              buffer = ByteBuffer.allocate(256);
    //          System.out.println("S-a creat selectorul");
              workSelector = Selector.open();
              System.out.println("Selector open ");
         private void doRead(SelectionKey key) throws IOException{
              SocketChannel clientChannel = (SocketChannel)key.channel();
              buffer.clear();
              System.out.println("Speaking to client");
              if(clientChannel.read(buffer) == -1){
                   key.cancel();
                   clientChannel.close();
              }else{
                   buffer.flip();
                   String message = decoder.decode(buffer).toString();
                   System.out.println(message);
                   if(message.trim().equals(".")){
                        clientChannel.write(encoder.encode(CharBuffer.wrap("BYE")));
                        key.cancel();
                        clientChannel.close();
                   }else{
                        buffer.flip();
                        clientChannel.write(buffer);
         private void doWrite(SelectionKey key){
              System.out.println("WRITE!!!");
         public void run(){
              while(true){
                   try{
                   if(workSelector.select() > 0){
                        Set keys1 = workSelector.selectedKeys();
                        for(Iterator itr = keys1.iterator();itr.hasNext();){
                             SelectionKey key = (SelectionKey)itr.next();
                             itr.remove();
                             if(key.isReadable()) {doRead(key);}
                        //     if(key.isWritable()) {doWrite(key);}
              }catch(IOException e){
                   System.out.println("Error in workthread "+ID+" "+e);
    //main thread
    public class msselect implements Runnable{
         private ServerSocketChannel server;
         private ServerSocket sock;
         private Selector acceptSelector;
         private workThread wk;
         public static void main(String args[]){
              try{
              msselect x = new msselect("80.97.89.73",6500,5);
              new Thread(x).start();
              }catch(IOException ex){
                   System.out.println("Probleme"+ex);
         msselect(String host, int port, int numT) throws IOException{
              server = ServerSocketChannel.open();
              sock = server.socket();
              sock.bind(new InetSocketAddress(port));
              server.configureBlocking(false);
              acceptSelector = Selector.open();
              server.register(acceptSelector, SelectionKey.OP_ACCEPT);
    /*          for(int i=0;i<numT;i++){
                   wk[i] = new workThread();
                   wk.ID = i;
                   new Thread(wk[i]).start();
              wk = new workThread();
              wk.ID = 1;
              server.register(wk.workSelector, SelectionKey.OP_ACCEPT);
              new Thread(wk).start();
         public void run(){
              while(true){
                   try{
                   acceptSelector.select();
                   Set keys = acceptSelector.selectedKeys();
                   for(Iterator itr = keys.iterator();itr.hasNext();){
                        SelectionKey key = (SelectionKey)itr.next();
                        itr.remove();
                        if(key.isAcceptable()){
                             SocketChannel client = null;
                             client = server.accept();
                             client.configureBlocking(false);
                             System.out.println("Accepted "+client);
                             wk.addClient(client,SelectionKey.OP_READ);
              }catch(IOException e){
                   System.out.println("Main Thread error"+e);

    I compiled and ran your code.
    The call channel.register(...) should block while selector is blocked in workSelector.select(). The fact that the registration succeeds is that you registered the server channel with both the work selector and the acceptor selector. The work selector is returning from select() because of a new client connection is accepted and is a matter of thread scheduling that the client.register() succeeeds (but only sometimes).
    Possible solution:
    - don't register the server channel with the work selector;
    - probably call workSelector.wakeup() to make the client channel registration possible.

  • Blocking the EventDispatcher thread

    Hi,
    Some times, when I click on a menu item, I see a grey area underneath the menu pop-up.
    Probably, I am blocking the event dispatching thread.
    So , I am using the update method to overcome this ..
    e.getSourceTree().update(e.getSourceTree().getGraphics());
    But still, it doesnot seem to be working at times. Especially, when the menu popup appears on some other component, the overlapping area appears greyed.
    I even tried using SwingUtil.invokeLater but that does not seem to be working fine.
    Please advice.
    The code is pasted here...
    public void performTreeAction(XmlTreeEvent e) {
              e.getSourceTree().update(e.getSourceTree().getGraphics());
                   if((e.getActionType()!=null && e.getUiForm()!=null
                   && e.getUiMode()!=null ) && (e.getActionType().equals("ui"))) {
              // I load the form here ****************
                   else if(e.getActionType()!=null && e.getActionType().equalsIgnoreCase("command") && e.getActionCommand()!=null) {
                        if(e.getActionCommand().equalsIgnoreCase("Reload")) {
                             // I refresh the tree here
         }

    Swing and Thread handling...
    http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

  • Question About Java Threads and Blocking

    I'm helping someone rehost a tool from the PC to the Sun. We're using the Netbeans IDE and the Java programming language. I took a Java course several years ago, but need some help with something now. We're developing a front-end GUI using Swing to allow users to select different options to perform their tasks. I have a general question that will apply to all cases where we run an external process from the GUI. We have a "CommandProcessor" class that will call an external process using the "ProcessBuilder" class. I'm including the snippet of code below where this happens. We pass in a string which is the command we want to run. We also instantiate a class called "StreamGobbler" my coworker got off the Internet for redirecting I/O to a message window. I'm also including the "StreamGobbler" class below for reference. Here's the "CommandProcessor" class:
    // Test ProcessBuilder
    public class CommandProcessor {
    public static void Run(String[] cmd) throws Exception {
    System.out.println("inside CommandProcessor.Run function...");
    Process p = new ProcessBuilder(cmd).start();
    StreamGobbler s1 = new StreamGobbler("stdin", p.getInputStream());
    StreamGobbler s2 = new StreamGobbler("stderr", p.getErrorStream());
    s1.start();
    s2.start();
    //p.waitFor();
    System.out.println("Process Returned");
    Here's the "StreamGobbler" class:
    import java.lang.*;
    import java.io.*;
    // Attempt to make the output of the process go to the message window
    // as it is produced rather that waiting for the process to finish
    public class StreamGobbler implements Runnable {
    String name;
    InputStream is;
    Thread thread;
    public StreamGobbler (String name, InputStream is){
    this.name = name;
    this.is = is;
    public void start(){
    thread = new Thread (this);
    thread.start();
    public void run(){
    try{
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    while (true){
    String s = br.readLine();
    if (s == null) break;
    System.out.println(s);
    //messageWindow.writeToMessageArea("[" + name + "]" + s);
    is.close();
    catch(Exception ex){
    System.out.println("Problem reading stream" + name + "...:" + ex);
    ex.printStackTrace();
    The "CommandProcessor" class calls two (2) instances of the "StreamGobbler" class, one for "stdin" and one for "stderr". My coworker discovered these are the 2 I/O descriptors that are needed for the external command we're running in this case. We're actually called the Concurrent Versions System (cvs) command from the GUI. Here's what we need it to do:
    We want to display the output real-time as the external process is executing, but we want to block any actions being performed on the GUI itself until the process finishes. In other words, we want to show the user any generated output from the process, but don't want to alllow them to perform any other actions on the GUI until this process has finished. If we use the "waitFor()" function associated with a process, it blocks all external process output until the process has completed and then spews all the output to the screen all at once. That's NOT what we want. Also, if we don't use the "waitFor()" function, the code just continues on as it should, but we don't know how to block any actions on the GUI until this process has finished. My coworker tried the following code, but it also blocked any output until the process had finished:
    while (s1.thread.isAlive() || s2.thread.isAlive())
    // We really don't do anything here
    I'm pretty sure we have to use threads for the output, but how do we instantly show all output and block any GUI actions?
    Thank you in advance for your help!

    You're talking about a GUI, but there's nothing in that code which is putting events into the GUI update thread. You also say that nothing happens to the GUI until the CommandProcessor.Run() method returns if you wait for the process.
    This implies that you're calling CommandProcessor.Run() in an ActionListener. This will block the GUI thread until it completes.
    I was going to explain what to do, but a quick Google informed me that there's a new class which is designed to help in these situations SwingWorker (or as a [separate library|https://swingworker.dev.java.net/] if you're not up-to-date yet).

  • Blocking the applet and main threads ?

    The thread that runs the Applet callback methods like init() and start() is a thread named �applet-your.package.your.classname.class�.
    If I am doing a blocking method call, i.e. a method call that does not return immediately like doing I/O read on a socket connection, is it ok to do it on the thread mentioned above ? In other words, is it ok to hang/suspend/block the applet thread ?
    What about blocking the �main� thread that calls
    public static void main(String args[]) {�}
    Thanks.

    eminformatics, thanks for the reply.

  • Future.get and the event despatch thread blocking

    neeeyaaarghhhh
    been tying myself in knots thinking about this
    Following one of the java tech tips I've been using Callable and Future objects when I want to return a result from a task, in my case it's usually some file processing
    So I have a file chooser gui, I select a file and launch my Callable and await the result in Future.get...
    Now the problem is... Future.get I understand blocks the calling thread until the computation / work in the Callable is done and the result returned. In this case the blocked thread will be the event despatch thread... which causes problems as during my file reading I have a JProgressBar running and updating. Well at least I did, now it doesn't show up at all as all the updates to the JProgressBar via invokeLater are queued (as event despatch thread is blocked) until after the work thread has finished
    How do I launch a Callable, await the result and have some limited gui activity as the task progresses? The only solution I've found is to have the ProgressBar in a modal dialog, to block out the rest of the gui like this whilst I do the work in the event despatch thread (and drop the idea of threading altogether)
    Is my mental modal of how worker threads should spin off from the event thread flawed or am I just missing some 1 line command?

    In the situation of updating the gui, you usually want to pass some sort of callback object to the asynchronous code and have that callback method run on the gui event thread.
    public class GuiClass {
    public void handleResult(Object data);
    public void startTask() {
      threadpool.execute(new Runnable() {
        public void run() {
          // ... do asynch work ...
          final Object myResult = ...;
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              handleResult(myResult);
    }In this code, the startTask method is called on the gui thread. it starts some async work on the threadpool. when finished, the asynch task queues the result to be handled back on the gui thread. the handleResult method is called later on the gui thread with the final result. thus, no blocking of the gui thread.
    The Callable interface is great for when the invoking thread needs to wait for a result, but you pretty much never want to do this with the gui thread.

  • Db_checkpoint: Unable to allocate thread control block

    Hello,
    Every second day BDB 4.8 runs out of cache memory (size = 512MB).
    We have 10 static worker processes (no segfaults) and one
    db_checkpoint-process (checkpoints once a minute and exists).
    We use only DB_WRITE_NOSYNC
    After two days the db_checkpoint-process reports:
    db_checkpoint: Unable to allocate thread control block
    As soon as this error apears, I can neither checkpoint nor
    db_recover.
    Is there any chance (or a patch) to track down the memory leak?
    Thanks

    Hi Sandra,
    It happened again one hour ago. I had hardly problems with BDB 4.6
    Down below you will find a current "db_stat -e"
    We have 10 workers with persistent db-connection and once a minute
    a cronjob starts a checkpoint, then the cron-process exists.
    Every second day (40 to 48 hours) the checkpoint-process can't connect
    to the database and "db_checkpoint -1" says:
    db_checkpoint: Unable to allocate thread control block
    A normal "db_recover" would corrupt the database, I had to recover
    catastrophic.
    For sure the cache is not to small (512 MB, all database files: 1,3 GB)
    Thanks
    Markus
    Mon Nov 30 17:32:44 2009 Local time
    0x120897 Magic number
    0 Panic value
    4.8.24 Environment version
    9 Btree version
    9 Hash version
    1 Lock version
    15 Log version
    4 Queue version
    2 Sequence version
    1 Txn version
    Mon Nov 30 16:31:06 2009 Creation time
    0x9d316701 Environment ID
    2 Primary region allocation and reference count mutex [0/360 0% !Own]
    11 References
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    Thread tracking information
    75 Thread blocks allocated
    4096 Thread allocation threshold
    521 Thread hash buckets
    Thread status blocks:
    process/thread 5055/3086948768: out
    process/thread 5686/3086850464: out
    [...snip...]
    process/thread 6056/3086653856: out
    process/thread 6087/3086649760: out
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    0x40988 Log magic number
    15 Log version number
    16MB Log record cache size
    0 Log file mode
    10Mb Current log file size
    370618 Records entered into the log
    370MB 354KB 853B Log bytes written
    4MB 466KB 1001B Log bytes written since last checkpoint
    17691 Total log file I/O writes
    0 Total log file I/O writes due to overflow
    198 Total log file flushes
    665 Total log file I/O reads
    1786 Current log file number
    8303086 Current log file offset
    1786 On-disk log file number
    3630597 On-disk log file offset
    1 Maximum commits in a log flush
    1 Minimum commits in a log flush
    17MB Log region size
    9 The number of region locks that required waiting (0%)
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    5387 Last allocated locker ID
    0x7fffffff Current maximum unused locker ID
    9 Number of lock modes
    131072 Maximum number of locks possible
    131072 Maximum number of lockers possible
    131072 Maximum number of lock objects possible
    30 Number of lock object partitions
    622 Number of current locks
    797 Maximum number of locks at any one time
    13 Maximum number of locks in any one bucket
    0 Maximum number of locks stolen by for an empty partition
    0 Maximum number of locks stolen for any one partition
    632 Number of current lockers
    708 Maximum number of lockers at any one time
    69 Number of current lock objects
    160 Maximum number of lock objects at any one time
    2 Maximum number of lock objects in any one bucket
    0 Maximum number of objects stolen by for an empty partition
    0 Maximum number of objects stolen for any one partition
    13M Total number of locks requested (13372706)
    13M Total number of locks released (13372083)
    0 Total number of locks upgraded
    5313 Total number of locks downgraded
    9 Lock requests not available due to conflicts, for which we waited
    1 Lock requests not available due to conflicts, for which we did not wait
    0 Number of deadlocks
    60M Lock timeout value (60000000)
    0 Number of locks that have timed out
    60M Transaction timeout value (60000000)
    0 Number of transactions that have timed out
    66MB 904KB The size of the lock region
    2141 The number of partition locks that required waiting (0%)
    465 The maximum number of times any partition lock was waited for (0%)
    0 The number of object queue operations that required waiting (0%)
    3 The number of locker allocations that required waiting (0%)
    0 The number of region locks that required waiting (0%)
    2 Maximum hash bucket length
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    320MB 1KB 604B Total cache size
    1 Number of caches
    1 Maximum number of caches
    320MB 8KB Pool individual cache size
    0 Maximum memory-mapped file size
    0 Maximum open file descriptors
    0 Maximum sequential buffer writes
    0 Sleep after writing maximum sequential buffers
    0 Requested pages mapped into the process' address space
    17M Requested pages found in the cache (99%)
    71264 Requested pages not found in the cache
    67 Pages created in the cache
    71264 Pages read into the cache
    17944 Pages written from the cache to the backing file
    0 Clean pages forced from the cache
    0 Dirty pages forced from the cache
    0 Dirty pages written by trickle-sync thread
    71298 Current total page count
    71014 Current clean page count
    284 Current dirty page count
    32771 Number of hash buckets used for page location
    4096 Assumed page size used
    16M Total number of times hash chains searched for a page (16751183)
    8 The longest hash chain searched for a page
    39M Total number of hash chain entries checked for page (39437498)
    0 The number of hash bucket locks that required waiting (0%)
    0 The maximum number of times any hash bucket lock was waited for (0%)
    7 The number of region locks that required waiting (0%)
    0 The number of buffers frozen
    0 The number of buffers thawed
    0 The number of frozen buffers freed
    71627 The number of page allocations
    0 The number of hash buckets examined during allocations
    0 The maximum number of hash buckets examined for an allocation
    0 The number of pages examined during allocations
    0 The max number of pages examined for an allocation
    0 Threads waited on page I/O
    0 The number of times a sync is interrupted
    Pool File: article.db
    4096 Page size
    0 Requested pages mapped into the process' address space
    1868517 Requested pages found in the cache (99%)
    13311 Requested pages not found in the cache
    0 Pages created in the cache
    13311 Pages read into the cache
    3428 Pages written from the cache to the backing file
    [...snip...]
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    1786/3630541 File/offset for last checkpoint LSN
    Mon Nov 30 17:32:01 2009 Checkpoint timestamp
    0x8000675a Last transaction ID allocated
    4096 Maximum number of active transactions configured
    0 Active transactions
    3 Maximum active transactions
    26458 Number of transactions begun
    0 Number of transactions aborted
    26458 Number of transactions committed
    0 Snapshot transactions
    0 Maximum snapshot transactions
    0 Number of transactions restored
    1MB 192KB Transaction region size
    0 The number of region locks that required waiting (0%)
    Active transactions:
    =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
    31MB 32KB Mutex region size
    3 The number of region locks that required waiting (0%)
    4 Mutex alignment
    150 Mutex test-and-set spins
    254163 Mutex total count
    149165 Mutex free count
    104998 Mutex in-use count
    104998 Mutex maximum in-use count
    Mutex counts
    149165 Unallocated
    1 env region
    33 lock region
    797 logical lock
    1 log filename
    1 log flush
    1 log region
    74 mpoolfile handle
    71298 mpool buffer
    17 mpool file bucket
    32771 mpool hash bucket
    1 mpool region
    1 mutex region
    1 transaction checkpoint
    1 txn region

  • (J2ME) Stopping a blocked thread

    In J2ME, receiving a datagram blocks the current thread until a datagram is received. I have created a thread that simply receives a datagram and then loops waiting for the next one. How do I stop the thread when it is blocking in datagram receive waiting for a datagram to come in? I am using the code on http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html for a reference, and it mentions calling Thread.interrupt() but this method does not exist in J2ME.

    I tried searching for any API on J2ME... it looked like there were a lot of different specifications, and in any case I never found any API docs.
    However, i did want to say this:
    In regular java, the way you would normally do this is (ThreadObj).interrupt(), but you said this didn't exist. Are you 100% sure?
    If that's not working, I have 2 other ideas:
    1. Thread.stop() - it has been deprecated and is not technically "safe" but it could probably work in a pinch.
    2. There is often a way to put a timeout on an inputstream. See if you can do that.

  • Thread Blocked Problem

    I Have a multithread application which:
    - access to database
    - write files
    - read files
    - execute external process using exec
    What considerations should I take in order to avoid Threads Blocking? When Thread blocking occurs how can I know what is the cause?
    Thanks!
    T

    http://www.ibm.com/developerworks/library/j-thread.html
    - Saish

  • Having a problem with threads and using locks

    I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
    Withdrawal Threads         Deposit Threads            Balance
    Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
    Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
    Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
    Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                    Thread 1 deposits $187          $187
                                    Thread 3 deposits $169          $356
                                    Thread 5 deposits $61           $417
    Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
    /************Assign2_Main.java************/
    import java.util.concurrent.*;
    public class Assign2_Main
    {//start Assign2_Main
        public static void main(String[] args)
        {//start main
               // create ExecutorService to manage threads
               ExecutorService threadExecutor = Executors.newCachedThreadPool();
            Account account = new SynchronizedThreads();
            Deposit deposit1 = new Deposit(account, "Thread 1");
            Deposit deposit2 = new Deposit(account, "Thread 3");
            Deposit deposit3 = new Deposit(account, "Thread 5");
            Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
            Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
            Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
            Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
            System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
            System.out.println("------------------\t\t---------------\t\t\t-------\n");
            try
                threadExecutor.execute(withdrawal1);       
                threadExecutor.execute(deposit1);     
                threadExecutor.execute(withdrawal2);  
                threadExecutor.execute(deposit2);    
                threadExecutor.execute(withdrawal3);
                threadExecutor.execute(deposit3);       
                threadExecutor.execute(withdrawal4);
            catch ( Exception e )
                 e.printStackTrace();
                //shutdown worker threads
               threadExecutor.shutdown();
        }//end main
    }//end Assign2_Main/******************Withdrawal.java****************************/
    public class Withdrawal implements Runnable
    {//start  class Withdrawal
          *constructor
        public Withdrawal(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start ruin
             int newNum = 0;
                newNum = account.getBalance(name); 
               Thread.yield();
        }//end run
        private Account account;
        private String name;
    }//end  class Withdrawal/*******************Deposit.java***************/
    import java.util.Random;
    public class Deposit implements Runnable
    {//start class Deposit
          *constructor
        public Deposit(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start run
                try
                     Thread.sleep(100);
                   account.setBalance(random.nextInt(200), name);
                }// end try
                catch (InterruptedException e)
                  e.printStackTrace();
       }//end run
       private Account account;
       private Random random = new Random();
       private String name;
    }//end class Deposit/********************Account.java*****************/
    *Account interface specifies methods called by Producer and Consumer.
    public interface Account
         //place sum into Account
         public void setBalance(int sum, String name);
         //return  value of Account
            public int getBalance(String name);         
    } /**************SynchronizedThreads.java****************/
    import java.util.concurrent.locks.*;
    import java.util.Random;
    public class SynchronizedThreads implements Account
    {//start SynchronizedThreads
          *place money into buffer
        public void setBalance(int amount, String name)
        {//start setBalance
             // lock object
             myLock.lock();           
            sum += amount;
            System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
               //threads are singnaled to wakeup
            MakeWD.signalAll();
              // unlock object                                                
            myLock.unlock();
           }//end setBalance
            *gets the balance from buffer
           public int getBalance(String name)
        {//start getBalance
             int NewSum = random.nextInt(50);
             //lock object
            myLock.lock();
            try
                 if(sum > NewSum)
                     //takes NewSum away from the account
                     sum -= NewSum;
                        System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
                else
                     System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                     //not enough funds so thread waits
                        MakeWD.await();         
                //threads are singnaled to wakeup
                MakeD.signalAll();     
                }//end try
            catch (InterruptedException e)
                   e.printStackTrace();
            finally
                 //unlock object
                 myLock.unlock();
            return NewSum;     
         }//end getBalance
         private Random random = new Random();  
         private Lock myLock = new ReentrantLock();
         private Condition MakeD = myLock.newCondition();
         private Condition MakeWD = myLock.newCondition();
         private int sum = 0;
    }//end SynchronizedThreads

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Applet with JFilechooser called from a Javascript blocks paint messages

    Hi,
    I am trying to create an applet that can:
    1) be called from a Javascript
    2) displays a file selection dialog for multi-selecting files
    3) returns the selected filenames in a string to the JavaScript
    I am able to use doPrivileged to apply the necessary security context to launch a JFilechooser and return the filenames selected. However, When the JFilechooser dialog is visible and the user moves the dialog window around the HTML pages dose not receive any repaint messages. They seem to be blocked by the thread that launched the JFilechooser dialog and is probably blocking update events as the dialog is still visible.
    I know I need some type of a message pump so the child thread can inform the parent thread and the browser to repaint. However, I don't know how to do this.
    Please help.
    ------Applet Code Begin:-----
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.AWTEvent;
    import java.awt.event.AWTEventListener.*;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Locale;
    import java.util.MissingResourceException;
    import java.util.Properties;
    import java.util.ResourceBundle;
    import java.util.Vector;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    public class SampleApplet extends JApplet
       boolean allowDirs=false;
       boolean allowFiles=true;
       boolean hidden=false;
       File lastUserDir=null;
       public void init()
        public void start()
        public void stop()
        public String selectFiles()
           String choosenFiles = null;
           choosenFiles = new String((String)java.security.AccessController.doPrivileged(
           new java.security.PrivilegedAction()
         public Object run()
            String choosenFiles=new String();
                 JFilechooser fc = new JFilechooser();
         fc.setFileSelectionMode(allowDirs ? (allowFiles ? JFileChooser.FILES_AND_DIRECTORIES
            : JFileChooser.DIRECTORIES_ONLY)
            : JFileChooser.FILES_ONLY);
         fc.setMultiSelectionEnabled(true);
                 int returnVal = fc.showOpenDialog(null);
                 if (returnVal == JFileChooser.APPROVE_OPTION)
                    choosenFiles = "The selected filesnames will be stuffed here";
              return choosenFiles; //return whatever you want
           return choosenFiles;   
    ------Applet Code End:-----
    ------Html Code Begin:-----
    <html>
    <applet id="SampleApplet" archive="SampleApplet.jar"; code="SampleApplet.class"; width="2" height="2" codebase=".">
    </applet>
    <head>
        <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
    function SelectFiles_onclick()
      var s = (document.applets[0].selectFiles());
      alert(s);
    </script>
    </head>
    <body>
        Click Test button to select files
        <input id="SelectFiles" type="button" value="Select Files" onclick="return SelectFiles_onclick()" />
    </body>
    </html>
    ------Html Code End:-----

    try this:
    first don't open the file dialog in the SelectFiles call. Start a new thread that does that. Then return from the SelectFiles call immediately. Now after the user selectes the files call back into the javascript by doing something like this:
    pass the list of files into this function, each on being a String in the params array
        public synchronized void sendDataToUI(Object[] params) {
            if (FuserState.hasQuit()) {
                return;
            String function = "getUpdates";
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "Calling Javascript function " + function);
            if (getJavaScriptWindow() == null) {
                logger.log(Level.SEVERE, "Member javascriptWindow is NULL, no call was made!");
                return;
            try {
                getJavaScriptWindow().call(function, params);
            catch (netscape.javascript.JSException x) {
                if (params == null) {
                    logger.log(Level.SEVERE, "p=NULL PARAM");
                } else {
                    logger.log(Level.SEVERE, "p=" + params[0]);
        protected JSObject getJavaScriptWindow() {
            javascriptWindow = JSObject.getWindow(this);
        }

Maybe you are looking for

  • Not able to see disk connected to AirPort Extreme 802.11n

    I just installed my AirPort Extreme 802.11n Wireless Base station. Wireless internet works like a charm, however, I cannot see my external hard disk when it is connected to the base station (amber light blinking and when checking the problem, I am to

  • How to handle garbage collection in a recursive function

    I'm writing a web crawler which basically looks like this: //Entity class representing a page on the web class Page    Page[] children; public void crawl(Page parentPage)    Page[] children = getChildrenUsingSomeFunction(parentPage);    parentPage.se

  • Duplicating a DVD

    I have a "universal disk format" DVD. It opens and plays fine using the "DVD Player" app. on this computer. It plays fine on both my Blue Ray disk players and HDTVs. I've used both the finder 'duplicate' and Disk Utility 'disk image' methods to try t

  • Please adjust base unit and coversion factor

    Hello Frinds, When I am going to change purchase info record, I am getting the error "Please adjust base unit and coversion factor". Base unit in info record and material master are same. I don't understand reason for this error. can anybody help me

  • MySQL Auto Increment Keys

    Is there a way to use MySQL Auto Increment Keys with Kodo? sean.