• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

on critical question

Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

is this wil cause deadlock or not please expalain

1. public class SyncTest{
2. public static void main(String[] args) {
3. final StringBuffer s1= new StringBuffer();
4. final StringBuffer s2= new StringBuffer();
5. new Thread () {
6. public void run() {
7. synchronized(s1) {
8. s2.append("A");
9. synchronized(s2) {
10. s2.append("B");
11. System.out.print(s1);
12. System.out.print(s2);
13. }
14. }
15. }
16. }.start();
17. new Thread() {
18. public void run() {
19. synchronized(s2) {
20. s2.append("C");
21. synchronized(s1) {
22. s1.append("D");
23. System.out.print(s2);
24. System.out.print(s1);
25. }
26. }
27. }
28. }.start();
29. }
30. }
Which two statements are true? (Choose Two)
A. The program prints "ABBCAD"
B. The program prints "CDDACB"
C. The program prints "ADCBADBC"
D. The output is a non-deterministic point because of a possible deadlock condition.
E. The output is dependent on the threading model of the system the program is
running on.

velan vel
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi ranchers,

by simply looking at the code in main, i was under impression of possible deadlock condition. however by running program, it runs fine without any deadlock.

what's heppening here is i guess that as the thread first declared, defined and run is having a very small code to execute in its run() method, now to create a thread, it takes few efforts in case of CPU and memory cycle by JVM, before the second thread is run, first thread executes its run() method and leaves locks on monitor of s1 and s2. and then newly created second thread runs it run() method.

if any forever loop is introduced in run() method of either thread, a deadlock can occur. but as far answers to this question is concerned, i would go with D and E.

however, i think my understanding is not up to the marks as far as this question is concerned, please correct it.

    Bookmark Topic Watch Topic
  • New Topic