Java Face questions and Answers (III.)

Source: Internet
Author: User
Tags readline

1. This code works in most cases, but in some cases it can be problematic. When will there be any problems? How to fix?

 Public classMystack {Privatelist<string> list =NewArraylist<string>();  Public synchronized voidpush (String value) {synchronized( This) {List.add (value);          Notify (); }      }         Public synchronizedString pop ()throwsinterruptedexception {synchronized( This) {              if(List.size () <= 0) {wait (); }              returnList.remove (List.size ()-1); }      }  }

List.remove (List.size ()-1); This code might throw an array subscript out of bounds

Reason ( answer from Internet, non-personal answer ):
Let's say one of these situations! There may be many problems, but the principle is similar. The following labels represent the sequencing of the sequence of the program.
1, the value of the list at initialization is 0, then thread 1 calls the pop, then wait, and then release the lock.
2, thread 2 calls push, thread 3 calls pop before notify (remember that this time thread 1 has not been woken up, still in wait), at which point 3 is suspended because of waiting for the lock, or spin, anyway, is waiting for the lock to be available.
3, then thread 2 continues to execute, notify is executed (but at this time thread 1 will not wake up, because the lock is also 2 occupied), thread 2 exits the push method, releasing the built-in lock, at this point, thread 1 and thread 3 are in the built-in lock waiting queue. Because synchronized is unable to guarantee the fairness of thread contention, thread 1 and thread 3 can be locked.
4, assume that thread 1 competes to the lock, does not have a problem, the normal removal of the list value, and then remove, after the execution of the thread 3 execution, also wait to live.
5, assuming that thread 3 competes to the lock, the problem comes, thread 3 will determine that the size of the list is not 0, so remove, so the list of size is 0, and then thread 3 release the lock, this time, thread 1 will be locked, then wake up from wait, continue to execute, Then directly call the list of remove, because the list of size=0, then remove (-1), the cross-boundary error is generated.

Improved:

Improved 1,—— minimal code churn, check list.size==0 before remove
Improved 2,--remove the second lock check in the push and pop methods, I did not find out what the lock would do, but instead consumed performance. Of course, there is still a plan 1 judgment (thanks to the first floor reminder).
Improved 3,--redesign, if I were to design such a producer, consumer model. I prefer to use linkedblockingqueue, which has a take method to block the consumer until the queue is available. And there are offer methods to block the producer until the queue can be inserted, which effectively blocks oom.

2, write a piece of code to realize the bank transfer function, from the transfer account to deduct the transfer amount, to transfer account to increase the transfer amount, to ensure that two operations are either successful at the same time, or fail at the same time

 Public InterfaceItransfer {/*** Fromaccountid Transfer Account Toaccountid transfer amount to account amount **/     Public voidTransferinner (String Fromaccountid, String toaccountid, BigDecimal amount); /*** External Transfer-out, deduct the transfer amount from the Transfer Account Fromaccountid transfer the account amount Transfer amount **/     Public voidtransferout (String fromaccountid, BigDecimal amount); /*** External Transfer-transfer, add to account transfer Amount Toaccountid transfer amount to account amount transfer*/     Public voidTransferin (String toaccountid, BigDecimal amount);}

This question examines the understanding of affairs. If the turn-out and transfer operations are in the same application, the transaction characteristics of the database can be used to "either succeed at the same time, or fail at the same time"; otherwise it will be solved with the solution of distributed transaction, First digest this article "Distributed System Transaction consistency solution".

3, the implementation of statistics in a directory of each file appears in the number of letters, number, space and number of lines?

/*text content Limited to numbers, letters, and spaces*/ImportJava.io.*;classEx6_5 { Public Static voidMain (string[] args) {String fileName= "C:/hello.txt", line; inti,j,f,k; Try{BufferedReader in=NewBufferedReader (NewFileReader (fileName)); Line= In.readline ();//read a line of content              while(Line! =NULL ) {                     if(Character.isletter (line)) I++; Else if(Character.isdigit (line)) J++; ElseF++; Line=In.readline (); K++} in.close (); System.out.println ("Letter" +i+ "number" +j+ "Space" +j+ "number of lines" +k)}Catch(IOException iox) {System.out.println ("Problem reading" +fileName); }    }}

4, if there is a string "6sabcsfs33", with the most rapid way to remove the character "ab3", can not use the Java built-in string method (Indeof,substring,replaceall, etc.)

  String regx = "[^a|b|3]";   = "6sabcsssfsfs33";   = Pattern.compile (regx);   = P.matcher (temp);    while (M.find ()) {   System.out.print (M.group ());  }


Java Face questions and Answers (III.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.