Thread safe display of JTable

Hi all,
I have a JTree, which has JTable as its node.
Each JTable has some children that will be displayed on expanding a node.
When user expands a node, next sibling node of that ( a JTable again) will get header.I am programmatically adding header to the table.To display properly I am performing 2 steps:
1) adding header to the table
2) Increasing the size of the table by some new dimension for making it to show with header.
At run time when I expand the tree is not repainting properly.When I expands any node the next sibling(a JTable) is only appearing with its old size but showing header. After performing some more events it is appearing properly to the user.
Is this because of improper threads?
pls provide a solution to this problem.
thanks in advance
amar

Hi sabre150 ,
thanx for responding.
It took some time for me to prepare a sample.
Here I am pasting sample similar to my application.
I hope you can better understand my problem by running this sample.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.util.*;
import javax.swing.event.*;
public class TestJTreePanel extends JPanel {
JScrollPane jScrollPane1 = new JScrollPane();
JTree jTree1;
TradeAllocTableNodePanel treenodePanel = new TradeAllocTableNodePanel();
TradeAllocTableNodePanel treenodePanel2 = new TradeAllocTableNodePanel();
TradeAllocRcptDelTableNodePanel childtreenodePanel = new TradeAllocRcptDelTableNodePanel();
GridBagLayout gridBagLayout1 = new GridBagLayout();
public TestJTreePanel() {
this.setBorder(null);
try {
DefaultMutableTreeNode topNode = new DefaultMutableTreeNode("Allocations", true);
treenodePanel.getTable().getTableHeader().setPreferredSize(new Dimension(897,20));
DefaultMutableTreeNode childTradeAllocNode1 = new DefaultMutableTreeNode(treenodePanel, true);
((TradeAllocTableNodePanel)childTradeAllocNode1.getUserObject()).setUserPreferedSize(new Dimension(897, 40));
DefaultMutableTreeNode childRcptDelNode1 = new DefaultMutableTreeNode(childtreenodePanel);
jScrollPane1.setBorder(null);
this.setAlignmentX((float) 0.5);
this.setAlignmentY((float) 0.5);
this.setActionMap(null);
childTradeAllocNode1.add(childRcptDelNode1);
DefaultMutableTreeNode childTradeAllocNode2 = new DefaultMutableTreeNode(new TradeAllocTableNodePanel(), true);
DefaultMutableTreeNode childRcptDelNode2 = new DefaultMutableTreeNode(childtreenodePanel);
childTradeAllocNode2.add(childRcptDelNode2);
DefaultMutableTreeNode childTradeAllocNode3 = new DefaultMutableTreeNode(new TradeAllocTableNodePanel(), true);
DefaultMutableTreeNode childRcptDelNode3 = new DefaultMutableTreeNode(childtreenodePanel);
childTradeAllocNode3.add(childRcptDelNode3);
DefaultMutableTreeNode childTradeAllocNode4 = new DefaultMutableTreeNode(new TradeAllocTableNodePanel(), true);
DefaultMutableTreeNode childRcptDelNode4 = new DefaultMutableTreeNode(childtreenodePanel);
childTradeAllocNode4.add(childRcptDelNode4);
topNode.add(childTradeAllocNode1);
topNode.add(childTradeAllocNode2);
topNode.add(childTradeAllocNode3);
topNode.add(childTradeAllocNode4);
jTree1 = new JTree(topNode);
jTree1.setCellRenderer(new TradeAllocTreeCellRenderer());
jTree1.setRootVisible(false);
jTree1.setShowsRootHandles(true);
jTree1.addTreeExpansionListener(new TreeExpansionListener()
public void treeExpanded(TreeExpansionEvent e)
//TreePath of expanded node
TreePath pathObject = e.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)pathObject.getLastPathComponent();
if (node == null) return;
final DefaultMutableTreeNode siblingNode = node.getNextSibling();
if (siblingNode == null) return;
if(siblingNode.getLevel()==1)
((TradeAllocTableNodePanel)siblingNode.getUserObject()).getTable().getTableHeader().setPreferredSize(new Dimension(897, 20));
((TradeAllocTableNodePanel)siblingNode.getUserObject()).setUserPreferedSize(new Dimension(897, 40));
((DefaultTreeModel)jTree1.getModel()).nodeChanged(siblingNode);
jTree1.treeDidChange();
public void treeCollapsed(TreeExpansionEvent e)
TreePath pathObject = e.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)pathObject.getLastPathComponent();
if (node == null) return;
DefaultMutableTreeNode siblingNode = node.getNextSibling();
if (siblingNode == null) return;
if(siblingNode.getLevel()==1)
((TradeAllocTableNodePanel)siblingNode.getUserObject()).getTable().getTableHeader().setPreferredSize(new Dimension(0,0));
((TradeAllocTableNodePanel)siblingNode.getUserObject()).setUserPreferedSize(new Dimension(897, 20));
((DefaultTreeModel)jTree1.getModel()).nodeChanged(siblingNode);
jTree1.treeDidChange();
this.setLayout(gridBagLayout1);
this.add(jScrollPane1, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 397, -48));
jScrollPane1.getViewport().add(jTree1, null);
catch(Exception ex) {
ex.printStackTrace();
public static void main(String args[])
TestJTreePanel test=new TestJTreePanel();
JFrame frame=new JFrame();
frame.getContentPane().add(test);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(900,500));
frame.setVisible(true);
public static class ResultTreeCellRenderer extends DefaultTreeCellRenderer
public Component getTreeCellRendererComponent(JTree t, Object value,boolean s, boolean o,boolean l, int r, boolean h)
if (value instanceof DefaultMutableTreeNode)
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
if (node.getUserObject() instanceof TradeAllocTableNodePanel)
return new JScrollPane((TradeAllocTableNodePanel) node.getUserObject());
return super.getTreeCellRendererComponent(t, value, s, o, l, r, h);
//*************Table code**********************
public class TradeAllocTableNodePanel extends JPanel {
JScrollPane jScrollPane1 = new JScrollPane();
public JTable jTable1 = new JTable();
BorderLayout borderLayout1 = new BorderLayout();
public TradeAllocTableNodePanel() {
this.setBorder(null);
try {
Object[] [] rowData = {
{ "Allocated", "6789", "NO6-10;NO6-12", "GLENCOR E L", "5340", "12/01/20", "12/15/20", "", "", "$", "C", "FA" }
String[] columnNames = { "AllocStatus", "AllocNumb", "Cmdty", "Cpty", "Alloc", "MinForm", "MaxToD", "MOTType", "MOT", "ShowCosts", "Comments", "FullyActualize" };
jTable1 = new JTable(rowData, columnNames);
jTable1.getTableHeader().setPreferredSize(new Dimension(0,0));
setUserPreferedSize(new Dimension(897, 20));
this.setLayout(borderLayout1);
jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
jScrollPane1.setAutoscrolls(false);
this.add(jScrollPane1, BorderLayout.CENTER);
jScrollPane1.getViewport().add(jTable1, null);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
catch(Exception ex) {
ex.printStackTrace();
public void setUserPreferedSize(Dimension newDimension){
if(newDimension != null){
super.setPreferredSize(newDimension);
public JTable getTable() {
return jTable1;
public class TradeAllocTreeCellRenderer extends DefaultTreeCellRenderer {
public TradeAllocTreeCellRenderer() {
super();
updateUI();
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected,
boolean expanded, boolean leaf,
int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf,
row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode deftreenode = (DefaultMutableTreeNode) value;
Object userObj = deftreenode.getUserObject();
if (userObj instanceof JPanel) {
JPanel pnlLeaf = (JPanel) userObj;
tree.setRowHeight(0);
pnlLeaf.repaint();
pnlLeaf.invalidate();
pnlLeaf.validate();
return ((JPanel)pnlLeaf);
return super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
public Dimension getPreferredSize() {
Dimension retDimension = super.getPreferredSize();
if(retDimension != null)
retDimension = new Dimension(retDimension.width+3,
retDimension.height);
return retDimension;
public class TradeAllocRcptDelTableNodePanel extends JPanel {
JScrollPane jScrollPane1 = new JScrollPane();
JTable jTable1;
BorderLayout borderLayout1 = new BorderLayout();
public TradeAllocRcptDelTableNodePanel() {
try {
jbInit();
catch(Exception ex) {
ex.printStackTrace();
void jbInit() throws Exception {
Object[] [] rowData = {
{ "REC", "GLENCOR E L", "87063/3/1/168673", "NO6-10", "12/02/2", "12/15/2", "12/02/2", "5430", "BBL", "0", "A", "true", "", "", "", "" },
{ "DEL", "GLENCOR E L", "87063/3/1/168673", "NO6-10", "12/02/2", "12/15/2", "12/02/2", "5430", "BBL", "0", "B", "true", "", "", "", "" }
String[] columnNames = { "REC_DEL", "Cpty", "Trade_Port", "Cmdty", "NomFrom", "NomTo", "ETA", "NomQTY", "NomUOM", "ActualQTY", "A", "P", "FA", "ActualDT", "Credit", "Insp_Agent" };
jTable1 = new JTable(rowData, columnNames);
this.setLayout(borderLayout1);
jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
jScrollPane1.setAutoscrolls(false);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
//upto here on 080404
jScrollPane1.getViewport().add(jTable1, null);
this.add(jScrollPane1, BorderLayout.CENTER);
this.setPreferredSize(new Dimension(879, 56));
thanx
amar

Similar Messages

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Trying to understand "thread-safe" w/ swing components

    The other day there was a big hullabaloo about some code I posted because I was calling JLabel.setText from a thread that wasn't the ui thread. On the other hand, this thread was the only thread making changes to the JLabel. My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?
    Second question - JLabel.setText() is essentially setting data in the model for JLabel, which then gets picked up and displayed the next time the GUI thread paints it. So if it's not safe to update a JLabel's model, I assume its never safe to update any data that also is being displayed visually. So for instance, if I was showing some database table data in a JTable, I should do the update in the UI thread - probably not. But what is the distinction?
    Third question - what swing components and what operations need to be run on the UI thread to call your program "thread-safe". Validate? setSize()? setLocation()? add? remove? Is there anything that can be called on swing components from a non-ui thread?
    Edited by: tjacobs01 on Nov 2, 2008 8:29 PM

    tjacobs01 wrote:
    My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?This is not true. As I mentioned in that hullabaloo thread, the Java Memory Model allows threads to cache values of variables they use. This means that values written by one thread are not guaranteed to ever be visible to other threads, unless you use proper synchronization.
    Take the following example:
    import java.util.concurrent.TimeUnit;
    public class ThreadExample {
        static class Foo {
            private String value = "A";
            public String getValue() {
                return value;
            public void setValue(String value) {
                this.value = value;
        public static void main(String[] args) {
            final Foo foo = new Foo();
            Thread writer = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        foo.setValue("B");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            Thread reader = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MINUTES.sleep(1);
                        System.out.println(foo.getValue());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            writer.start();
            reader.start();
    }Here two different threads both access the same Foo instance, which is initialized with a value of "A". One thread, the writer, sleeps one second, and then sets foo's value to "B". The other thread, the reader, sleeps one minute (to avoid race conditions) and then prints foo's value to System.out. It may seem obvious that the reader thread will read the value "B", but this is in fact not guaranteed to be true. The reader thread may never see the value that was written by the writer thread, so it may very well read the old value "A".
    (If you run the code you will probably see "B" printed out, but again, this is not guaranteed behavior.)
    A simple way to fix this is to synchronize access to the mutable state that the two threads share. For example, change the class Foo to
        static class Foo {
            private String value = "A";
            public synchronized String getValue() {
                return value;
            public synchronized void setValue(String value) {
                this.value = value;
        }It's for this same reason that you often see the use of a volatile boolean as a control flag for stopping threads, rather than a plain old boolean. The use of volatile guarantees that the thread you want to stop actually sees the new value of the flag once it has been set by another thread.
    Here is an article that touches some of this stuff:
    [http://www.ibm.com/developerworks/java/library/j-jtp02244.html]
    I also highly recommend the book "Java Concurrency in Practice" (one of the authors of which, David Holmes, sometime hangs out on the Concurrency forum here, I believe).
    Edited by: Torgil on Nov 2, 2008 9:01 PM

  • Is thread safe the norm?

    In the Java tutorial - Creating a GUI with JFC/Swing trail - the main methods consist of some code to make the application "thread safe" by scheduleing the job for the event-dispatching thread. I can only guess at the true meaning of this. Other Java books do not take this approach. I actually don't remember the tutoral saying that last time I looked at it (some time ago). I have been using the main method to set up my frame and add to it my GUI class. This seems to always work for me. What do other forum members do and recommend?

    Whenever you write GUI code in Java, you (1) must ensure that changes to GUI objects only happen on the event thread, and (2) should schedule long-running operations on another thread.
    The first rule is simple: GUI objects are not synchronized, and if you try to change one from outside the event thread it may have inconsistent internal state when the GUI thread tries to access it. "Change" may be as simple as setting the contents of a JTextfield, or as complex as rebuilding the model for a JTable.
    If you simply create and display a JFrame from main(), you're generally safe. Until you call setVisible(true), the JFrame isn't actually accessed by the GUI thread. Once you call setVisible(true), the GUI thread takes control of the frame. If that's the last step in your main(), you're OK; for most complex programs, however, that's not the last step. As a result, it's a good habit to build up your frame from within a Runnable that you put on the event thread via SwingUtilities.invokeLater().
    (This last recommendation is a new part of the tutorial. I think it was added as-of 1.5, when show() was deprecated in favor of setVisible(true)).
    As long as your program simply reacts to events generated by your GUI programs, you don't have to worry about any other threads, since those events are distributed on the event thread. However, most real programs interact with the outside world: they read files, make database calls, access app-servers, or whatever. These calls all block the thread that's executing them; if you call them from the event thread, this will freeze your UI.
    So, rule #2 says to execute those potentially blocking operations on another thread (it's a suggestion, rather than an absolute, because you're free to do everything on the event thread as long as you don't mind blocked apps -- most people do mind, however).
    Of course, once you start something running on a separate thread, you need to get the results back to the event thread, which is where rule #1 (which is mandatory) comes in.
    Sun provides the SwingWorker class to help you with this; you can find it linked from the tutorial. Personally, I don't like it (in part because it spins up a new thread for each operation); instead, I use an "AsynchronousOperation" class that I pass to a threadpool for execution.

  • JTextArea: Not thread safe

    I am working on a lobby system with a chat are using Networking, and recently I noticed that occasionally my JTextArea does not append the data I give it, even if I have a System.out.println() directly before which shows me what it is being passed, and it is being passed correct Strings, it is just not appending them.
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        for (int x = 0; x < texts.size(); x++) {
                            System.out.println("ADDED: "+texts.get(x));
                            textArea.append(texts.get(x));
                        texts.clear();
                        scrollToEnd(textArea);
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };I have an ArrayList texts, which keeps track of what is being typed into the Chat Area. This code displays correctly What I want it to, i.e. "ADDED: Hello guys, etc.", however the JTextArea does not update. Is there something to make the JTextArea thread-safe because I have heard on several sites that JTextAreas are not thread-safe.
    Any help would be greatly appreciated.

    I changed my code to this: and now it does not work at all, i.e., the JTextArea never updates:
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        SwingUtilities.invokeAndWait(update);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InvocationTargetException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        Runnable update = new Runnable() {
            public void run()
                try {
                    texts.clear();
                    scrollToEnd(textArea);
                    for (int x = 0; x < texts.size(); x++) {
                        System.out.println("ADDED: " + texts.get(x));
                        textArea.append(texts.get(x));
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };

  • PopUpManager + Concurrency = NOT Thread-Safe

    Is there any way to make the PopUpManager not throw evil
    messages like this:
    RangeError: Error #2006: The supplied index is out of bounds.
    at flash.display::DisplayObjectContainer/addChildAt()
    at mx.managers::SystemManager/
    http://www.adobe.com/2006/flex/mx/internal::rawChildren_addChildAt()
    at mx.managers::SystemManager/addChild()
    at mx.managers::PopUpManagerImpl/addPopUp()
    at mx.managers::PopUpManager$/addPopUp()
    at mx.controls::Menu/show()
    at jseamless/::openRightClick()
    at Function/
    http://adobe.com/AS3/2006/builtin::apply()
    at ()
    at
    flash.external::ExternalInterface$/flash.external:ExternalInterface::_callIn()
    When a call is made concurrently. I think I can resolve the
    issue if I can replace the PopUpManager's implementation. Can
    someone tell me how to do that? I'd like to write a thread-safe
    version of the PopUpManager to handle concurrent calls to
    it....right now it just dies showing the error above.

    This should be addressed in the 9.2.0.1 Oracle JDBC release (pehaps also in earlier releases).
    Don't know why the original bug is still open (it likely got re-filed and fixed).
    -- Ekkehard

  • How can I use a Selector in a thread safe way?

    Hello,
    I'm using a server socket with a java.nio.channels.Selector contemporarily by 3 different threads (this number may change in the future).
    From the javadoc: Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.
    Following this advise, I wrote code in this way:
             List keys = new LinkedList(); //private key list for each thread
             while (true) {
              keys.clear();
              synchronized(selector) {
                  int num = selector.select();
                  if (num == 0)
                   continue;
                  Set selectedKeys = selector.selectedKeys();
                  //I expected this code to produce disjoint key sets on each thread...
                  keys.addAll(selectedKeys);
                  selectedKeys.clear();
              Iterator it = keys.iterator();
              while (it.hasNext()) {
                  SelectionKey key = (SelectionKey) it.next();
                  if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                   Socket s = serverSocket.accept();
                   SocketChannel sc = s.getChannel();
                   sc.configureBlocking( false );
                   sc.register( selector, SelectionKey.OP_READ );
                  } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
    //.....Unfortunately synchronizing on the selector didn't have the effect I expected. When another thread select()s, it sees the same key list as the other thread that select()ed previously. When control arrives to serverSocket.accept(), one thread goes ahead and the other two catch an IllegalBlockingModeException.
    I'm not willing to handle this exception, the right thing to do is giving disjoint key sets to each thread. How can I achieve this goal?
    Thanks in advance

    A single thread won't be enough cause after reading data from the socket I do some processing on it that may take long.So despatch that processing to a separate thread.
    Most of this processing is I/O boundI/O bound on the socket? or something else? If it's I/O bound on the socket that's even more of a reason to use a single thread.
    Anyway I think I'll use a single thread with the selector, put incoming data in a queue and let other 2 or 3 threads read from it.Precisely. Ditto outbound data.
    Thanks for your replies. But I'm still curious: why is a selector thread safe if it can't be used with multiple threads because of it's semantics?It can, but there are synchronization issues to overcome (with Selector.wakeup()), and generally the cost of solving these is much higher than the cost of a single-threaded selector solution with worker threads for the application processing.

  • How can I use the same thread to display time in both JPanel & status bar

    Hi everyone!
    I'd like to ask for some assistance regarding the use of threads. I currently have an application that displays the current time, date & day on three separate JLabels on a JPanel by means of a thread class that I created and it's working fine.
    I wonder how would I be able to use the same thread in displaying the current time, date & day in the status bar of my JFrame. I'd like to be able to display the date & time in the JPanel and JFrame synchronously. I am developing my application in Netbeans 4.1 so I was able to add a status bar in just a few clicks and codes.
    I hope somebody would be able to help me on this one. A simple sample code would be greatly appreciated.
    Thanks in advance!

    As you're using Swing, using threads directly just for this kind of purpose would be silly. You might as well use javax.swing.Timer, which has done a lot of the work for you already.
    You would do it something like this...
        ActionListener timerUpdater = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // DateFormat would be better, but this is an example.
                String timeString = new Date().toString();
                statusBar.setText(timeString);
                someOtherLabel.setText(timeString);
        new Timer(1000, timerUpdater).start();That code will update the time once a second. If you aren't going to display seconds, you might as well increase the delay.
    The advantage of using a timer over using an explicit thread, is that multiple Swing timers will share a single thread. This way you don't blow out your thread count. :-)

  • Is the Illustrator SDK thread-safe?

    After searching this forum and the Illustrator SDK documentation, I can't find any references to a discussion about threading issues using the Illustrator C++ SDK. There is only a reference in some header files as to whether menu text is threaded, without any explanation.
    I take this to mean that probably the Illustrator SDK is not "thread-safe" (i.e., it is not safe to make API calls from arbitrary threads; you should only call the API from the thread that calls into your plug-in). Does anyone know this to be the case, or not?
    If it is the case, the normal way I'd write a plug-in to respond to requests from other applications for drawing services would be through a mutex-protected queue. In other words, when Illustrator calls the plug-in at application startup time, the plug-in could set up a mutually exclusive lock (a mutex), start a thread that could respond to requests from other applications, and request periodic idle processing time from the application. When such a request arrived from another application at an arbitrary time, the thread could respond by locking the queue, adding a request to the queue for drawing services in some format that the plug-in would define, and unlocking the queue. The next time the application called the plugin with an idle event, the queue could be locked, pulled from, and unlocked. Whatever request had been pulled could then be serviced with Illustrator API calls. Does anyone know whether that is a workable strategy for Illustrator?
    I assume it probably is, because that seems to be the way the ScriptingSupport.aip plug-in works. I did a simple test with three instances of a Visual Basic generated EXE file. All three were able to make overlapping requests to Illustrator, and each request was worked upon in turn, with intermediate results from each request arriving in turn. This was a simple test to add some "Hello, World" text and export some jpegs,
    repeatedly.
    Any advice would be greatly appreciated!
    Glenn Picher
    Dirigo Multimedia, Inc.
    [email protected]

    Zac Lam wrote:
    The Memory Suite does pull from a specific memory pool that is set based on the user-specified Memory settings in the Preferences.  If you use standard OS calls, then you could end up allocating memory beyond the user-specified settings, whereas using the Memory Suite will help you stick to the Memory settings in the Preferences.
    When you get back NULL when allocating memory, are you hitting the upper boundaries of your memory usage?  Are you getting any error code returned from the function calls themselves?
    I am not hitting the upper memory bounds - I have several customers that have 10's of Gb free.
    There is no error return code from the ->NewPtr() call.
         PrMemoryPtr (*NewPtr)(csSDK_uint32 byteCount);
    A NULL pointer is how you detect a problem.
    Note that changing the size of the ->ReserveMemory() doesn't seem to make any difference as to whether you'll get a memory ptr or NULL back.
    btw my NewPtr size is either
         W x H x sizeof(PrPixelFormat_YUVA4444_32f)
         W x H x sizeof(PrPixelFormat_YUVA4444_8u)
    and happens concurrently on #cpu's threads (eg 16 to 32 instances at once is pretty common).
    The more processing power that the nVidia card has seems to make it fall over faster.
    eg I don't see it at all on a GTS 250 but do on a GTX 480, Quadro 4000 & 5000 and GTX 660
    I think there is a threading issue and an issue with the Memory Suite's pool and how it interacts with the CUDA memory pool. - note that CUDA sets RESERVED (aka locked) memory which can easily cause a fragmenting problem if you're not using the OS memory handler.

  • Is the Memory Suite thread safe?

    Hi all,
    Is the memory suite thread safe (at least when used from the Exporter context)?
    I ask because I have many threads getting and freeing memory and I've found that I get back null sometimes. This, I suspect, is the problem that's all the talk in the user forum with CS6 crashing with CUDA enabled. I'm starting to suspect that there is a memory management problem when there is also a lot of memory allocation and freeing going on by the CUDA driver. It seems that the faster the nVidia card the more likely it is to crash. That would suggest the CUDA driver (ie the code that manages the scheduling of the CUDA kernels) is in some way coupled to the memory use by Adobe or by Windows alloc|free too.
    I replaced the memory functions with _aligned_malloc|free and it seems far more reliable. Maybe it's because the OS malloc|free are thread safe or maybe it's because it's pulling from a different pool of memory (vs the Memory Suite's pool or the CUDA pool)
    comments?
    Edward

    Zac Lam wrote:
    The Memory Suite does pull from a specific memory pool that is set based on the user-specified Memory settings in the Preferences.  If you use standard OS calls, then you could end up allocating memory beyond the user-specified settings, whereas using the Memory Suite will help you stick to the Memory settings in the Preferences.
    When you get back NULL when allocating memory, are you hitting the upper boundaries of your memory usage?  Are you getting any error code returned from the function calls themselves?
    I am not hitting the upper memory bounds - I have several customers that have 10's of Gb free.
    There is no error return code from the ->NewPtr() call.
         PrMemoryPtr (*NewPtr)(csSDK_uint32 byteCount);
    A NULL pointer is how you detect a problem.
    Note that changing the size of the ->ReserveMemory() doesn't seem to make any difference as to whether you'll get a memory ptr or NULL back.
    btw my NewPtr size is either
         W x H x sizeof(PrPixelFormat_YUVA4444_32f)
         W x H x sizeof(PrPixelFormat_YUVA4444_8u)
    and happens concurrently on #cpu's threads (eg 16 to 32 instances at once is pretty common).
    The more processing power that the nVidia card has seems to make it fall over faster.
    eg I don't see it at all on a GTS 250 but do on a GTX 480, Quadro 4000 & 5000 and GTX 660
    I think there is a threading issue and an issue with the Memory Suite's pool and how it interacts with the CUDA memory pool. - note that CUDA sets RESERVED (aka locked) memory which can easily cause a fragmenting problem if you're not using the OS memory handler.

  • Can use the same thread safe variable in the different processes?

    Hello,
    Can  use the same thread safe variable in the different processes?  my application has a log file used to record some event, the log file will be accessed by the different process, is there any synchronous method to access the log file with CVI ?
    David

    Limiting concurrent access to shared resources can be better obtained by using locks: once created, the lock can be get by one requester at a time by calling CmtGetLock, the other being blocked in the same call until the lock is free. If you do not want to lock a process you can use CmtTryToGtLock instead.
    Don't forget to discard locks when you have finished using them or at program end.
    Alternatively you can PostDeferredCall a unique function (executed in the main thread) to write the log passing the apprpriate data to it.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • Native library NOT thread safe - how to use it via JNI?

    Hello,
    has anybody ever tried to use a native library from JNI, when the library is not thread safe?
    The library (Windows DLL) was up to now used in an MFC App and thus was only used by one user - that meant one thread - at a time.
    Now we would like to use the library like a "server": many Java clients connect the same time to the library via JNI. That would mean each client makes its calls to the library in its own thread. Because the library is not thread safe, this would cause problems.
    Now we discussed to load the library several times - separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this way?
    Are there other ways to use the library, though it is not thread safe?
    Any ideas welcome.
    Thanks for any contributions to the discussion, Ina

    (1)
    has anybody ever tried to use a native library from
    JNI, when the library (Windows DLL) is not thread safe?
    Now we want many Java clients.
    That would mean each client makes its calls
    to the library in its own thread. Because the library
    is not thread safe, this would cause problems.Right. And therefore you have to encapsulate the DLL behind a properly synchronized interface class.
    Now the details of how you have to do that depends: (a) does the DLL contain state information other than TLS? (b) do you know which methods are not thread-safe?
    Depending on (a), (b) two extremes are both possible:
    One extreme would be to get an instance of the interface to the DLL from a factory method you'll have to write, where the factory method will block until it can give you "the DLL". Every client thread would obtain "the DLL", then use it, then release it. That would make the whole thing a "client-driven" "dedicated" server. If a client forgets to release the DLL, everybody else is going to be locked out. :-(
    The other extreme would be just to mirror the DLL methods, and mark the relevant ones as synchronized. That should be doable if (a) is false, and (b) is true.
    (2)
    Now we discussed to load the library several times -
    separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this
    way?The DLL is going to be mapped into the process address space on first usage. More Java threads just means adding more references to the same DLL instance.
    That would not result in thread-safe behavior.

  • Is Persistence context thread safe?  nop

    In my code, i have a servlet , 2 stateless session beans:
    in the servlet, i use jndi to find a stateless bean (A) and invoke a method methodA in A:
    (Stateless bean A):
    @EJB
    StatelessBeanB beanB;
    methodA(obj) {
    beanB.save(obj);
    (Stateless bean B, where container inject a persistence context):
    @PersistenceContext private EntityManager em;
    save(obj) {
    em.persist(obj);
    it is said entity manager is not thread safe, so it should not be an instance variable. But in the code above, the variable "em" is an instance variable of stateless bean B, Does it make sense to put it there using pc annotation? is it then thread safe when it is injected (manager) by container?
    since i think B is a stateless session bean, so each request will share the instance variable of B class which is not a thread safe way.
    So , could you please give me any guide on this problem? make me clear.
    any is appreciated. thank you
    and what if i change stateless bean B to
    (Stateless bean B, where container inject a persistence context):
    @PersistenceUnit private EntityManagerFactory emf;
    save(obj) {
    em = emf.creatEntityManager()
    //begin tran
    em.persist(obj);
    // commit tran
    //close em
    the problem is i have several stateless beans like B, if each one has a emf injected, is there any problem ?

    Hi Jacky,
    An EntityManager object is not thread-safe. However, that's not a problem when accessing an EntityManager from EJB bean instance state. The EJB container guarantees that no more than one thread has access to a particular bean instance at any given time. In the case of stateless session beans, the container uses as many distinct bean instances as there are concurrent requests.
    Storing an EntityManager object in servlet instance state would be a problem, since in the servlet programming model any number of concurrent threads share the same servlet instance.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Web service client proxy thread safe?

    Is the jax-ws web service client proxy and port objects thread safe in Weblogic 10.3.4?
    Been searching through the docs but can't find any info on this.

    I have searched and it seems that with cxf it's safe to do something like this.
    Nobody knows if this is safe using metro?

  • Thread-safe design pattern for encapsulating Collections?

    Hi,
    This must be a common problem, but I just can't get my head around it.
    Bascially I'm reading in data from a process, and creating/updating data structuers from this data. I've got a whloe bunch of APTProperty objects (each with a name/value) stored in a sychronized HashMap encapsulated by a class called APTProperties. It has methods such as:
    addProperty(APTProperty) // puts to hashmap
    getProperty(String name) // retreives from hashmap
    I also want clients to be able to iterate through all the APTProperties, in a thread safe manner . ie. they aren't responsible for sychronizing on the Map before getting the iterator. (See Collections.synchronizedMap() API docs).
    Is there any way of doing this?
    Or should I just have a method called
    Iterator propertyIterator() which returns the corresponding iterator of the HashMap (but then I can't really make it thread safe).
    I'd rather not make the internal HashMap visible to calling clients, if possible, 'cause I don't want people tinkering with it, if you know what I mean.
    Hope this makes sense.
    Keith

    In that case, I think you need to provide your own locking mechanism.
    public class APTProperties {
    the add, get and remove methods call lock(), executes its own logic, then call unlock()
    //your locking mechanism
    private Thread owner; //dont need to be volatile due to synchronized access
    public synchronized void lock() {
    while(owner != null) {
    wait();
    th = Thread.currentThread();
    public synzhronized void unlock() {
    if(owner == currentThread()){
    owner = null;
    notifyAll();
    }else {
    throw new IllegalMonitorStateException("Thread: "+ Thread.currentThread() + "does not own the lock");
    Now you dont gain a lot from this code, since a client has to use it as
    objAPTProperties.lock();
    Iterator ite = objAPTProperties.propertyIterator();
    ... do whatever needed
    objAPTProperties.unlock();
    But if you know how the iterator will be used, you can make the client unaware of the locking mechanism. Lets say, your clients will always go upto the end thru the iterator. In that case, you can use a decorator iterator to handle the locking
    public class APTProperties {
    public Iterator getThreadSafePropertyIterator() {
    private class ThreadSafeIterator implements Iterator {
    private iterator itr;
    private boolean locked;
    private boolean doneIterating;
    public ThreadSafeIterator(Iterator itr){
    this.itr = itr;
    public boolean hasNext() {
    return doneIterating ? false : itr.hasNext();
    public Object next() {
    lockAsNecessary();
    Object obj = itr.next();
    unlockAsNecessary();
    return obj;
    public void remove() {
    lockAsNecessary();
    itr.remove();
    unlockAsNecessary();
    private void lockAsNecessary() {
    if(!locked) {
    lock();
    locked = true;
    private void unlcokAsNecessary() {
    if(!hasNext()) {
    unlock();
    doneIterating = true;
    }//APTProperties ends
    The code is right out of my head, so it may have some logic problem, but the basic idea should work.

Maybe you are looking for