You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConcurrentClassDefinitionTest.java 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package javassist;
  2. import javassist.bytecode.ClassFile;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.junit.runners.Parameterized;
  6. @RunWith(Parameterized.class)
  7. public class ConcurrentClassDefinitionTest {
  8. @Parameterized.Parameter
  9. public int N;
  10. @Parameterized.Parameters
  11. public static Object[] data() {
  12. return new Object[] {
  13. 1, // single threaded - should pass
  14. Runtime.getRuntime().availableProcessors() * 2
  15. };
  16. }
  17. @Test
  18. public void showDefineClassRaceCondition() throws Exception{
  19. Worker[] workers = new Worker[N];
  20. for (int i = 0; i < N; i++) {
  21. workers[i] = new Worker(N + "_ " + i, 100);
  22. workers[i].start();
  23. }
  24. for (Worker w : workers) {
  25. w.join();
  26. }
  27. for (Worker w : workers) {
  28. if (w.e != null) {
  29. throw w.e;
  30. }
  31. }
  32. }
  33. private static class Worker extends Thread {
  34. String id;
  35. int count;
  36. Exception e;
  37. Worker(String id, int count) {
  38. this.id = id;
  39. this.count = count;
  40. }
  41. @Override
  42. public void run() {
  43. try {
  44. for (int i = 0; i < count; i++) {
  45. Class c = makeClass(id + "_" + i);
  46. assert c != null;
  47. }
  48. } catch (Exception e) {
  49. this.e = e;
  50. }
  51. }
  52. @Override
  53. public void interrupt() {
  54. super.interrupt();
  55. }
  56. }
  57. private static Class makeClass(String id) throws Exception {
  58. ClassFile cf = new ClassFile(
  59. false, "com.example.JavassistGeneratedClass_" + id, null);
  60. ClassPool classPool = ClassPool.getDefault();
  61. return classPool.makeClass(cf).toClass();
  62. }
  63. }