Jpanel setBackground color thread safe?

is this method thread safe?
meaning do i have to use Invoke on the dispatch thread everytime or
it doesn't really matter

is this method thread safe?
meaning do i have to use Invoke on the dispatch
thread everytime or
it doesn't really matterThat's not what thread safe means, but yes, you should be able to call it from any thread.

Similar Messages

  • SetBackground(Color c)

    Hello All,
    What do you know about setBackground(Color c) execution ?
    I mean does this function work as PostMessage() or as SendMessage ? Can I be sure that after the funcion has returned this "paint message" has already been processed by the system ?

    Wrong. I suggest you take a look at the code in JComponent:
    public void setBackground(Color bg) {
       Color oldBg = getBackground();
       super.setBackground(bg);
       if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
          // background already bound in AWT1.2
          repaint();
    }But in general if you program in such a way that it matters when exactly
    your component gets repainted, better re-think your approach:
    You should call setBackground() only from AWTs event thread and you
    better don't make long-running calculations in this thread.
    However at the latest your component will get repainted when this
    thread is idle.
    Also, take a look at the JavaDoc of repaint():
    "Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched."
    So even repaint() does not paint your component immediatly.
    The gist of it: JavaDoc and the JDK sources are your friend.

  • SetBackground(Color.WHITE) not working

    I am trying to set background color to white, but it's not working. Can anyone find out the problem?
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.font.FontRenderContext;
    import java.awt.font.LineMetrics;
    import java.awt.font.TextLayout;
    import java.awt.geom.*;
    public class Lab3ex2 {
         * @param args ignored
         public static void main(String[] args) throws IOException {
              // Station[] stations = new Station[100];
              // int n = 0;
              ArrayList<Station> stations = new ArrayList<Station>();
              ArrayList xPos = new ArrayList();
              ArrayList yPos = new ArrayList();
              final String fname = "C://Positions-v2.csv";
              BufferedReader br = new BufferedReader(new FileReader(fname));
              String stationName, item, line;
              line = br.readLine(); // first line skipped
              line = br.readLine(); // 2nd
              while (line != null) {
                   StringTokenizer stoke = new StringTokenizer(line, ",");
                   stationName = stoke.nextToken().trim();
                   item = stoke.nextToken();
                   float x = Float.parseFloat(item);
                   item = stoke.nextToken();
                   float y = Float.parseFloat(item);
                   item = stoke.nextToken();
                   String justification = item;
                   // stations[n] = new Station(stationName, x, y);
                   // n++;
                   stations.add(new Station(stationName, x, y, justification));
                   xPos.add(x);
                   yPos.add(y);
                   line = br.readLine(); // line 3,4,...
              for (Station station : stations) {
                   System.out.println(station);
                   //System.out.printf("%20s %6.1f,%6.1f)%n",station.name, station.x, station.y);
              System.out.print("Press enter...");
              System.in.read();
              JFrame f = new JFrame("Lab3ex2");
              f.add(new MyPanel(stations, xPos, yPos));
              f.setSize(500,400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to avoid needing ^C
    class Station {
         public String name;
         public float x;
         public float y;
         public String justification;
         public Station(String name, float x, float y, String justification) {
              this.name = name;
              this.x = x;
              this.y = y;
              this.justification = justification;
         public String toString() {
              // todo: format x and y
              return name + " (" + x + "," + y + ")";
    class MyPanel extends JPanel {
         private ArrayList<Station> stations;
         private float xMax, yMax;
         private ArrayList xPos;
         private ArrayList yPos;
         public void paintComponent(Graphics g) {
              Graphics2D g2 = (Graphics2D)g;
              Dimension dim = getSize();
              float xScale, yScale, scale, x, y, radius = 1.0f, diam;
              String justification = null;
              diam = 2.0f*radius;
              Shape s;
              xScale = dim.width/xMax;
              yScale = dim.height/yMax;
              scale = Math.min(xScale, yScale);
              g2.scale(scale, scale);
              g2.setStroke(new BasicStroke(1.0f/scale)); // thin lines
              g2.setFont(new Font("SanSerif", Font.PLAIN, (int)(11.2f/scale))); // always 12 approx
              int total = 0;
              for (Station st : stations) {
                   if(st.name.length()>total)
                        total = st.name.length();
              for (Station st : stations) {
                   x = st.x - radius;
                   y = st.y - radius;
                   justification = st.justification;
                   s = new Ellipse2D.Float(x, y, 2.0f*radius, 2.0f*radius);
                   g2.draw(s);
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
                   if(justification.equals("R"))
                        g2.drawString(st.name, (x-st.name.length())-2, (y+diam));
                   else
                        g2.drawString(st.name, (x+diam+radius), (y+diam));
    GeneralPath theShape = new GeneralPath();
         theShape.moveTo((float)(Float)xPos.get(0), (float)(Float)yPos.get(0));
    for(int i=0; i<15; i++)
         theShape.lineTo((float)(Float)xPos.get(i), (float)(Float)yPos.get(i));
    g2.draw(theShape);
    this.setBackground(Color.WHITE);
         public MyPanel(ArrayList<Station> stations, ArrayList xPos, ArrayList yPos) {
              this.stations = stations;
              this.xPos = xPos;
              this.yPos = yPos;
              xMax = -99999.0f;
              yMax = -99999.0f;
              for (Station st : stations) {
                   if (st.x > xMax) xMax = st.x;
                   if (st.y > yMax) yMax = st.y;
    }

    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.font.FontRenderContext;
    import java.awt.font.LineMetrics;
    import java.awt.font.TextLayout;
    import java.awt.geom.*;
    * Advanced Java Lab 3 ex 2: reading and drawing Met station data
    * @author rallen
    public class Lab3ex2 {
          * @param args
          *            ignored
         public static void main(String[] args) throws IOException {
              // Station[] stations = new Station[100];
              // int n = 0;
              ArrayList<Station> stations = new ArrayList<Station>();
              ArrayList xPos = new ArrayList();
              ArrayList yPos = new ArrayList();
              final String fname = "C://Positions-v2.csv";
              BufferedReader br = new BufferedReader(new FileReader(fname));
              String stationName, item, line;
              line = br.readLine(); // first line skipped
              line = br.readLine(); // 2nd
              while (line != null) {
                   StringTokenizer stoke = new StringTokenizer(line, ",");
                   stationName = stoke.nextToken().trim();
                   item = stoke.nextToken();
                   float x = Float.parseFloat(item);
                   item = stoke.nextToken();
                   float y = Float.parseFloat(item);
                   item = stoke.nextToken();
                   String justification = item;
                   // stations[n] = new Station(stationName, x, y);
                   // n++;
                   stations.add(new Station(stationName, x, y, justification));
                   xPos.add(x);
                   yPos.add(y);
                   line = br.readLine(); // line 3,4,...
              for (Station station : stations) {
                   System.out.println(station);
                   // System.out.printf("%20s %6.1f,%6.1f)%n",station.name, station.x,
                   // station.y);
              System.out.print("Press enter...");
              System.in.read();
              JFrame f = new JFrame("Lab3ex2");
              f.add(new MyPanel(stations, xPos, yPos));
              f.setSize(500, 400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to avoid needing ^C
    class Station {
         public String name;
         public float x;
         public float y;
         public String justification;
         public Station(String name, float x, float y, String justification) {
              this.name = name;
              this.x = x;
              this.y = y;
              this.justification = justification;
         public String toString() {
              // todo: format x and y
              return name + " (" + x + "," + y + ")";
    class MyPanel extends JPanel {
         private ArrayList<Station> stations;
         private float xMax, yMax;
         private ArrayList xPos;
         private ArrayList yPos;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              this.setLayout(new FlowLayout());
              Graphics2D g2 = (Graphics2D) g;
              Dimension dim = getSize();
              float xScale, yScale, scale, x, y, radius = 1.0f, diam;
              String justification = null;
              diam = 2.0f * radius;
              Shape s;
              xScale = dim.width / xMax;
              yScale = dim.height / yMax;
              scale = Math.min(xScale, yScale);
              g2.scale(scale, scale);
              g2.setStroke(new BasicStroke(1.0f / scale)); // thin lines
              g2.setFont(new Font("SanSerif", Font.PLAIN, (int) (11.2f / scale))); // always
                                                                                                        // 12
                                                                                                        // approx
              int total = 0;
              for (Station st : stations) {
                   if (st.name.length() > total)
                        total = st.name.length();
              for (Station st : stations) {
                   x = st.x - radius;
                   y = st.y - radius;
                   justification = st.justification;
                   s = new Ellipse2D.Float(x, y, 2.0f * radius, 2.0f * radius);
                   g2.draw(s);
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
                   if (justification.equals("R")) {
                        g2.drawString(st.name, (x - st.name.length()) - 2, (y + diam));
                   } else {
                        g2.drawString(st.name, (x + diam + radius), (y + diam));
              GeneralPath theShape = new GeneralPath();
              theShape.moveTo((float) (Float) xPos.get(0), (float) (Float) yPos
                        .get(0));
              for (int i = 0; i < 15; i++) {
                   theShape.lineTo((float) (Float) xPos.get(i), (float) (Float) yPos
                             .get(i));
              g2.draw(theShape);
              setOpaque(true);
         public MyPanel(ArrayList<Station> stations, ArrayList xPos, ArrayList yPos) {
              this.stations = stations;
              this.xPos = xPos;
              this.yPos = yPos;
              xMax = -99999.0f;
              yMax = -99999.0f;
              for (Station st : stations) {
                   if (st.x > xMax)
                        xMax = st.x;
                   if (st.y > yMax)
                        yMax = st.y;
              this.setBackground(Color.WHITE);
              this.setVisible(true);
    }Edited by: swapnil_raverkar on Sep 21, 2008 5:10 AM

  • SetBackground color not working

    Hello,
    While viewing my applet from within a HTML file, my background color is still grey, except the buttons.
    The color is fine while viewing with appletviewer so I'm a bit confussed.
    Any ideas as to why would be appreciated.
    Thanks in advance.
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.awt.event.*;
    public class MyCalendar extends javax.swing.JApplet  {
           public void init()
             Container content = getContentPane();
             JPanel calendars = new JPanel(new GridLayout(0,1));
             JScrollPane jsp = new JScrollPane(calendars);
             content.add(jsp, BorderLayout.CENTER);
             GregorianCalendar gc = new GregorianCalendar();
              //gc.set(GregorianCalendar.DAY_OF_YEAR,1);c
              gc.set(GregorianCalendar.DAY_OF_MONTH,1);     
                for (int i=0; i<12; i++)
               calendars.add(new CalendarPanel(gc));
               gc.add(GregorianCalendar.MONTH, 1);
              //setSize(300, 300);
                  //setVisible(true);
    class CalendarPanel extends JPanel implements ActionListener
           private JLabel jl;
           private int testYear;
           private final static String[] DOW = {"S","M","T","W","T","F","S"};
           SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
           GridBagConstraints gbc = new GridBagConstraints(0,0,7,1,1.0,1.0,GridBagConstraints.CENTER,
              GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0);
           public CalendarPanel(GregorianCalendar cal)
              setLayout(new GridBagLayout());
              setBorder(BorderFactory.createEtchedBorder());
              setBackground(Color.white);
              //get the month name
              String testMonth=sdf.format(cal.getTime());
               testYear = cal.get(GregorianCalendar.YEAR);
              int nextYear = cal.get(GregorianCalendar.YEAR)+1;
              JLabel lblYear = new JLabel(""+testYear);
              JLabel jl = new JLabel(testMonth, JLabel.CENTER);
              add(jl,gbc);
              gbc.gridwidth=1;
                 gbc.gridy=1;
              for (int i=0; i<7; i++)
                    gbc.gridx=i;
                    add(new JLabel(DOW, JLabel.CENTER),gbc);
              gbc.gridx = cal.get(GregorianCalendar.DAY_OF_WEEK)-1;
         gbc.gridy++;
              int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
              for (int i=1; i<=daysInMonth; i++)
              JButton jb = new JButton(""+i);
              jb.setBackground(Color.white);
              jb.setForeground(Color.blue);
              jb.addActionListener(this);
              //jb.setBorder(BorderFactory.createRaisedBevelBorder());
              add(jb,gbc);
              if (++gbc.gridx==7)
                   gbc.gridx=0;
                   gbc.gridy++;
         public void actionPerformed(ActionEvent event)
              String command = event.getActionCommand();
              if(event.getSource() instanceof JButton)
                   System.out.println("Button:"+command);
                   String text = jl.getText();     
                   System.out.println("Month:"+text);
                   System.out.println("Year:"+testYear);

    Ok, the last one worked but now one of my labels won't change color even after jl.setOpaque(true).
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.awt.event.*;
    public class MyCalendar extends javax.swing.JApplet  {
           public void init()
             Container content = getContentPane();
             JPanel calendars = new JPanel(new GridLayout(0,1));
             JScrollPane jsp = new JScrollPane(calendars);
             content.add(jsp, BorderLayout.CENTER);
             GregorianCalendar gc = new GregorianCalendar();
              //gc.set(GregorianCalendar.DAY_OF_YEAR,1);c
              gc.set(GregorianCalendar.DAY_OF_MONTH,1);     
                for (int i=0; i<12; i++)
               calendars.setOpaque(true); //this worked
               calendars.add(new CalendarPanel(gc));
               gc.add(GregorianCalendar.MONTH, 1);
    class CalendarPanel extends JPanel implements ActionListener
           private JLabel jl;
           private int testYear;
           private final static String[] DOW = {"S","M","T","W","T","F","S"};
           SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
           GridBagConstraints gbc = new GridBagConstraints(0,0,7,1,1.0,1.0,GridBagConstraints.CENTER,
              GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0);
           public CalendarPanel(GregorianCalendar cal)
              setLayout(new GridBagLayout());
              setBorder(BorderFactory.createEtchedBorder());
              setBackground(Color.white);
              //get the month name
              String testMonth=sdf.format(cal.getTime());
               testYear = cal.get(GregorianCalendar.YEAR);
              int nextYear = cal.get(GregorianCalendar.YEAR)+1;
              JLabel lblYear = new JLabel(""+testYear);
              JLabel jl = new JLabel(testMonth, JLabel.CENTER);
              jl.setOpaque(true); //only works in appletviewer NOT html
              jl.setBackground(Color.red);
              add(jl,gbc);
              gbc.gridwidth=1;
                 gbc.gridy=1;
              for (int i=0; i<7; i++)
                    gbc.gridx=i;
                    add(new JLabel(DOW, JLabel.CENTER),gbc);
              gbc.gridx = cal.get(GregorianCalendar.DAY_OF_WEEK)-1;
         gbc.gridy++;
              int daysInMonth = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
              for (int i=1; i<=daysInMonth; i++)
              JButton jb = new JButton(""+i);
              jb.setBackground(Color.white);
              jb.setForeground(Color.blue);
              jb.addActionListener(this);
              jb.setBorder(BorderFactory.createRaisedBevelBorder());
              add(jb,gbc);
              if (++gbc.gridx==7)
                   gbc.gridx=0;
                   gbc.gridy++;
         public void actionPerformed(ActionEvent event)
              String command = event.getActionCommand();
              if(event.getSource() instanceof JButton)
                   System.out.println("Button:"+command);
                   String text = jl.getText();     
                   System.out.println("Month:"+text);
                   System.out.println("Year:"+testYear);
    [\code]

  • JComponent.setbackground(Color.BLACK) is NOT working

    I am creating Space Invaders game and have GamePanel as my JComponent, named panel. The background is not changing for sum reason though???
    import java.awt.*;
    import javax.swing.*;
    public class SpaceInvaders{
         //variables
         public static final int WIDTH = 800;
         public static final int HEIGHT = 800;
         GamePanel panel;
         public SpaceInvaders()
              //create frame
              JFrame demoFrame = new JFrame("Space Invaders");
              demoFrame.setBounds(0,0,WIDTH,HEIGHT);
              demoFrame.setVisible(true);
              demoFrame.setResizable(false);
              demoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              demoFrame.setBackground(Color.BLACK);
              //create panel
              GamePanel panel = new GamePanel(this);
              panel.setBackground(Color.BLACK);
              demoFrame.add(panel);
              //add buttons
              JButton startButton = new JButton("Start");
              startButton.setEnabled(true);
              JButton stopButton = new JButton("Stop");
              stopButton.setEnabled(true);
    ..... import java.awt.*;
    import javax.swing.*;
    import java.awt.Image;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferStrategy;
    import javax.swing.*;
    import java.awt.event.*;
    public class GamePanel extends JComponent implements KeyListener, ActionListener
         SpaceInvaders game;
         static Player player1;
         Bullets bullet;
         private BufferStrategy strategy;
         static int alienNum = 36;
         static int alienRow = 6;
         static int alienCol = 6;
         static Aliens[][] aliens;
         static Bullets[] bullets;
         private Timer timer;
         int bulletNum=0;
         public GamePanel(SpaceInvaders game)
              this.game = game;
              player1 = new Player(this);
              player1.start();
              aliens = new Aliens[alienRow][alienCol];
              for(int i=0; i<alienRow; i++)
                   for(int j=0; j<alienCol; j++){
                        aliens[i][j] = new Aliens(this);
                        aliens[i][j].setX(i*50);
                        aliens[i][j].setY(j*50);
              bullets = new Bullets[5];
                   bullets[0]=new Bullets(this);
              timer=new Timer(500, this);
              //timer.setDelay(500);
              timer.start();
              this.setFocusable(true);
            this.addKeyListener(this);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Image pic1 = player1.getImage();
    ...........

    I changed the GamePanel class to extend JPanel instead of extend JComponent and it works now. Didnt realise JComponent had no paint functions.. Thanks for your help.
    import java.awt.image.BufferStrategy;
    import javax.swing.*;
    import java.awt.event.*;
    public class GamePanel extends JPanel implements KeyListener, ActionListener
         SpaceInvaders game;
         static Player player1;
         Bullets bullet;
         private BufferStrategy strategy;

  • JLabel.setBackground(Color.red) not working

    Hi, I am using the (JLabel) lblPrmf.setBackground(Color.RED), but the label is not colored. Here is my program:
    import java.util.*;
    import javax.swing.*; //JFrame and JPanel etc...
    import java.awt.*; //BorderLayout and Container etc....
    import java.awt.Color;
    import java.awt.event.*; //ActionListener og WindowAdapter
    public class AllVac extends JFrame
    //Define JLabel
    private JLabel lblDays;
    private JLabel lblAbs;
    private JLabel lblPrmf;
    //Define JButton
    private JButton month;
    private JButton back;
    private JButton forward;
    //Define JPanel
    private JPanel south;
    private JPanel north;
    public AllVac()
    // JFrame jf = new JFrame("Vacation for the Stavanger Team ");
    Container c = getContentPane();
    // c.setTitle("Vacation for the Stavanger Team ");
    c.setLayout(new BorderLayout());
    c.add(new ShowNorth(), BorderLayout.NORTH);
    c.add(new ShowSouth(), BorderLayout.SOUTH);
    pack();
    setVisible(true);
    addWindowListener(new Close());
    public static void main(String args[])
    AllVac a = new AllVac();
    public class ShowNorth extends JPanel
    public ShowNorth()
         north = new JPanel(new GridLayout(1, 3));
         month = new JButton("August 2006");
         back = new JButton("<<");
         forward = new JButton(">>");
         north.add(back);
         north.add(month);
         north.add(forward);
         add(north);
    public class ShowSouth extends JPanel
    public ShowSouth()
         int days = 31;
         south = new JPanel(new GridLayout(16, days+1));
    //Arrange the days
    for ( int i = 1; i<(days+1); i++)
    lblDays = new JLabel(" " + Integer.toString(i));
    lblDays.setBorder(BorderFactory.createLineBorder(Color.red));
    south.add(lblDays);
    add(south, BorderLayout.LINE_START);
    //Fill in the names and vacation days
    for ( int i = 1; i<(days+1); i++)
    lblAbs = new JLabel(" ");
    south.add(lblAbs);
    add(south, BorderLayout.LINE_START);
    for (int j = 0; j<14; j++)
    for ( int i = 1; i<days+1; i++)
    String v = "v";
    lblPrmf = new JLabel(" " + v + " ");
    lblPrmf.setBackground(Color.RED);
    lblPrmf.setBorder(BorderFactory.createLineBorder(Color.blue));
    lblPrmf.setBackground(Color.RED);
    lblPrmf.repaint();
    south.add(lblPrmf);
    add(south);
    public class Close extends WindowAdapter
    public void windowClosing(WindowEvent c)
    System.exit(0);
    }

    You are building a GUI with Swing components. Why would you ask the question in the general programming forum???? People there may never have built a GUI or heard of Swing.
    Concepts of creating GUI components adding then to a GUI, dealing with models, listening to events and responding to the events are all techniques related to GUI programming. Even Swing programming is different from AWT programming in some cases.
    So when you topic title says. "I have a problem, with a Swing (JLabel) component", or "How do I change a JTable in a JScrollPane" where do you think the question should be asked. Maybe its just me but I would think the Swing forum is where you would find the experts, or at least people who think they know something about Swing.
    Your previous posting on "display a button on a background image" was not very clear. You use an Applet and Panel which are an AWT components. But then you are also using JFrame and JButton which are Swing components. Since you posted the question in the general programming forum, I had no idea whether you where attempting to write an AWT or a Swing application so I ignored the posting.

  • 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

  • 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.

  • 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