Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > synchronizing access to static variables

Thread Tools

synchronizing access to static variables

Posts: n/a
I copied and pasted some DES crypto code from the internet. I am trying
to transform the class to be more utility-based instead of having to
instantiate a copy each time. I am not great at Java threads. Can you
please examine the (small amount of) code below and tell me if the
synchronization is optimal? Please feel free to make any other comments
about how I can improve the class.

public final class DESCrypto {
private static final Log logger =
private static final String DES = "DES";
private static final String UTF8 = "UTF8";

private static final Cipher ecipher;
private static final Cipher dcipher;

private DESCrypto() {
throw new UnsupportedOperationException("do not use");

static {
try {
// load the stored key
InputStream keyis =
DESCrypto.class.getResourceAsStream("DESCrypto.key ");
ByteArrayOutputStream byteos = new ByteArrayOutputStream();
int b;
while ((b = != -1) {
SecretKey key = new SecretKeySpec(byteos.toByteArray(),

// to generate a new key, use:
// SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// byte[] keyout = key.getEncoded();
// FileOutputStream keyfos = new
// keyfos.write(keyout);
// keyfos.close();

// create and initialize ciphers
ecipher = Cipher.getInstance(DES);
dcipher = Cipher.getInstance(DES);
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (Exception ex) {
throw new RuntimeException(ex);

public static String encrypt(String str) {
try {
synchronized (DESCrypto.class) {
byte[] utf8 = str.getBytes(UTF;
byte[] enc = ecipher.doFinal(utf;
return new sun.misc.BASE64Encoder().encode(enc);
} catch (Exception ex) {
throw new RuntimeException(ex);

public static String decrypt(String str) {
try {
synchronized (DESCrypto.class) {
byte[] dec = new
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, UTF;
} catch (Exception ex) {
throw new RuntimeException(ex);

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
How can I access non-static variables from static funcition? Neviton C++ 9 09-17-2007 10:21 PM
Synchronizing access to resources in Java dlugi Java 9 10-04-2006 09:03 AM
Synchronizing 2 Processes to access a text file simultaneously arvind MCAD 0 01-13-2005 10:02 AM
Instantiating a static class( Class with all static members - methods and variables) SaravanaKumar Java 6 10-19-2004 08:20 AM
synchronizing static methods? Paul Tomblin Java 1 07-10-2003 02:58 PM