Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. package Task2;
  2.  
  3. public class SolutionWithNoSynchronization implements MemoryWrapper{
  4.  
  5. private MemorySegment _memory = null;
  6. private boolean writing = false;
  7. private int readers = 0, writers = 0;
  8.  
  9. public SolutionWithNoSynchronization(){
  10. _memory = new MemorySegment();
  11. }
  12.  
  13. public void read(Process p){
  14. p.setState("wantread");
  15. beforeRead();
  16. p.setState("reading");
  17. _memory.read();
  18. p.setState("idle");
  19. afterRead();
  20. }
  21.  
  22. public void write(Process p){
  23. p.setState("wantwrite");
  24. beforeWrite();
  25. p.setState("writing");
  26. _memory.write();
  27. p.setState("idle");
  28. afterWrite();
  29. }
  30.  
  31. private synchronized void beforeRead() {
  32. while(!okToRead()) {
  33. try {
  34. wait();
  35. } catch (InterruptedException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. }
  40. readers++;
  41. }
  42.  
  43. private synchronized void afterRead() {
  44. readers--;
  45. notifyAll();
  46. }
  47.  
  48. private synchronized void beforeWrite() {
  49. while(!okToWrite()) {
  50. try {
  51. wait();
  52. } catch (InterruptedException e) {
  53. // TODO Auto-generated catch block
  54. e.printStackTrace();
  55. }
  56. }
  57. writing = true;
  58. }
  59.  
  60. private synchronized void afterWrite() {
  61. writing = false;
  62. notifyAll();
  63. }
  64.  
  65. private boolean okToRead() {
  66. return !writing;
  67. }
  68.  
  69. private boolean okToWrite() {
  70. return !writing && readers == 0;
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement