• Post Reply Bookmark Topic Watch Topic
  • New Topic

cuncurrency problems with class Properties

 
Andy Jung
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

having a class Properties (to work with user configuration properties) causes concurrency problems in my mutlithreaded Swing application.
This is due to the fact that methods setProperty and getProperty are not synchronized.

I tried to solve this problem by creating a synchronized version of my Properties class

however, at runtime this results in a ClassCastException:


What's wrong and how can I produce a synchronized version of class Properties then?

Thanks,
Andy
 
Andy Jung
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got the solution:

Properties implements interface Map<String, String>.
Collections.synchronizedMap(), however, returns a Map<Object, Object>, so casting to Properties won't be possible (-> covariance of generics).

Since Properties also extends class Hashtable<String, String> and Hashtable is synchronized use its put() and get()-methods instead of
the unsynchronized setProperty()- and getProperty()-methods of class Properties.
 
Ajay Saxena
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Watch out for check-then-put pattern in your code which requires external synchronization.
e.g let's say we have the following piece of code

If the application is so designed that the method foo() could be invoked on the same object in multiple threads,it's not sufficient to just declare the map as a synchronized collection,as done in line # 02
Try reasoning out why.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!